Esempio n. 1
0
static void print_cpu(struct seq_file *m, int cpu)
{
	struct rq *rq = cpu_rq(cpu);
	unsigned long flags;

#ifdef CONFIG_X86
	{
		unsigned int freq = cpu_khz ? : 1;

		SEQ_printf(m, "cpu#%d, %u.%03u MHz\n",
			   cpu, freq / 1000, (freq % 1000));
	}
#else
	SEQ_printf(m, "cpu#%d\n", cpu);
#endif

#define P(x)								\
do {									\
	if (sizeof(rq->x) == 4)						\
		SEQ_printf(m, "  .%-30s: %ld\n", #x, (long)(rq->x));	\
	else								\
		SEQ_printf(m, "  .%-30s: %Ld\n", #x, (long long)(rq->x));\
} while (0)

#define PN(x) \
	SEQ_printf(m, "  .%-30s: %Ld.%06ld\n", #x, SPLIT_NS(rq->x))

	P(nr_running);
	SEQ_printf(m, "  .%-30s: %lu\n", "load",
		   rq->load.weight);
	P(nr_switches);
	P(nr_load_updates);
	P(nr_uninterruptible);
	PN(next_balance);
	P(curr->pid);
	PN(clock);
	P(cpu_load[0]);
	P(cpu_load[1]);
	P(cpu_load[2]);
	P(cpu_load[3]);
	P(cpu_load[4]);
#undef P
#undef PN

#ifdef CONFIG_SCHEDSTATS
#define P(n) SEQ_printf(m, "  .%-30s: %d\n", #n, rq->n);
#define P64(n) SEQ_printf(m, "  .%-30s: %Ld\n", #n, rq->n);

	P(yld_count);

	P(sched_count);
	P(sched_goidle);
#ifdef CONFIG_SMP
	P64(avg_idle);
#endif

	P(ttwu_count);
	P(ttwu_local);

#undef P
#undef P64
#endif
	spin_lock_irqsave(&sched_debug_lock, flags);
	print_cfs_stats(m, cpu);
	print_rt_stats(m, cpu);

	rcu_read_lock();
	print_rq(m, rq, cpu);
	rcu_read_unlock();
	spin_unlock_irqrestore(&sched_debug_lock, flags);
	SEQ_printf(m, "\n");
}
Esempio n. 2
0
        uint8_t delta = a - b;
        uint8_t scaled = scale8( delta, frac);
        result = a - scaled;
    }
    return result;
}

int16_t inoise16_raw(uint32_t x, uint32_t y, uint32_t z)
{
  // Find the unit cube containing the point
  uint8_t X = (x>>16)&0xFF;
  uint8_t Y = (y>>16)&0xFF;
  uint8_t Z = (z>>16)&0xFF;

  // Hash cube corner coordinates
  uint8_t A = P(X)+Y;
  uint8_t AA = P(A)+Z;
  uint8_t AB = P(A+1)+Z;
  uint8_t B = P(X+1)+Y;
  uint8_t BA = P(B) + Z;
  uint8_t BB = P(B+1)+Z;

  // Get the relative position of the point in the cube
  uint16_t u = x & 0xFFFF;
  uint16_t v = y & 0xFFFF;
  uint16_t w = z & 0xFFFF;

  // Get a signed version of the above for the grad function
  int16_t xx = (u >> 1) & 0x7FFF;
  int16_t yy = (v >> 1) & 0x7FFF;
  int16_t zz = (w >> 1) & 0x7FFF;
Esempio n. 3
0
/* when vectorize = 0 */
void c_out(const char* prefix)
{
#if NMODL
	Item *q;
	extern int point_process;
#endif

	Fprintf(fcout, "/* Created by Language version: %s */\n", nmodl_version_);
	Fflush(fcout);

#if VECTORIZE
	if (vectorize) {
		vectorize_do_substitute();
		kin_vect2();	/* heh, heh.. bet you can't guess what this is */
		c_out_vectorize(prefix);
		return;
	}
#endif
#if VECTORIZE
	P("/* NOT VECTORIZED */\n");
#endif
	Fflush(fcout);
	/* things which must go first and most declarations */
#if SIMSYS
	P("#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include \"mathlib.h\"\n");
	P("#include \"common.h\"\n#include \"softbus.h\"\n");
	P("#include \"sbtypes.h\"\n#include \"Solver.h\"\n");
#else
	P("#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include \"scoplib_ansi.h\"\n");
	P("#undef PI\n");
	P("#define nil 0\n");
P("#include \"md1redef.h\"\n");
P("#include \"section.h\"\n");
P("#include \"nrniv_mf.h\"\n");
P("#include \"md2redef.h\"\n");

#endif
	printlist(defs_list);
	printlist(firstlist);
	P("static int _reset;\n");
#if NMODL
	P("static ");
#endif	
	if (modelline) {
		Fprintf(fcout, "char *modelname = \"%s\";\n\n", modelline);
	} else {
		Fprintf(fcout, "char *modelname = \"\";\n\n");
	}
	Fflush(fcout);		/* on certain internal errors partial output
				 * is helpful */
	P("static int error;\n");
#if NMODL
	P("static ");
#endif	
	P("int _ninits = 0;\n");
	P("static int _match_recurse=1;\n");
#if NMODL
	P("static void ");
#endif	
	P("_modl_cleanup(){ _match_recurse=1;}\n");
	/*
	 * many machinations are required to make the infinite number of
	 * definitions involving _p in defs.h to be invisible to the user 
	 */
	/*
	 * This one allows scop variables in functions which do not have the
	 * p array as an argument 
	 */
#if SIMSYS || HMODL || NMODL
#else
	P("static double *_p;\n\n");
#endif
	funcdec();
	Fflush(fcout);

	/*
	 * translations of named blocks into functions, procedures, etc. Also
	 * some special declarations used by some blocks 
	 */
	printlist(procfunc);
	Fflush(fcout);

	/* Initialization function must always be present */
#if NMODL
	P("\nstatic void initmodel() {\n  int _i; double _save;");
#endif
#if SIMSYS || HMODL
	P("\ninitmodel() {\n  int _i; double _save;");
#endif
#if (!(SIMSYS || HMODL || NMODL))
	P("\ninitmodel(_pp) double _pp[]; {\n int _i; double _save; _p = _pp;");
#endif
#if !NMODL
	P("_initlists();\n");
#endif
	P("_ninits++;\n");
	P(saveindep); /*see solve.c; blank if not a time dependent process*/
	P("{\n");
	initstates();
	printlist(initfunc);
	if (match_bound) {
		P("\n_init_match(_save);");
	}
	P("\n}\n}\n");
	Fflush(fcout);

#if NMODL
	/* generation of initmodel interface */
#if VECTORIZE
	P("\nstatic void nrn_init(_NrnThread* _nt, _Memb_list* _ml, int _type){\n");
	  P("Node *_nd; double _v; int* _ni; int _iml, _cntml;\n");
	  P("#if CACHEVEC\n");
	  P("    _ni = _ml->_nodeindices;\n");
	  P("#endif\n");
	  P("_cntml = _ml->_nodecount;\n");
	  P("for (_iml = 0; _iml < _cntml; ++_iml) {\n");
	  P(" _p = _ml->_data[_iml]; _ppvar = _ml->_pdata[_iml];\n");
#else
	P("\nstatic nrn_init(_prop, _v) Prop *_prop; double _v; {\n");
	P(" _p = _prop->param; _ppvar = _prop->dparam;\n");
#endif
	if (debugging_ && net_receive_) {
		P(" _tsav = -1e20;\n");
	}
	if (!artificial_cell) {ext_vdef();}
	if (!artificial_cell) {P(" v = _v;\n");}
	printlist(get_ion_variables(1));
	P(" initmodel();\n");
	printlist(set_ion_variables(2));
#if VECTORIZE
	P("}}\n");
#else
	P("}\n");
#endif

	/* standard modl EQUATION without solve computes current */
	P("\nstatic double _nrn_current(double _v){double _current=0.;v=_v;");
#if CVODE
	if (cvode_nrn_current_solve_) {
		fprintf(fcout, "if (cvode_active_) { %s(); }\n", cvode_nrn_current_solve_->name);
	}
#endif
	P("{");
	if (currents->next != currents) {
		printlist(modelfunc);
	}
	ITERATE(q, currents) {
		Sprintf(buf, " _current += %s;\n", SYM(q)->name);
		P(buf);
	}
void alphatFixedDmdtWallBoilingWallFunctionFvPatchScalarField::updateCoeffs()
{
    if (updated())
    {
        return;
    }

    // Lookup the fluid model
    const ThermalPhaseChangePhaseSystem
    <
        MomentumTransferPhaseSystem<twoPhaseSystem>
    >& fluid =
        refCast
        <
            const ThermalPhaseChangePhaseSystem
            <
                MomentumTransferPhaseSystem<twoPhaseSystem>
            >
        >
        (
            db().lookupObject<phaseSystem>("phaseProperties")
        );

    const phaseModel& liquid
    (
        fluid.phase1().name() == dimensionedInternalField().group()
      ? fluid.phase1()
      : fluid.phase2()
    );

    const label patchi = patch().index();

    // Retrieve turbulence properties from model
    const compressibleTurbulenceModel& turbModel =
        db().lookupObject<compressibleTurbulenceModel>
        (
            IOobject::groupName
            (
                compressibleTurbulenceModel::propertiesName,
                dimensionedInternalField().group()
            )
        );

    const scalar Cmu25 = pow025(Cmu_);

    const scalarField& y = turbModel.y()[patchi];

    const tmp<scalarField> tmuw = turbModel.mu(patchi);
    const scalarField& muw = tmuw();

    const tmp<scalarField> talphaw = liquid.thermo().alpha(patchi);
    const scalarField& alphaw = talphaw();

    scalarField& alphatw = *this;

    const tmp<volScalarField> tk = turbModel.k();
    const volScalarField& k = tk();
    const fvPatchScalarField& kw = k.boundaryField()[patchi];

    const fvPatchVectorField& Uw = turbModel.U().boundaryField()[patchi];
    const scalarField magUp(mag(Uw.patchInternalField() - Uw));
    const scalarField magGradUw(mag(Uw.snGrad()));

    const fvPatchScalarField& rhow = turbModel.rho().boundaryField()[patchi];
    const fvPatchScalarField& hew =
        liquid.thermo().he().boundaryField()[patchi];

    const fvPatchScalarField& Tw =
        liquid.thermo().T().boundaryField()[patchi];

    scalarField Tp(Tw.patchInternalField());

    // Heat flux [W/m2] - lagging alphatw
    const scalarField qDot
    (
        (alphatw + alphaw)*hew.snGrad()
    );

    scalarField uTau(Cmu25*sqrt(kw));

    scalarField yPlus(uTau*y/(muw/rhow));

    scalarField Pr(muw/alphaw);

    // Molecular-to-turbulent Prandtl number ratio
    scalarField Prat(Pr/Prt_);

    // Thermal sublayer thickness
    scalarField P(this->Psmooth(Prat));

    scalarField yPlusTherm(this->yPlusTherm(P, Prat));

    scalarField alphatConv(this->size(), 0.0);

    // Populate boundary values
    forAll(alphatw, faceI)
    {
        // Evaluate new effective thermal diffusivity
        scalar alphaEff = 0.0;
        if (yPlus[faceI] < yPlusTherm[faceI])
        {
            scalar A = qDot[faceI]*rhow[faceI]*uTau[faceI]*y[faceI];
            scalar B = qDot[faceI]*Pr[faceI]*yPlus[faceI];
            scalar C = Pr[faceI]*0.5*rhow[faceI]*uTau[faceI]*sqr(magUp[faceI]);
            alphaEff = A/(B + C + VSMALL);
        }
        else
        {
            scalar A = qDot[faceI]*rhow[faceI]*uTau[faceI]*y[faceI];
            scalar B =
                qDot[faceI]*Prt_*(1.0/kappa_*log(E_*yPlus[faceI]) + P[faceI]);
            scalar magUc =
                uTau[faceI]/kappa_*log(E_*yPlusTherm[faceI]) - mag(Uw[faceI]);
            scalar C =
                0.5*rhow[faceI]*uTau[faceI]
               *(Prt_*sqr(magUp[faceI]) + (Pr[faceI] - Prt_)*sqr(magUc));
            alphaEff = A/(B + C + VSMALL);
        }

        // Update convective heat transfer turbulent thermal diffusivity
        alphatConv[faceI] = max(0.0, alphaEff - alphaw[faceI]);
    }
Esempio n. 5
0
int
catmouse(int nargs,
         char ** args)
{
  int catindex, mouseindex, error;
  int i;
  int mean_cat_wait_usecs, mean_mouse_wait_usecs;
  time_t before_sec, after_sec, wait_sec;
  uint32_t before_nsec, after_nsec, wait_nsec;
  int total_bowl_milliseconds, total_eating_milliseconds, utilization_percent;

  /* check and process command line arguments */
  if ((nargs != 9) && (nargs != 5)) {
    kprintf("Usage: <command> NUM_BOWLS NUM_CATS NUM_MICE NUM_LOOPS\n");
    kprintf("or\n");
    kprintf("Usage: <command> NUM_BOWLS NUM_CATS NUM_MICE NUM_LOOPS ");
    kprintf("CAT_EATING_TIME CAT_SLEEPING_TIME MOUSE_EATING_TIME MOUSE_SLEEPING_TIME\n");
    return 1;  // return failure indication
  }

  /* check the problem parameters, and set the global variables */
  NumBowls = atoi(args[1]);
  if (NumBowls <= 0) {
    kprintf("catmouse: invalid number of bowls: %d\n",NumBowls);
    return 1;
  }
  NumCats = atoi(args[2]);
  if (NumCats < 0) {
    kprintf("catmouse: invalid number of cats: %d\n",NumCats);
    return 1;
  }
  NumMice = atoi(args[3]);
  if (NumMice < 0) {
    kprintf("catmouse: invalid number of mice: %d\n",NumMice);
    return 1;
  }
  NumLoops = atoi(args[4]);
  if (NumLoops <= 0) {
    kprintf("catmouse: invalid number of loops: %d\n",NumLoops);
    return 1;
  }

  if (nargs == 9) {
    CatEatTime = atoi(args[5]);
    if (CatEatTime < 0) {
      kprintf("catmouse: invalid cat eating time: %d\n",CatEatTime);
      return 1;
    }
  
    CatSleepTime = atoi(args[6]);
    if (CatSleepTime < 0) {
      kprintf("catmouse: invalid cat sleeping time: %d\n",CatSleepTime);
      return 1;
    }
  
    MouseEatTime = atoi(args[7]);
    if (MouseEatTime < 0) {
      kprintf("catmouse: invalid mouse eating time: %d\n",MouseEatTime);
      return 1;
    }
  
    MouseSleepTime = atoi(args[8]);
    if (MouseSleepTime < 0) {
      kprintf("catmouse: invalid mouse sleeping time: %d\n",MouseSleepTime);
      return 1;
    }
  }

  if ((NumMice >= INVALID_ANIMAL_NUM) || (NumCats >= INVALID_ANIMAL_NUM)) {
    panic("Trying to use too many cats or mice: limit =  %d\n", INVALID_ANIMAL_NUM);
  }

  kprintf("Using %d bowls, %d cats, and %d mice. Looping %d times.\n",
          NumBowls,NumCats,NumMice,NumLoops);
  kprintf("Using cat eating time %d, cat sleeping time %d\n", CatEatTime, CatSleepTime);
  kprintf("Using mouse eating time %d, mouse sleeping time %d\n", MouseEatTime, MouseSleepTime);

  /* create the semaphore that is used to make the main thread
     wait for all of the cats and mice to finish */
  CatMouseWait = sem_create("CatMouseWait",0);
  if (CatMouseWait == NULL) {
    panic("catmouse: could not create semaphore\n");
  }

  /* initialize our simulation state */
  initialize_bowls();

  /* initialize the synchronization functions */
  catmouse_sync_init(NumBowls);

  /* get current time, for measuring total simulation time */
  gettime(&before_sec,&before_nsec);

  /*
   * Start NumCats cat_simulation() threads and NumMice mouse_simulation() threads.
   * Alternate cat and mouse creation.
   */
  for (catindex = 0; catindex < NumCats; catindex++) {
    error = thread_fork("cat_simulation thread", NULL, cat_simulation, NULL, catindex);
    if (error) {
      panic("cat_simulation: thread_fork failed: %s\n", strerror(error));
    }
    if (catindex < NumMice) {
      error = thread_fork("mouse_simulation thread", NULL, mouse_simulation, NULL, catindex);
      if (error) {
	panic("mouse_simulation: thread_fork failed: %s\n",strerror(error));
      }
    } 
  }
  /* launch any remaining mice */
  for(mouseindex = catindex; mouseindex < NumMice; mouseindex++) {
    error = thread_fork("mouse_simulation thread", NULL, mouse_simulation, NULL, mouseindex);
    if (error) {
      panic("mouse_simulation: thread_fork failed: %s\n",strerror(error));
    }
  }
  
  /* wait for all of the cats and mice to finish before
     terminating */  
  for(i=0;i<(NumCats+NumMice);i++) {
    P(CatMouseWait);
  }

  /* get current time, for measuring total simulation time */
  gettime(&after_sec,&after_nsec);
  /* compute total simulation time */
  getinterval(before_sec,before_nsec,after_sec,after_nsec,&wait_sec,&wait_nsec);
  /* compute and report bowl utilization */
  total_bowl_milliseconds = (wait_sec*1000 + wait_nsec/1000000)*NumBowls;
  total_eating_milliseconds = (NumCats*CatEatTime + NumMice*MouseEatTime)*NumLoops*1000;
  if (total_bowl_milliseconds > 0) {
    utilization_percent = total_eating_milliseconds*100/total_bowl_milliseconds;
    kprintf("STATS: Bowl utilization: %d%%\n",utilization_percent);
  }

  /* clean up the semaphore that we created */
  sem_destroy(CatMouseWait);

  /* clean up the synchronization state */
  catmouse_sync_cleanup(NumBowls);

  /* clean up resources used for tracking bowl use */
  cleanup_bowls();

  if (cat_wait_count > 0) {
    /* some rounding error here - not significant if cat_wait_count << 1000000 */
    mean_cat_wait_usecs = (cat_total_wait_secs*1000000+cat_total_wait_nsecs/1000)/cat_wait_count;
    kprintf("STATS: Mean cat waiting time: %d.%d seconds\n",
             mean_cat_wait_usecs/1000000,mean_cat_wait_usecs%1000000);
  }
  if (mouse_wait_count > 0) {
    /* some rounding error here - not significant if mouse_wait_count << 1000000 */
    mean_mouse_wait_usecs = (mouse_total_wait_secs*1000000+mouse_total_wait_nsecs/1000)/mouse_wait_count;
    kprintf("STATS: Mean mouse waiting time: %d.%d seconds\n",
             mean_mouse_wait_usecs/1000000,mean_mouse_wait_usecs%1000000);
  }

  return 0;
}
Esempio n. 6
0
static bRC do_set_scsi_encryption_key(void *value)
{
   DCR *dcr;
   DEVICE *dev;
   DEVRES *device;
   DIRRES *director;
   char StoredVolEncrKey[MAX_NAME_LENGTH];
   char VolEncrKey[MAX_NAME_LENGTH];

   /*
    * Unpack the arguments passed in.
    */
   dcr = (DCR *)value;
   if (!dcr) {
      return bRC_Error;
   }
   dev = dcr->dev;
   if (!dev) {
      return bRC_Error;
   }
   device = dev->device;
   if (!device) {
      return bRC_Error;
   }

   *StoredVolEncrKey = '\0';
   if (!get_volume_encryption_key(dcr, StoredVolEncrKey)) {
      return bRC_Error;
   }

   /*
    * See if a volume encryption key is available.
    */
   if (!*StoredVolEncrKey) {
      Dmsg0(dbglvl, "scsicrypto-sd: No encryption key to load on device\n");
      return bRC_OK;
   }

   /*
    * See if device supports hardware encryption.
    */
   if (!device->drive_crypto_enabled) {
      Dmsg0(dbglvl, "scsicrypto-sd: Trying to load encryption key on drive without support\n");
      Emsg0(M_ERROR, 0,
            _("scsicrypto-sd: Trying to load encryption key on drive without support\n"));
      return bRC_Error;
   }

   /*
    * The key passed from the director to the storage daemon is always base64 encoded.
    */
   base64_to_bin(VolEncrKey, sizeof(VolEncrKey), StoredVolEncrKey, strlen(StoredVolEncrKey));

   /*
    * See if we have an key encryption key in the config then the passed key
    * has been wrapped using RFC3394 key wrapping. We first copy the current
    * wrapped key into a temporary variable for unwrapping.
    */
   if (dcr->jcr && dcr->jcr->director) {
      director = dcr->jcr->director;
      if (director->keyencrkey) {
         char WrappedVolEncrKey[MAX_NAME_LENGTH];

         memcpy(WrappedVolEncrKey, VolEncrKey, MAX_NAME_LENGTH);
         memset(VolEncrKey, 0, MAX_NAME_LENGTH);

         if (aes_unwrap((unsigned char *)director->keyencrkey,
                        DEFAULT_PASSPHRASE_LENGTH / 8,
                        (unsigned char *)WrappedVolEncrKey,
                        (unsigned char *)VolEncrKey) != 0) {
            Dmsg1(dbglvl,
                  "scsicrypto-sd: Failed to unwrap encryption key using %s\n", director->keyencrkey);
            Emsg0(M_ERROR, 0,
                  _("scsicrypto-sd: Failed to unwrap encryption key, probably wrong KeyEncryptionKey in config\n"));
            return bRC_Error;
         }
      }
   }

   Dmsg1(dbglvl, "scsicrypto-sd: Loading new crypto key %s\n", VolEncrKey);

   P(crypto_operation_mutex);
   if (set_scsi_encryption_key(dev->fd(), dev->dev_name, VolEncrKey)) {
      dev->set_crypto_enabled();
      V(crypto_operation_mutex);
      return bRC_OK;
   } else {
      V(crypto_operation_mutex);
      return bRC_Error;
   }
}
int main(int number_of_scan_positions) {


	NEWMAT::Matrix Pg(3,3);
	NEWMAT::Matrix P(2,2);
	double tempAx, tempAy, tempBx, tempBy;
	double Gx, Gy, fi;
	double Px, Py, Pfi;
	Tocka Xp, G;
	Razlomljena_Duzina *map_in_local_frame = new Razlomljena_Duzina[120];
	Razlomljena_Duzina* map= new Razlomljena_Duzina[400];
	int line_counter=0;
	int number_of_lines_in_map=0;
	for (int i=0; i<number_of_scan_positions; i++){

		line_counter=0;
		ifstream file_line ("map_lines_in_local_frame" +IntToString(i)+".txt");

		P << 0 << 0 << 0 << 0;        // set line variance in local frame to 0

		while(!file_line.eof()){

			file_line >> tempAx >> tempAy >> tempBx >> tempBy;

			map_in_local_frame[line_counter].A.push_back(Tocka(tempAx, tempAy));
			map_in_local_frame[line_counter].B.push_back(Tocka(tempBx, tempBy));
			map_in_local_frame[line_counter].postaviVar(P);

			line_counter++;
		}




		file_line.close();

		ifstream file_pose ("pose_with_covariance" +IntToString(i)+".txt");
		file_pose >> Gx >> Gy >> fi;
		G=Tocka (Gx, Gy);

		file_pose >> Px  >> Py >> Pfi;

		Pg << Px<< 0 << 0
		   << 0  << Py <<0
		   << 0  << 0 <<Pfi;

		file_pose.close();




		transformiraj2(map_in_local_frame,line_counter,G,fi,&Xp,Pg);

		map=duzinacat2(map, number_of_lines_in_map, map_in_local_frame, line_counter, &number_of_lines_in_map);


	}

	poklopi_kartu2(map,number_of_lines_in_map);
	Snimi ("final_map.m", map, number_of_lines_in_map);



}
Esempio n. 8
0
b2Vec2 b2WeldJoint::GetReactionForce(float32 inv_dt) const
{
	b2Vec2 P(m_impulse.x, m_impulse.y);
	return inv_dt * P;
}
Esempio n. 9
0
void gtk_setup_config_box(struct controlbox *b, int midsession, void *win)
{
    struct controlset *s, *s2;
    union control *c;
    int i;

    if (!midsession) {
	/*
	 * Add the About button to the standard panel.
	 */
	s = ctrl_getset(b, "", "", "");
	c = ctrl_pushbutton(s, "About", 'a', HELPCTX(no_help),
			    about_handler, P(win));
	c->generic.column = 0;
    }

    /*
     * GTK makes it rather easier to put the scrollbar on the left
     * than Windows does!
     */
    s = ctrl_getset(b, "Window", "scrollback",
		    "Control the scrollback in the window");
    ctrl_checkbox(s, "Scrollbar on left", 'l',
		  HELPCTX(no_help),
		  conf_checkbox_handler,
                  I(CONF_scrollbar_on_left));
    /*
     * Really this wants to go just after `Display scrollbar'. See
     * if we can find that control, and do some shuffling.
     */
    for (i = 0; i < s->ncontrols; i++) {
        c = s->ctrls[i];
        if (c->generic.type == CTRL_CHECKBOX &&
            c->generic.context.i == CONF_scrollbar) {
            /*
             * Control i is the scrollbar checkbox.
             * Control s->ncontrols-1 is the scrollbar-on-left one.
             */
            if (i < s->ncontrols-2) {
                c = s->ctrls[s->ncontrols-1];
                memmove(s->ctrls+i+2, s->ctrls+i+1,
                        (s->ncontrols-i-2)*sizeof(union control *));
                s->ctrls[i+1] = c;
            }
            break;
        }
    }

    /*
     * X requires three more fonts: bold, wide, and wide-bold; also
     * we need the fiddly shadow-bold-offset control. This would
     * make the Window/Appearance panel rather unwieldy and large,
     * so I think the sensible thing here is to _move_ this
     * controlset into a separate Window/Fonts panel!
     */
    s2 = ctrl_getset(b, "Window/Appearance", "font",
                     "Font settings");
    /* Remove this controlset from b. */
    for (i = 0; i < b->nctrlsets; i++) {
        if (b->ctrlsets[i] == s2) {
            memmove(b->ctrlsets+i, b->ctrlsets+i+1,
                    (b->nctrlsets-i-1) * sizeof(*b->ctrlsets));
            b->nctrlsets--;
            ctrl_free_set(s2);
            break;
        }
    }
    ctrl_settitle(b, "Window/Fonts", "Options controlling font usage");
    s = ctrl_getset(b, "Window/Fonts", "font",
                    "Fonts for displaying non-bold text");
    ctrl_fontsel(s, "Font used for ordinary text", 'f',
		 HELPCTX(no_help),
		 conf_fontsel_handler, I(CONF_font));
    ctrl_fontsel(s, "Font used for wide (CJK) text", 'w',
		 HELPCTX(no_help),
		 conf_fontsel_handler, I(CONF_widefont));
    s = ctrl_getset(b, "Window/Fonts", "fontbold",
                    "Fonts for displaying bolded text");
    ctrl_fontsel(s, "Font used for bolded text", 'b',
		 HELPCTX(no_help),
		 conf_fontsel_handler, I(CONF_boldfont));
    ctrl_fontsel(s, "Font used for bold wide text", 'i',
		 HELPCTX(no_help),
		 conf_fontsel_handler, I(CONF_wideboldfont));
    ctrl_checkbox(s, "Use shadow bold instead of bold fonts", 'u',
		  HELPCTX(no_help),
		  conf_checkbox_handler,
		  I(CONF_shadowbold));
    ctrl_text(s, "(Note that bold fonts or shadow bolding are only"
	      " used if you have not requested bolding to be done by"
	      " changing the text colour.)",
              HELPCTX(no_help));
    ctrl_editbox(s, "Horizontal offset for shadow bold:", 'z', 20,
		 HELPCTX(no_help), conf_editbox_handler,
                 I(CONF_shadowboldoffset), I(-1));

    /*
     * Markus Kuhn feels, not totally unreasonably, that it's good
     * for all applications to shift into UTF-8 mode if they notice
     * that they've been started with a LANG setting dictating it,
     * so that people don't have to keep remembering a separate
     * UTF-8 option for every application they use. Therefore,
     * here's an override option in the Translation panel.
     */
    s = ctrl_getset(b, "Window/Translation", "trans",
		    "Character set translation on received data");
    ctrl_checkbox(s, "Override with UTF-8 if locale says so", 'l',
		  HELPCTX(translation_utf8_override),
		  conf_checkbox_handler,
		  I(CONF_utf8_override));

#ifdef OSX_META_KEY_CONFIG
    /*
     * On OS X, there are multiple reasonable opinions about whether
     * Option or Command (or both, or neither) should act as a Meta
     * key, or whether they should have their normal OS functions.
     */
    s = ctrl_getset(b, "Terminal/Keyboard", "meta",
		    "Choose the Meta key:");
    ctrl_checkbox(s, "Option key acts as Meta", 'p',
		  HELPCTX(no_help),
		  conf_checkbox_handler, I(CONF_osx_option_meta));
    ctrl_checkbox(s, "Command key acts as Meta", 'm',
		  HELPCTX(no_help),
		  conf_checkbox_handler, I(CONF_osx_command_meta));
#endif

    if (!midsession) {
        /*
         * Allow the user to specify the window class as part of the saved
         * configuration, so that they can have their window manager treat
         * different kinds of PuTTY and pterm differently if they want to.
         */
        s = ctrl_getset(b, "Window/Behaviour", "x11",
                        "X Window System settings");
        ctrl_editbox(s, "Window class name:", 'z', 50,
                     HELPCTX(no_help), conf_editbox_handler,
                     I(CONF_winclass), I(1));
    }
}
Esempio n. 10
0
//
//  benchmarking program
//
int main( int argc, char **argv )
{    
    //
    //  process command line
    //
    if( find_option( argc, argv, "-h" ) >= 0 )
    {
        printf( "Options:\n" );
        printf( "-h to see this help\n" );
        printf( "-n <int> to set the number of particles\n" );
        printf( "-p <int> to set the number of threads\n" );
        printf( "-o <filename> to specify the output file name\n" );
        return 0;
    }
    
    n = read_int( argc, argv, "-n", 1000 );
    n_threads = read_int( argc, argv, "-p", 2 );
    char *savename = read_string( argc, argv, "-o", NULL );
    
    //
    //  allocate resources
    //
    fsave = savename ? fopen( savename, "w" ) : NULL;

    particles = (particle_t*) malloc( n * sizeof(particle_t) );
    set_size( n );
    init_particles( n, particles );

    pthread_attr_t attr;
    P( pthread_attr_init( &attr ) );
    P( pthread_barrier_init( &barrier, NULL, n_threads ) );

	// VIRAJ
	doBinning();
	// !VIRAJ

	// create threads
    int *thread_ids = (int *) malloc( n_threads * sizeof( int ) );
    for( int i = 0; i < n_threads; i++ ) 
        thread_ids[i] = i;

    pthread_t *threads = (pthread_t *) malloc( n_threads * sizeof( pthread_t ) );
    
    //
    //  do the parallel work
    //
    double simulation_time = read_timer( );
    for( int i = 1; i < n_threads; i++ ) 
        P( pthread_create( &threads[i], &attr, thread_routine, &thread_ids[i] ) );
    
    thread_routine( &thread_ids[0] );
    
    for( int i = 1; i < n_threads; i++ ) 
        P( pthread_join( threads[i], NULL ) );
    simulation_time = read_timer( ) - simulation_time;
    
    printf( "n = %d, n_threads = %d, simulation time = %g seconds\n", n, n_threads, simulation_time );
    
    //
    //  release resources
    //
    P( pthread_barrier_destroy( &barrier ) );
    P( pthread_attr_destroy( &attr ) );
    free( thread_ids );
    free( threads );
    free( particles );
    if( fsave )
        fclose( fsave );

    return 0;
}
Esempio n. 11
0
/*
 * I/O function (for both reads and writes)
 */
static
int
lhd_io(struct device *d, struct uio *uio)
{
	struct lhd_softc *lh = d->d_data;

	uint32_t sector = uio->uio_offset / LHD_SECTSIZE;
	uint32_t sectoff = uio->uio_offset % LHD_SECTSIZE;
	uint32_t len = uio->uio_resid / LHD_SECTSIZE;
	uint32_t lenoff = uio->uio_resid % LHD_SECTSIZE;
	uint32_t i;
	uint32_t statval = LHD_WORKING;
	int result;

	/* Don't allow I/O that isn't sector-aligned. */
	if (sectoff != 0 || lenoff != 0) {
		return EINVAL;
	}

	/* Don't allow I/O past the end of the disk. */
	/* XXX this check can overflow */
	if (sector+len > lh->lh_dev.d_blocks) {
		return EINVAL;
	}

	/* Set up the value to write into the status register. */
	if (uio->uio_rw==UIO_WRITE) {
		statval |= LHD_ISWRITE;
	}

	/* Loop over all the sectors we were asked to do. */
	for (i=0; i<len; i++) {

		/* Wait until nobody else is using the device. */
		P(lh->lh_clear);

		/*
		 * Are we writing? If so, transfer the data to the
		 * on-card buffer.
		 */
		if (uio->uio_rw == UIO_WRITE) {
			result = uiomove(lh->lh_buf, LHD_SECTSIZE, uio);
			membar_store_store();
			if (result) {
				V(lh->lh_clear);
				return result;
			}
		}

		/* Tell it what sector we want... */
		lhd_wreg(lh, LHD_REG_SECT, sector+i);

		/* and start the operation. */
		lhd_wreg(lh, LHD_REG_STAT, statval);

		/* Now wait until the interrupt handler tells us we're done. */
		P(lh->lh_done);

		/* Get the result value saved by the interrupt handler. */
		result = lh->lh_result;

		/*
		 * Are we reading? If so, and if we succeeded,
		 * transfer the data out of the on-card buffer.
		 */
		if (result==0 && uio->uio_rw==UIO_READ) {
			membar_load_load();
			result = uiomove(lh->lh_buf, LHD_SECTSIZE, uio);
		}

		/* Tell another thread it's cleared to go ahead. */
		V(lh->lh_clear);

		/* If we failed, return the error. */
		if (result) {
			return result;
		}
	}

	return 0;
}
Esempio n. 12
0
bool ccTorus::buildUp()
{
	if (m_drawPrecision < MIN_DRAWING_PRECISION)
		return false;

	//invalid parameters?
	if ((m_rectSection && m_rectSectionHeight < ZERO_TOLERANCE) || m_insideRadius >= m_outsideRadius || m_angle_rad < ZERO_TOLERANCE)
		return false;

	//topology
	bool closed = (m_angle_rad >= 2.0*M_PI);

	const unsigned steps = m_drawPrecision;

	unsigned sweepSteps = 4 * (closed ? steps : static_cast<unsigned>(ceil((m_angle_rad * steps)/(2.0*M_PI))));
	unsigned sectSteps = (m_rectSection ? 4 : steps);

	//vertices
	unsigned vertCount = (sweepSteps + (closed ? 0 : 1)) * sectSteps; //DGM: +1 row for non closed loops
	//faces
	unsigned facesCount = sweepSteps * sectSteps *2;
	//faces normals
	unsigned faceNormCount = (sweepSteps + (closed ? 0 : 1)) * sectSteps; //DGM: +1 row for non closed loops
	if (!closed)
		facesCount += (m_rectSection ? 2 : sectSteps)*2;

	if (!init(vertCount + (closed || m_rectSection ? 0 : 2), false, facesCount, faceNormCount + (closed ? 0 : 2)))
	{
		ccLog::Error("[ccTorus::buildUp] Not enough memory");
		return false;
	}

	//2D section
	std::vector<CCVector3> sectPoints;
	try
	{
		sectPoints.resize(sectSteps);
	}
	catch (const std::bad_alloc&)
	{
		init(0,false,0,0);
		ccLog::Error("[ccTorus::buildUp] Not enough memory");
		return false;
	}

	double sweepStep_rad = m_angle_rad / sweepSteps;
	double sectStep_rad = (2.0*M_PI) / sectSteps;

	PointCoordinateType sectionRadius = (m_outsideRadius-m_insideRadius)/2;
	if (m_rectSection)
	{
		//rectangular section
		sectPoints[0].x = (m_outsideRadius-m_insideRadius)/2;
		sectPoints[0].z = m_rectSectionHeight/2;
		sectPoints[1].x = -sectPoints[0].x;
		sectPoints[1].z = sectPoints[0].z;
		sectPoints[2].x = sectPoints[1].x;
		sectPoints[2].z = -sectPoints[1].z;
		sectPoints[3].x = -sectPoints[2].x;
		sectPoints[3].z = sectPoints[2].z;
	}
	else
	{
		//circular section
		for (unsigned i=0; i<sectSteps; ++i)
		{
			double sect_angle_rad = i * sectStep_rad;
			sectPoints[i].x = static_cast<PointCoordinateType>(cos(sect_angle_rad) * sectionRadius);
			sectPoints[i].z = static_cast<PointCoordinateType>(sin(sect_angle_rad) * sectionRadius);
		}
	}

	ccPointCloud* verts = vertices();
	assert(verts);
	assert(m_triNormals);

	//main sweep
	PointCoordinateType sweepRadius = (m_insideRadius + m_outsideRadius)/2;
	for (unsigned t=0; t<(closed ? sweepSteps : sweepSteps+1); ++t)
	{
		//unit director vector
		CCVector3 sweepU(static_cast<PointCoordinateType>(cos(t*sweepStep_rad)),
						 static_cast<PointCoordinateType>(sin(t*sweepStep_rad)),
						 0);

		//section points
		for (unsigned i=0; i<sectSteps; ++i)
		{
			CCVector3 P(sweepU.x * (sweepRadius + sectPoints[i].x),
						sweepU.y * (sweepRadius + sectPoints[i].x),
						sectPoints[i].z);
			verts->addPoint(P);
		}

		//normals
		if (m_rectSection)
		{
			m_triNormals->addElement(ccNormalVectors::GetNormIndex(CCVector3(0.0,0.0,1.0).u));
			m_triNormals->addElement(ccNormalVectors::GetNormIndex((-sweepU).u));
			m_triNormals->addElement(ccNormalVectors::GetNormIndex(CCVector3(0.0,0.0,-1.0).u));
			m_triNormals->addElement(ccNormalVectors::GetNormIndex(sweepU.u));
		}
		else //circular section
		{
			for (unsigned i=0; i<sectSteps; ++i)
			{
				double sectAngle_rad = i * sectStep_rad;
				CCVector3 sectU = CCVector3::fromArray(CCVector3(cos(sectAngle_rad), 0.0, sin(sectAngle_rad)).u);
				CCVector3 N(sweepU.x * sectU.x,
							sweepU.y * sectU.x,
							sectU.z);
				m_triNormals->addElement(ccNormalVectors::GetNormIndex(N.u));
			}
		}
	}

	if (!closed && !m_rectSection)
	{
		CCVector3 P(sweepRadius,0,0);
		verts->addPoint(P);
		CCVector3 P2(	static_cast<PointCoordinateType>(cos(m_angle_rad))*sweepRadius,
						static_cast<PointCoordinateType>(sin(m_angle_rad))*sweepRadius,
						 0);
		verts->addPoint(P2);
	}

	if (!closed)
	{
		//first section (left side)
		m_triNormals->addElement(ccNormalVectors::GetNormIndex(CCVector3(0,-1,0).u));
		//last section (right side)
		m_triNormals->addElement(ccNormalVectors::GetNormIndex(CCVector3(	static_cast<PointCoordinateType>(-sin(m_angle_rad)),
																			static_cast<PointCoordinateType>(cos(m_angle_rad)),
																			0).u));
	}

	sectPoints.clear();

	//mesh faces
	{
		assert(m_triVertIndexes);

		for (unsigned t=0;t<sweepSteps;++t)
		{
			unsigned sweepStart = t*sectSteps;
			for (unsigned i=0;i<sectSteps;++i)
			{
				unsigned iNext = (i+1)%sectSteps;
				addTriangle(sweepStart+i,(sweepStart+i+sectSteps)%vertCount,(sweepStart+iNext+sectSteps)%vertCount);
				if (m_rectSection)
					addTriangleNormalIndexes(sweepStart+i,(sweepStart+i+sectSteps)%faceNormCount,(sweepStart+i+sectSteps)%faceNormCount);
				else
					addTriangleNormalIndexes(sweepStart+i,(sweepStart+i+sectSteps)%faceNormCount,(sweepStart+iNext+sectSteps)%faceNormCount);
				addTriangle(sweepStart+i,(sweepStart+iNext+sectSteps)%vertCount,sweepStart+iNext);
				if (m_rectSection)
					addTriangleNormalIndexes(sweepStart+i,(sweepStart+i+sectSteps)%faceNormCount,sweepStart+i);
				else
					addTriangleNormalIndexes(sweepStart+i,(sweepStart+iNext+sectSteps)%faceNormCount,sweepStart+iNext);
			}
		}

		if (!closed)
		{
			unsigned lastSectionShift = sweepSteps*sectSteps;
			if (m_rectSection)
			{
				//rectangular left section
				addTriangle(0,1,2);
				addTriangleNormalIndexes(faceNormCount,faceNormCount,faceNormCount);
				addTriangle(0,2,3);
				addTriangleNormalIndexes(faceNormCount,faceNormCount,faceNormCount);
				//rectangular right section
				addTriangle(lastSectionShift,lastSectionShift+2,lastSectionShift+1);
				addTriangleNormalIndexes(faceNormCount+1,faceNormCount+1,faceNormCount+1);
				addTriangle(lastSectionShift,lastSectionShift+3,lastSectionShift+2);
				addTriangleNormalIndexes(faceNormCount+1,faceNormCount+1,faceNormCount+1);
			}
			else
			{
				unsigned lastSectionCenterShift = vertCount;
				//circular 'left' section
				for (unsigned i=0;i<sectSteps;++i)
				{
					unsigned iNext = (i+1)%sectSteps;
					addTriangle(lastSectionCenterShift,i,iNext);
					addTriangleNormalIndexes(faceNormCount,faceNormCount,faceNormCount);
				}
				//circular 'right' section
				for (unsigned i=0;i<sectSteps;++i)
				{
					unsigned iNext = (i+1)%sectSteps;
					addTriangle(lastSectionCenterShift+1,lastSectionShift+iNext,lastSectionShift+i);
					addTriangleNormalIndexes(faceNormCount+1,faceNormCount+1,faceNormCount+1);
				}
			}
		}
	}

	notifyGeometryUpdate();
	showTriNorms(true);

	return true;
}
Esempio n. 13
0
int lustre_mds_stat_by_fid( const entry_id_t * p_id, struct stat *inode )
{
    char filename[MAXNAMLEN];
    char           buffer[1024];
    struct lov_user_mds_data *lmd = ( struct lov_user_mds_data * ) buffer;
    int rc;

    /* ensure fid directory is opened */
    if ( fid_dir_fd == NULL )
    {
        P( dir_lock );
        if ( fid_dir_fd == NULL )
        {
            char path[RBH_PATH_MAX];
            char *curr = path;
            unsigned int mlen;

            /* filesystem root */
            strcpy( path, get_mount_point(&mlen) );
            curr += mlen;

            /* fid directory */
            strcpy( curr, "/" FIDDIR );

            /* open fir directory */
            fid_dir_fd = opendir( path );
        }
        V( dir_lock );
        if ( fid_dir_fd == NULL )
            return errno;
    }

    sprintf( filename, DFID, PFID(p_id) );
    memset( lmd, 0, sizeof( buffer ) );
    rh_strncpy(buffer, filename, strlen(filename) + 1);

    rc = ioctl( dirfd( fid_dir_fd ), IOC_MDC_GETFILEINFO, ( void * ) lmd );

    if ( rc )
    {
        if ( errno == ENOTTY )
        {
            return ENOTSUP;
        }
        else if ( ( errno == ENOENT ) || ( errno == ESTALE ) )
        {
            DisplayLog( LVL_MAJOR, TAG_MDSSTAT, "Warning: %s: %s does not exist",
                        __FUNCTION__, filename );
            return ENOENT;
        }
        else
        {
            DisplayLog( LVL_CRIT, TAG_MDSSTAT,
                        "Error: %s: IOC_MDC_GETFILEINFO failed for %s",
                        __FUNCTION__, filename );
            return errno;
        }
    }

    *inode = lmd->lmd_st;
    return 0;
}
Esempio n. 14
0
void proc_sched_show_task(struct task_struct *p, struct seq_file *m)
{
	unsigned long nr_switches;

	SEQ_printf(m, "%s (%d, #threads: %d)\n", p->comm, p->pid,
						get_nr_threads(p));
	SEQ_printf(m,
		"---------------------------------------------------------\n");
#define __P(F) \
	SEQ_printf(m, "%-35s:%21Ld\n", #F, (long long)F)
#define P(F) \
	SEQ_printf(m, "%-35s:%21Ld\n", #F, (long long)p->F)
#define __PN(F) \
	SEQ_printf(m, "%-35s:%14Ld.%06ld\n", #F, SPLIT_NS((long long)F))
#define PN(F) \
	SEQ_printf(m, "%-35s:%14Ld.%06ld\n", #F, SPLIT_NS((long long)p->F))

	PN(se.exec_start);
	PN(se.vruntime);
	PN(se.sum_exec_runtime);

	nr_switches = p->nvcsw + p->nivcsw;

#ifdef CONFIG_SCHEDSTATS
	PN(se.statistics.wait_start);
	PN(se.statistics.sleep_start);
	PN(se.statistics.block_start);
	PN(se.statistics.sleep_max);
	PN(se.statistics.block_max);
	PN(se.statistics.exec_max);
	PN(se.statistics.slice_max);
	PN(se.statistics.wait_max);
	PN(se.statistics.wait_sum);
	P(se.statistics.wait_count);
	PN(se.statistics.iowait_sum);
	P(se.statistics.iowait_count);
	P(se.nr_migrations);
	P(se.statistics.nr_migrations_cold);
	P(se.statistics.nr_failed_migrations_affine);
	P(se.statistics.nr_failed_migrations_running);
	P(se.statistics.nr_failed_migrations_hot);
	P(se.statistics.nr_forced_migrations);
	P(se.statistics.nr_wakeups);
	P(se.statistics.nr_wakeups_sync);
	P(se.statistics.nr_wakeups_migrate);
	P(se.statistics.nr_wakeups_local);
	P(se.statistics.nr_wakeups_remote);
	P(se.statistics.nr_wakeups_affine);
	P(se.statistics.nr_wakeups_affine_attempts);
	P(se.statistics.nr_wakeups_passive);
	P(se.statistics.nr_wakeups_idle);

	{
		u64 avg_atom, avg_per_cpu;

		avg_atom = p->se.sum_exec_runtime;
		if (nr_switches)
			avg_atom = div64_ul(avg_atom, nr_switches);
		else
			avg_atom = -1LL;

		avg_per_cpu = p->se.sum_exec_runtime;
		if (p->se.nr_migrations) {
			avg_per_cpu = div64_u64(avg_per_cpu,
						p->se.nr_migrations);
		} else {
			avg_per_cpu = -1LL;
		}

		__PN(avg_atom);
		__PN(avg_per_cpu);
	}
#endif
	__P(nr_switches);
	SEQ_printf(m, "%-35s:%21Ld\n",
		   "nr_voluntary_switches", (long long)p->nvcsw);
	SEQ_printf(m, "%-35s:%21Ld\n",
		   "nr_involuntary_switches", (long long)p->nivcsw);

	P(se.load.weight);
	P(policy);
	P(prio);
#ifdef CONFIG_PREEMPT_RT_FULL
	P(migrate_disable);
#endif
	P(nr_cpus_allowed);
#undef PN
#undef __PN
#undef P
#undef __P

	{
		unsigned int this_cpu = raw_smp_processor_id();
		u64 t0, t1;

		t0 = cpu_clock(this_cpu);
		t1 = cpu_clock(this_cpu);
		SEQ_printf(m, "%-35s:%21Ld\n",
			   "clock-delta", (long long)(t1-t0));
	}
}
Esempio n. 15
0
/*
	Get from / Set to RTC
*/
LOCAL	void	rtc_get_set(SYSTIM *stm, BOOL set)
{
	ID		dd;
	W		asz;
	ER		er;
	DATE_TIM	dt;
	struct tm	ctm;
	struct tzinfo	tz;

	/* open RTC (CLOCK) driver */
	dd = tk_opn_dev("CLOCK", (set == TRUE) ? TD_WRITE : TD_READ);
	if (dd < E_OK) {
		P("Can't open CLOCK device [%#x]\n", dd);
		goto exit0;
	}

	/* Note: The RTC is set to UTC rather than local time. because UTC
	   is not affected by time zone and daylight saving time. */

	if (set == TRUE) {	/* set date to RTC */

		/* convert system time to UTC date/time */
		dt_gmtime_ms(stm, &ctm);

		/* set local date/time to RTC */
		dt.d_year = ctm.tm_year;
		dt.d_month = ctm.tm_mon + 1;
		dt.d_day = ctm.tm_mday;
		dt.d_hour = ctm.tm_hour;
		dt.d_min = ctm.tm_min;
		dt.d_sec = ctm.tm_sec;
		dt.d_wday = ctm.tm_wday;
		er = tk_swri_dev(dd, DN_CKDATETIME, &dt, sizeof(dt), &asz);
		if (er < E_OK) {
			P("Can't set CLOCK [%#x]\n", er);
			goto exit1;
		}
	} else {		/* get date from RTC */

		/* get timezone of "UTC+0" */
		memset(&tz, 0, sizeof(tz));
		er = dt_tzset(&tz, "UTC+0");
		if (er < E_OK ) {
			P("dt_tzset(UTC+0) ERR [%#x]\n", er);
			goto exit1;
		}

		/* get UTC date/time from RTC */
		er = tk_srea_dev(dd, DN_CKDATETIME, &dt, sizeof(dt), &asz);
		if (er < E_OK) {
			P("Can't get CLOCK [%#x]\n", er);
			goto exit1;
		}

		/* convert to system time */
		ctm.tm_year = dt.d_year;
		ctm.tm_mon = dt.d_month - 1;
		ctm.tm_mday = dt.d_day;
		ctm.tm_hour = dt.d_hour;
		ctm.tm_min = dt.d_min;
		ctm.tm_sec = dt.d_sec;
		ctm.tm_wday = dt.d_wday;
		ctm.tm_usec = 0;
		ctm.tm_wday = -1;
		ctm.tm_isdst = 0;
		ctm.tm_yday = 0;
		dt_mktime_ms(&ctm, &tz, stm);
	}
exit1:
	tk_cls_dev(dd, 0);
exit0:
	return;
}
Esempio n. 16
0
msgpack_t::unpack_tab_t &
msgpack_t::unpack_tab () 
{
  static unpack_tab_t tab;
  static bool init;
  if (!init) {

#define P(code, obj) \
    tab[code] = &msgpack_t::unpack_##obj;

    for (u_int8_t i = 0; i < 0xff; i++) { tab[i] = NULL; }

    for (u_int8_t i = 0x00; i <= 0x7f; i++) P(i, positive_fixnum);
    for (u_int8_t i = 0x80; i <= 0x8f; i++) P(i, fix_map);
    for (u_int8_t i = 0x90; i <= 0x9f; i++) P(i, fix_array);
    for (u_int8_t i = 0xa0; i <= 0xbf; i++) P(i, fix_raw);
    
    P(0xc0, nil);
    P(0xc2, false);
    P(0xc3, true);
    P(0xca, float);
    P(0xcb, double);
    P(0xcc, uint8);
    P(0xcd, uint16);
    P(0xce, uint32);
    P(0xcf, uint64);
    P(0xd0, int8);
    P(0xd1, int16);
    P(0xd2, int32);
    P(0xd3, int64);
    P(0xda, raw16);
    P(0xdb, raw32);
    P(0xdc, array16); 
    P(0xdd, array32); 
    P(0xde, map16); 
    P(0xdf, map32); 

    for (u_int16_t i = 0xe0; i <= 0xff; i++) P(i, negative_fixnum);

#undef P
    init = true;
  }

  return tab;
}
Esempio n. 17
0
/*
	execute command
*/
EXPORT	INT	exec_cmd(B *cmd)
{
	INT	ac;
	B	*av[N_ARGS];

	ac = setup_param(cmd, av);
	if (ac < 1) return 0;

	if (strcmp(av[0], "date") == 0) {
		cmd_date(ac, av);
	} else if (strcmp(av[0], "attach") == 0) {
		cmd_attach(ac, av);
	} else if (strcmp(av[0], "detach") == 0) {
		cmd_detach(ac, av);
	} else if (strcmp(av[0], "mkdir") == 0) {
		cmd_mkdir(ac, av);
	} else if (strcmp(av[0], "rmdir") == 0) {
		cmd_rmdir(ac, av);
	} else if (strcmp(av[0], "pwd") == 0) {
		cmd_pwd(ac, av);
	} else if (strcmp(av[0], "cd") == 0) {
		cmd_cd(ac, av);
	} else if (strcmp(av[0], "rm") == 0) {
		cmd_rm(ac, av);
	} else if (strcmp(av[0], "mv") == 0) {
		cmd_mv(ac, av);
	} else if (strcmp(av[0], "ls") == 0) {
		cmd_ls(ac, av);
	} else if (strcmp(av[0], "tp") == 0 || strcmp(av[0], "tpx") == 0) {
		cmd_tp(ac, av);
	} else if (strcmp(av[0], "cp") == 0) {
		cmd_cp(ac, av);
	} else if (strcmp(av[0], "trunc") == 0) {
		cmd_trunc(ac, av);
	} else if (strcmp(av[0], "df") == 0) {
		cmd_df(ac, av);
	} else if (strcmp(av[0], "sync") == 0) {
		cmd_sync(ac, av);
	} else if (strcmp(av[0], "chmod") == 0) {
		cmd_chmod(ac, av);
	} else if (strcmp(av[0], "ref") == 0) {
		cmd_ref(ac, av);
	} else if (strcmp(av[0], "load") == 0) {
		cmd_load(ac, av);
	} else if (strcmp(av[0], "loadspg") == 0) {
		cmd_loadspg(ac, av);
	} else if (strcmp(av[0], "unload") == 0) {
		cmd_unload(ac, av);
	} else if (strcmp(av[0], "call") == 0) {
		cmd_call(ac, av);
	} else if (strncmp(av[0], "?", 1) == 0) {
		P("date     [y m d [h m s]]\n");
		P("attach   devnm connm\n");
		P("detach   connm\n");
		P("cd       dir\n");
		P("pwd      \n");
		P("ls       [-t][-l][dir]\n");
		P("mkdir    dir [mode]\n");
		P("rmdir    dir\n");
		P("rm       path\n");
		P("mv       o-path n-path\n");
		P("trunc    path len\n");
		P("df       path\n");
		P("sync     [path [d]]\n");
		P("chmod    path mode\n");
		P("tp       path [ofs len]\n");
		P("tpx      path [ofs len]\n");
		P("cp       s-path d-path/dir [wofs [wlen]]\n");
		P("ref      [item]\n");
		P("call     addr [p1 p2 p3]\n");
		P("load     path\n");
		P("loadspg  path [arg ...]\n");
		P("unload   progid\n");
#ifdef	NET_SAMPLE
		P("net      execute network sample\n");

	} else if (strcmp(av[0], "net") == 0) {
IMPORT	void	net_test(void);
		net_test();
#endif
	} else {
		return 0;
	}
	return 1;
}
Esempio n. 18
0
        ClrPriv(client, PRIV_GLINE);
        ClrPriv(client, PRIV_MUTE);
        ClrPriv(client, PRIV_JUPE);
        ClrPriv(client, PRIV_OPMODE);
        ClrPriv(client, PRIV_BADCHAN);
    }
}

/** Array mapping privilege values to names and vice versa. */
static struct {
    char        *name; /**< Name of privilege. */
    unsigned int priv; /**< Enumeration value of privilege */
} privtab[] = {
    /** Helper macro to define an array entry for a privilege. */
#define P(priv)		{ #priv, PRIV_ ## priv }
    P(CHAN_LIMIT),     P(MODE_LCHAN),     P(WALK_LCHAN),    P(DEOP_LCHAN),
    P(SHOW_INVIS),     P(SHOW_ALL_INVIS), P(UNLIMIT_QUERY), P(KILL),
    P(LOCAL_KILL),     P(REHASH),         P(RESTART),       P(DIE),
    P(GLINE),          P(LOCAL_GLINE),    P(JUPE),          P(LOCAL_JUPE),
    P(OPMODE),         P(LOCAL_OPMODE),   P(SET),           P(WHOX),
    P(BADCHAN),        P(LOCAL_BADCHAN),  P(SEE_CHAN),      P(PROPAGATE),
    P(DISPLAY),        P(SEE_OPERS),      P(WIDE_GLINE),    P(LIST_CHAN),
    P(FORCE_OPMODE),   P(FORCE_LOCAL_OPMODE), P(APASS_OPMODE), P(SET_FAKEHOST),
#undef P
    { 0, 0 }
};

/** Report privileges of \a client to \a to.
 * @param[in] to Client requesting privilege list.
 * @param[in] client Client whos privileges should be listed.
 * @return Zero.
Esempio n. 19
0
static bRC handle_read_error(void *value)
{
   DCR *dcr;
   DEVICE *dev;
   DEVRES *device;
   bool decryption_needed;

   /*
    * Unpack the arguments passed in.
    */
   dcr = (DCR *)value;
   if (!dcr) {
      return bRC_Error;
   }
   dev = dcr->dev;
   if (!dev) {
      return bRC_Error;
   }
   device = dev->device;
   if (!device) {
      return bRC_Error;
   }

   /*
    * See if drive crypto is enabled.
    */
   if (device->drive_crypto_enabled) {
      /*
       * See if the read error is an EIO which can be returned when we try to read an
       * encrypted block from a volume without decryption enabled or without a proper
       * encryption key loaded.
       */
      switch (dev->dev_errno) {
      case EIO:
         /*
          * See if we need to query the drive or use the tracked encryption status of the stored.
          * When we can query the drive we look at the next block encryption state to see if
          * we need decryption of the data on the volume.
          */
         if (device->query_crypto_status) {
            P(crypto_operation_mutex);
            if (need_scsi_crypto_key(dev->fd(), dev->dev_name, false)) {
               decryption_needed = true;
            } else {
               decryption_needed = false;
            }
            V(crypto_operation_mutex);
         } else {
            decryption_needed = dev->is_crypto_enabled();
         }

         /*
          * Alter the error message so it known this error is most likely due to a
          * failed decryption of the encrypted data on the volume.
          */
         if (decryption_needed) {
            berrno be;

            be.set_errno(dev->dev_errno);
            Mmsg5(dev->errmsg, _("Read error on fd=%d at file:blk %u:%u on device %s. ERR=%s.\n"
                                 "Probably due to reading encrypted data from volume\n"),
                  dev->fd(), dev->file, dev->block_num, dev->print_name(), be.bstrerror());
         }
         break;
      default:
         break;
      }
   }
   return bRC_OK;
}
Esempio n. 20
0
long double
asinl(long double x)
{
	union {
		long double e;
		struct ieee_ext bits;
	} u;
	long double t=0.0,w,p,q,c,r,s;
	int16_t expsign, expt;
	u.e = x;
	expsign = (u.bits.ext_sign << 15) | u.bits.ext_exp;
	expt = expsign & 0x7fff;
	if(expt >= BIAS) {		/* |x|>= 1 */
		if(expt==BIAS && ((u.bits.ext_frach&~LDBL_NBIT)
#ifdef EXT_FRACHMBITS
			| u.bits.ext_frachm
#endif /* EXT_FRACHMBITS */
#ifdef EXT_FRACLMBITS
			| u.bits.ext_fraclm
#endif /* EXT_FRACLMBITS */
			| u.bits.ext_fracl)==0)
		    /* asin(1)=+-pi/2 with inexact */
		    return x*pio2_hi+x*pio2_lo;	
	    return (x-x)/(x-x);		/* asin(|x|>1) is NaN */   
	} else if (expt<BIAS-1) {	/* |x|<0.5 */
	    if(expt<ASIN_LINEAR) {	/* if |x| is small, asinl(x)=x */
		if(huge+x>one) return x;/* return x with inexact if x!=0*/
	    }
	    t = x*x;
	    p = P(t);
	    q = Q(t);
	    w = p/q;
	    return x+x*w;
	}
	/* 1> |x|>= 0.5 */
	w = one-fabsl(x);
	t = w*0.5;
	p = P(t);
	q = Q(t);
	s = sqrtl(t);
#ifdef EXT_FRACHMBITS
	if((((uint64_t)u.bits.ext_frach << EXT_FRACHMBITS)
		| u.bits.ext_frachm) >= THRESH) {
						/* if |x| is close to 1 */
#else /* EXT_FRACHMBITS */
	if(u.bits.ext_frach>=THRESH) {		/* if |x| is close to 1 */
#endif /* EXT_FRACHMBITS */
	    w = p/q;
	    t = pio2_hi-(2.0*(s+s*w)-pio2_lo);
	} else {
	    u.e = s;
	    u.bits.ext_fracl = 0;
#ifdef EXT_FRACLMBITS
	    u.bits.ext_fraclm = 0;
#endif /* EXT_FRACLMBITS */
	    w = u.e;
	    c  = (t-w*w)/(s+w);
	    r  = p/q;
	    p  = 2.0*s*r-(pio2_lo-2.0*c);
	    q  = pio4_hi-2.0*w;
	    t  = pio4_hi-(p-q);
	}    
	if(expsign>0) return t; else return -t;    
}
Esempio n. 21
0
double U(int m, int n, int l)
{
  return P(0, m, n, l);
}
Esempio n. 22
0
void b2FrictionJoint::InitVelocityConstraints(const b2TimeStep& step)
{
	b2Body* bA = m_bodyA;
	b2Body* bB = m_bodyB;

	// Compute the effective mass matrix.
	b2Vec2 rA = b2Mul(bA->GetTransform().R, m_localAnchorA - bA->GetLocalCenter());
	b2Vec2 rB = b2Mul(bB->GetTransform().R, m_localAnchorB - bB->GetLocalCenter());

	// J = [-I -r1_skew I r2_skew]
	//     [ 0       -1 0       1]
	// r_skew = [-ry; rx]

	// Matlab
	// K = [ mA+r1y^2*iA+mB+r2y^2*iB,  -r1y*iA*r1x-r2y*iB*r2x,          -r1y*iA-r2y*iB]
	//     [  -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB,           r1x*iA+r2x*iB]
	//     [          -r1y*iA-r2y*iB,           r1x*iA+r2x*iB,                   iA+iB]

	float32 mA = bA->m_invMass, mB = bB->m_invMass;
	float32 iA = bA->m_invI, iB = bB->m_invI;

	b2Mat22 K1;
	K1.col1.x = mA + mB;	K1.col2.x = 0.0f;
	K1.col1.y = 0.0f;		K1.col2.y = mA + mB;

	b2Mat22 K2;
	K2.col1.x =  iA * rA.y * rA.y;	K2.col2.x = -iA * rA.x * rA.y;
	K2.col1.y = -iA * rA.x * rA.y;	K2.col2.y =  iA * rA.x * rA.x;

	b2Mat22 K3;
	K3.col1.x =  iB * rB.y * rB.y;	K3.col2.x = -iB * rB.x * rB.y;
	K3.col1.y = -iB * rB.x * rB.y;	K3.col2.y =  iB * rB.x * rB.x;

	b2Mat22 K = K1 + K2 + K3;
	m_linearMass = K.GetInverse();

	m_angularMass = iA + iB;
	if (m_angularMass > 0.0f)
	{
		m_angularMass = 1.0f / m_angularMass;
	}

	if (step.warmStarting)
	{
		// Scale impulses to support a variable time step.
		m_linearImpulse *= step.dtRatio;
		m_angularImpulse *= step.dtRatio;

		b2Vec2 P(m_linearImpulse.x, m_linearImpulse.y);

		bA->m_linearVelocity -= mA * P;
		bA->m_angularVelocity -= iA * (b2Cross(rA, P) + m_angularImpulse);

		bB->m_linearVelocity += mB * P;
		bB->m_angularVelocity += iB * (b2Cross(rB, P) + m_angularImpulse);
	}
	else
	{
		m_linearImpulse.SetZero();
		m_angularImpulse = 0.0f;
	}
}
Esempio n. 23
0
static int ext_client_bgp_recv(struct thread * t)
{
  struct ext_client_bgp * ext_client_bgp = THREAD_ARG(t);
  struct bgp_header * bgph;
  u_int16_t length;
  size_t bgph_size = sizeof(struct bgp_header);
  struct rfp_forward_bgp * rfpb;
  size_t already = 0;
  size_t nbytes;
  struct rfpbuf * bgp_buf = rfpbuf_new(bgph_size);
  struct bgp_listener * listener;
  unsigned int peer_fd = THREAD_FD(t);

  printf("ext_client_bgp_recv called\n");

  LIST_FOR_EACH(listener, struct bgp_listener, node, &ext_client_bgp->listen_sockets)
  {
    // if we found a listener matching fd, we are done
    if(listener->peer_fd == peer_fd)
      break;
  }


  if(((nbytes = rfpbuf_read_try(bgp_buf, peer_fd, bgph_size - already)) == 0) ||
      (nbytes == -1))
  {
    // failed
    return -1;
  }
  if(nbytes != bgph_size - already)
  {
    /* Try again later */
    ext_client_bgp_event(EXT_CLIENT_BGP_READ, ext_client_bgp, listener);
    return 0;
  }

  already = bgph_size;

  bgph = rfpbuf_at_assert(bgp_buf, 0, sizeof(struct bgp_header));
  length = ntohs(bgph->length);
  rfpbuf_prealloc_tailroom(bgp_buf, length - already);

  if(already < length)
  {
    if(((nbytes = rfpbuf_read_try(bgp_buf, peer_fd, length - already)) == 0) ||
      (nbytes == -1))
    {
      // failed
      return -1;
    }
    if(nbytes != length - already)
    {
      /* Try again later */
      ext_client_bgp_event(EXT_CLIENT_BGP_READ, ext_client_bgp, listener);
      return 0;
    }
  }

  // put a header
  P(ext_client_bgp).ibuf = routeflow_alloc_xid(RFPT_FORWARD_BGP, RFP10_VERSION, 0, sizeof(struct rfp_forward_bgp));

  rfpb = rfpbuf_at_assert(P(ext_client_bgp).ibuf, 0, sizeof(struct rfp_forward_bgp));

  memcpy(&rfpb->bgp_header, bgp_buf->data, bgph_size);

  // call our parent's class
  ext_client_recv(&P(ext_client_bgp));

  // sent the data so free the memomry
  rfpbuf_delete(bgp_buf);
  rfpbuf_delete(P(ext_client_bgp).ibuf);
  P(ext_client_bgp).ibuf = 0;

  ext_client_bgp_event(EXT_CLIENT_BGP_READ, ext_client_bgp, listener);
  return 0;
}
Esempio n. 24
0
/**
 * This is the mane entry point of the program
 * 
 * @param   argc  The number of elements in `argv`
 * @parma   argv  Command line arguments, including the command
 * @return        Exit value, zero on success
 */
int main(int argc, char** argv)
{
  struct winsize win;
  struct termios saved_stty;
  struct termios stty;
  size_t i, ndevices = 0;
  pid_t pid = 0;
  char* set = NULL;
  int j, get = 0, help = 0, all = 0, cols = 80;
  char** devices = alloca((size_t)argc * sizeof(char*));
  
  
  if (argc > 1)
    {
      char* arg;
      for (i = 1; i < (size_t)argc; i++)
	{
	  #define T(S)  (!strcmp(arg, S))
	  arg = *(argv + i);
	  if (T("-h") || T("--help"))
	    help = 1;
	  else if (T("-a") || T("--all"))
	    all = 1;
	  else if (T("-c") || T("--copyright") || T("--copying"))
	    {
	      P("\n");
	      P("adjbacklight – Convenient method for adjusting the backlight on your portable computer");
	      P("");
	      P("Copyright © " _YEARS_ "  Mattias Andrée ([email protected])");
	      P("");
	      P("This program is free software: you can redistribute it and/or modify");
	      P("it under the terms of the GNU General Public License as published by");
	      P("the Free Software Foundation, either version 3 of the License, or");
	      P("(at your option) any later version.");
	      P("");
	      P("This program is distributed in the hope that it will be useful,");
	      P("but WITHOUT ANY WARRANTY; without even the implied warranty of");
	      P("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the");
	      P("GNU General Public License for more details.");
	      P("");
	      P("You should have received a copy of the GNU General Public License");
	      P("along with this program.  If not, see <http://www.gnu.org/licenses/>.");
	      P("\n");
	      return 0;
	    }
	  else if (T("-w") || T("--warranty"))
	    {
	      P("\n");
	      P("This program is distributed in the hope that it will be useful,");
	      P("but WITHOUT ANY WARRANTY; without even the implied warranty of");
	      P("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the");
	      P("GNU General Public License for more details.");
	      P("\n");
	      return 0;
	    }
	  else if (T("-s") || T("--set"))
	    {
	      char* tmp;
	      if (i + 1 == (size_t)argc)
		fprintf(stderr, "%s: argument for option %s is missing, ignoring option\n", *argv, arg);
	      else
		if (!isnumerical(tmp = *(argv + ++i)))
		  fprintf(stderr, "%s: argument for option %s is malformated, ignoring option\n", *argv, arg);
		else
		  {
		    set = tmp;
		    get = 0;
		  }
	    }
	  else if (T("-g") || T("--get"))
	    {
	      get = 1;
	      set = NULL;
	    }
	  else if (((*arg == '-') || (*arg == '+') || (*arg == '=')) && isnumerical(arg + 1))
	    {
	      set = arg;
	      get = 0;
	    }
	  else
	    {
	      if (*arg && (*arg != '-'))
		*(devices + ndevices++) = arg;
	      else
		fprintf(stderr, "%s: ignoring unrecognised argument: %s\n", *argv, arg);
	    }
	  #undef T
	}
      fflush(stderr);
      if (help || (((size_t)all + ndevices + (size_t)get == 0) && !set))
	{
	  P("\n");
	  P("adjbacklight - Convenient method for adjusting the backlight on your portable computer");
	  P("");
	  P("USAGE: adjbacklight (-c | -w | [-g | -s LEVEL | LEVEL] [-a | DEVICE...])");
	  P("");
	  P("Run with options to adjust the backlight on your monitors.");
	  P("");
	  P("");
	  P("OPTIONS:");
	  P("");
	  P("-c");
	  P("--copyright");
	  P("--copying       Display copyright information");
	  P("");
	  P("-w");
	  P("--warranty      Display warranty disclaimer");
	  P("");
	  P("-a");
	  P("--all           Run for all devices, including ACPI devices");
	  P("");
	  P("-g");
	  P("--get           Get average brightness on devices");
	  P("");
	  P("-s");
	  P("--set LEVEL[%]  Set brightness on devices");
	  P("");
	  P("+LEVEL          Increase brightness on devices by actual value");
	  P("-LEVEL          Decrease brightness on devices by actual value");
	  P("=LEVEL          Set brightness on devices by actual value");
	  P("");
	  P("+LEVEL%         Increase brightness on devices by percentage-points");
	  P("-LEVEL%         Decrease brightness on devices by percentage-points");
	  P("=LEVEL%         Set brightness on devices by percentage-points");
	  P("");
	  P("+LEVEL%%        Increase brightness on devices by percentage");
	  P("-LEVEL%%        Decrease brightness on devices by percentage");
	  P("=LEVEL%%        Set brightness on devices by percentage");
	  P("");
	  P("");
	  P("KEYBOARD:");
	  P("");
	  P("←");
	  P("↓               Darken the screen");
	  P("");
	  P("→");
	  P("↑               Brighten the screen");
	  P("");
	  P("q");
	  P("enter");
	  P("C-d             Continue to next controller, or if at last, quit");
	  P("");
	  P("");
	  P("");
	  P("Copyright © " _YEARS_ "  Mattias Andrée ([email protected])");
	  P("");
	  P("This program is free software: you can redistribute it and/or modify");
	  P("it under the terms of the GNU General Public License as published by");
	  P("the Free Software Foundation, either version 3 of the License, or");
	  P("(at your option) any later version.");
	  P("");
	  return 0;
	}
    }
  
  
  /* Check permissions */
  if (getuid()) /* Always accept root */
  {
    struct group* video_grp = getgrnam("video");
    if (video_grp) /* Accept everypony if the group ‘video’ does not exist */
      {
	struct passwd* realuser = getpwuid(getuid());
	char** mems;
	char* realname;
	int ok;
	if (!realuser)
	  {
	    P("You do not exist, go away!");
	    return 1;
	  }
	mems = video_grp->gr_mem;
	realname = realuser->pw_name;
	ok = 0;
	for (; *mems; mems++)
	  if (!strcmp(realname, *mems))
	    {
	      ok = 1;
	      break;
	    }
	endgrent();
	if (!ok)
	  {
	    P("Sorry, you need to be in the group 'video'.");
	    return 1;
	  }
      }
    endpwent();
  }
  
  
  if (!get && !set)
    {
      P("\n");
      P("If the program is abnormally aborted the may be some residual");
      P("effects on the terminal. the following commands should reset it:");
      P("");
      P("    stty icanon echo");
      P("    echo -en '\\e[?25h'");
      P("");
      P("\n\n\n");
    }
  
  
  if (!get && !set)
    {
      /* Get the size of the terminal */
      if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == -1)
	perror(*argv);
      else
	cols = win.ws_col;
      
      /* Hide cursor */
      printf("%s", "\033[?25l");
      fflush(stdout);
      
      /* stty -icanon -echo */
      if (tcgetattr(STDIN_FILENO, &stty))
	{
	  perror(*argv);
	  return 1;
	}
      saved_stty = stty;
      stty.c_lflag &= (tcflag_t)~(ICANON | ECHO);
      if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &stty))
	{
	  perror(*argv);
	  return 1;
	}
    }
  
  
  /* Fork to diminish risk of unclean exit */
  if (!get && !set)
    {
      pid = FORK();
      if (pid == (pid_t)-1)
	{
	  perror(*argv);
	  pid = 0;
	}
    }
  
  if (pid)
    waitpid(pid, NULL, 0);
  else
    {
      float brightness = 0;
      int nbrightness = 0;
      
      if (!get && !set)
	{
	  line = malloc((size_t)cols * 3 * sizeof(char));
	  space = malloc((size_t)cols * sizeof(char));
	  for (i = 0; i < (size_t)cols; i++)
	    {
	      *(line + i * 3 + 0) = (char)(0xE2);
	      *(line + i * 3 + 1) = (char)(0x94);
	      *(line + i * 3 + 2) = (char)(0x80);
	      *(space + i) = ' ';
	    }
	  *(space + cols - 1) = 0;
	  *(line + (cols - 2) * 3) = 0;
	}
      
      if (ndevices)
	{
	  char* device;
	  for (i = 0; i < ndevices; i++)
	    {
	      device = *(devices + i);
	      for (j = 0; *(device + j); j++)
		if (*(device + j) == '/')
		  {
		    device += j + 1;
		    j = -1;
		  }
	      if (get)
		{
		  float value = getbrightness(device);
		  if (value >= 0.f)
		    {
		      brightness += value;
		      nbrightness++;
		    }
		}
	      else if (set)
		setbrightness(device, set);
	      else
		adjust(cols, device);
	    }
	}
      else
	{
	  struct dirent* ent;
	  DIR* dir = opendir(BACKLIGHT_DIR);
	  if (dir)
	    {
	      char* device;
	      while ((ent = readdir(dir)))
		{
		  device = ent->d_name;
		  if (all || (strstr(device, "acpi_video") != device))
		    if (*device && (*device != '.'))
		      {
			if (get)
			  {
			    float value = getbrightness(device);
			    if (value >= 0.f)
			      {
				brightness += value;
				nbrightness++;
			      }
			  }
			else if (set)
			  setbrightness(device, set);
			else
			  adjust(cols, device);
		      }
		}
	      closedir(dir);
	    }
	}
      
      if (!get && !set)
	{
	  free(line);
	  free(space);
	}
      else if (get)
	{
	  if (nbrightness)
	    {
	      brightness *= 100.f;
	      brightness /= (float)nbrightness;
	      printf("%.2f%%\n", (double)brightness);
	      fflush(stdout);
	    }
	  else
	    {
	      printf("%s\n", "100.00%");
	      fflush(stdout);
	    }
	}
    }
  
  
  if (!get && !set)
    {
      /* `stty icanon echo` */
      if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved_stty))
	{
	  perror(*argv);
	  return 1;
	}
      
      /* Show cursor */
      printf("%s", "\033[?25h");
      fflush(stdout);
    }
  
  return 0;
}
Esempio n. 25
0
CC_FILE_ERROR AsciiFilter::loadCloudFromFormatedAsciiFile(	const QString& filename,
															ccHObject& container,
															const AsciiOpenDlg::Sequence& openSequence,
															char separator,
															unsigned approximateNumberOfLines,
															qint64 fileSize,
															unsigned maxCloudSize,
															unsigned skipLines,
															LoadParameters& parameters)
{
	//we may have to "slice" clouds when opening them if they are too big!
	maxCloudSize = std::min(maxCloudSize,CC_MAX_NUMBER_OF_POINTS_PER_CLOUD);
	unsigned cloudChunkSize = std::min(maxCloudSize,approximateNumberOfLines);
	unsigned cloudChunkPos = 0;
	unsigned chunkRank = 1;

	//we initialize the loading accelerator structure and point cloud
	int maxPartIndex = -1;
	cloudAttributesDescriptor cloudDesc = prepareCloud(openSequence, cloudChunkSize, maxPartIndex, separator, chunkRank);

	if (!cloudDesc.cloud)
		return CC_FERR_NOT_ENOUGH_MEMORY;

	//we re-open the file (ASCII mode)
	QFile file(filename);
	if (!file.open(QFile::ReadOnly))
	{
		//we clear already initialized data
		clearStructure(cloudDesc);
		return CC_FERR_READING;
	}
	QTextStream stream(&file);

	//we skip lines as defined on input
	{
		for (unsigned i = 0; i < skipLines; ++i)
		{
			stream.readLine();
		}
	}

	//progress indicator
	ccProgressDialog pdlg(true, parameters.parentWidget);
	CCLib::NormalizedProgress nprogress(&pdlg, approximateNumberOfLines);
	if (parameters.parentWidget)
	{
		pdlg.setMethodTitle(QObject::tr("Open ASCII file [%1]").arg(filename));
		pdlg.setInfo(QObject::tr("Approximate number of points: %1").arg(approximateNumberOfLines));
		pdlg.start();
	}

	//buffers
	ScalarType D = 0;
	CCVector3d P(0,0,0);
	CCVector3d Pshift(0,0,0);
	CCVector3 N(0,0,0);
	ccColor::Rgb col;

	//other useful variables
	unsigned linesRead = 0;
	unsigned pointsRead = 0;

	CC_FILE_ERROR result = CC_FERR_NO_ERROR;

	//main process
	unsigned nextLimit = /*cloudChunkPos+*/cloudChunkSize;
	QString currentLine = stream.readLine();
	while (!currentLine.isNull())
	{
		++linesRead;

		//comment
		if (currentLine.startsWith("//"))
		{
			currentLine = stream.readLine();
			continue;
		}

		if (currentLine.size() == 0)
		{
			ccLog::Warning("[AsciiFilter::Load] Line %i is corrupted (empty)!",linesRead);
			currentLine = stream.readLine();
			continue;
		}

		//if we have reached the max. number of points per cloud
		if (pointsRead == nextLimit)
		{
			ccLog::PrintDebug("[ASCII] Point %i -> end of chunk (%i points)",pointsRead,cloudChunkSize);

			//we re-evaluate the average line size
			{
				double averageLineSize = static_cast<double>(file.pos())/(pointsRead+skipLines);
				double newNbOfLinesApproximation = std::max(1.0, static_cast<double>(fileSize)/averageLineSize - static_cast<double>(skipLines));

				//if approximation is smaller than actual one, we add 2% by default
				if (newNbOfLinesApproximation <= pointsRead)
				{
					newNbOfLinesApproximation = std::max(static_cast<double>(cloudChunkPos+cloudChunkSize)+1.0,static_cast<double>(pointsRead) * 1.02);
				}
				approximateNumberOfLines = static_cast<unsigned>(ceil(newNbOfLinesApproximation));
				ccLog::PrintDebug("[ASCII] New approximate nb of lines: %i",approximateNumberOfLines);
			}

			//we try to resize actual clouds
			if (cloudChunkSize < maxCloudSize || approximateNumberOfLines-cloudChunkPos <= maxCloudSize)
			{
				ccLog::PrintDebug("[ASCII] We choose to enlarge existing clouds");

				cloudChunkSize = std::min(maxCloudSize,approximateNumberOfLines-cloudChunkPos);
				if (!cloudDesc.cloud->reserve(cloudChunkSize))
				{
					ccLog::Error("Not enough memory! Process stopped ...");
					result = CC_FERR_NOT_ENOUGH_MEMORY;
					break;
				}
			}
			else //otherwise we have to create new clouds
			{
				ccLog::PrintDebug("[ASCII] We choose to instantiate new clouds");

				//we store (and resize) actual cloud
				if (!cloudDesc.cloud->resize(cloudChunkSize))
					ccLog::Warning("Memory reallocation failed ... some memory may have been wasted ...");
				if (!cloudDesc.scalarFields.empty())
				{
					for (unsigned k=0; k<cloudDesc.scalarFields.size(); ++k)
						cloudDesc.scalarFields[k]->computeMinAndMax();
					cloudDesc.cloud->setCurrentDisplayedScalarField(0);
					cloudDesc.cloud->showSF(true);
				}
				//we add this cloud to the output container
				container.addChild(cloudDesc.cloud);
				cloudDesc.reset();

				//and create new one
				cloudChunkPos = pointsRead;
				cloudChunkSize = std::min(maxCloudSize,approximateNumberOfLines-cloudChunkPos);
				cloudDesc = prepareCloud(openSequence, cloudChunkSize, maxPartIndex, separator, ++chunkRank);
				if (!cloudDesc.cloud)
				{
					ccLog::Error("Not enough memory! Process stopped ...");
					break;
				}
				cloudDesc.cloud->setGlobalShift(Pshift);
			}

			//we update the progress info
			if (parameters.parentWidget)
			{
				nprogress.scale(approximateNumberOfLines, 100, true);
				pdlg.setInfo(QObject::tr("Approximate number of points: %1").arg(approximateNumberOfLines));
			}

			nextLimit = cloudChunkPos+cloudChunkSize;
		}

		//we split current line
		QStringList parts = currentLine.split(separator,QString::SkipEmptyParts);

		int nParts = parts.size();
		if (nParts > maxPartIndex)
		{
			//(X,Y,Z)
			if (cloudDesc.xCoordIndex >= 0)
				P.x = parts[cloudDesc.xCoordIndex].toDouble();
			if (cloudDesc.yCoordIndex >= 0)
				P.y = parts[cloudDesc.yCoordIndex].toDouble();
			if (cloudDesc.zCoordIndex >= 0)
				P.z = parts[cloudDesc.zCoordIndex].toDouble();

			//first point: check for 'big' coordinates
			if (pointsRead == 0)
			{
				if (HandleGlobalShift(P,Pshift,parameters))
				{
					cloudDesc.cloud->setGlobalShift(Pshift);
					ccLog::Warning("[ASCIIFilter::loadFile] Cloud has been recentered! Translation: (%.2f ; %.2f ; %.2f)",Pshift.x,Pshift.y,Pshift.z);
				}
			}

			//add point
			cloudDesc.cloud->addPoint(CCVector3::fromArray((P+Pshift).u));

			//Normal vector
			if (cloudDesc.hasNorms)
			{
				if (cloudDesc.xNormIndex >= 0)
					N.x = static_cast<PointCoordinateType>(parts[cloudDesc.xNormIndex].toDouble());
				if (cloudDesc.yNormIndex >= 0)
					N.y = static_cast<PointCoordinateType>(parts[cloudDesc.yNormIndex].toDouble());
				if (cloudDesc.zNormIndex >= 0)
					N.z = static_cast<PointCoordinateType>(parts[cloudDesc.zNormIndex].toDouble());
				cloudDesc.cloud->addNorm(N);
			}

			//Colors
			if (cloudDesc.hasRGBColors)
			{
				if (cloudDesc.iRgbaIndex >= 0)
				{
					const uint32_t rgb = parts[cloudDesc.iRgbaIndex].toInt();
					col.r = ((rgb >> 16) & 0x0000ff);
					col.g = ((rgb >> 8 ) & 0x0000ff);
					col.b = ((rgb      ) & 0x0000ff);

				}
				else if (cloudDesc.fRgbaIndex >= 0)
				{
					const float rgbf = parts[cloudDesc.fRgbaIndex].toFloat();
					const uint32_t rgb = (uint32_t)(*((uint32_t*)&rgbf));
					col.r = ((rgb >> 16) & 0x0000ff);
					col.g = ((rgb >> 8 ) & 0x0000ff);
					col.b = ((rgb      ) & 0x0000ff);
				}
				else
				{
					if (cloudDesc.redIndex >= 0)
					{
						float multiplier = cloudDesc.hasFloatRGBColors[0] ? static_cast<float>(ccColor::MAX) : 1.0f;
						col.r = static_cast<ColorCompType>(parts[cloudDesc.redIndex].toFloat() * multiplier);
					}
					if (cloudDesc.greenIndex >= 0)
					{
						float multiplier = cloudDesc.hasFloatRGBColors[1] ? static_cast<float>(ccColor::MAX) : 1.0f;
						col.g = static_cast<ColorCompType>(parts[cloudDesc.greenIndex].toFloat() * multiplier);
					}
					if (cloudDesc.blueIndex >= 0)
					{
						float multiplier = cloudDesc.hasFloatRGBColors[2] ? static_cast<float>(ccColor::MAX) : 1.0f;
						col.b = static_cast<ColorCompType>(parts[cloudDesc.blueIndex].toFloat() * multiplier);
					}
				}
				cloudDesc.cloud->addRGBColor(col.rgb);
			}
			else if (cloudDesc.greyIndex >= 0)
Esempio n. 26
0
/*
	ls command
*/
LOCAL	void	cmd_ls(INT ac, B *av[])
{
	ER	er;
	DIR	*dir;
	struct dirent	ent, *entp;
	B	path[FILENAME_MAX + 1];
	struct stat_ms	st;
	struct tm	ctm;
	INT	n, opt;

	opt = 0;
	for (n = 1; n < ac; n++) {
		if (*av[n] != '-') break;
		switch(*(av[n] + 1)) {
		case 't':	opt |= 0x01;	break;
		case 'a':	opt |= 0x02;	break;
		}
	}

	if (ac <= n) {
		fs_getcwd(path, sizeof(path) -1);
	} else {
		strcpy(path, av[n]);
	}

	dir = opendir(path);
	if (dir == NULL) {
		P("opendir ERR\n");
		return;
	}

	n = strlen(path);
	path[n++] = '/';

	while (readdir_r(dir, &ent, &entp) >= 0) {
		if (entp == NULL) break;
		if (strcmp(entp->d_name, ".") == 0 ||
		    strcmp(entp->d_name, "..") == 0) continue;

		strcpy(&path[n],  entp->d_name);
		er = fs_stat_ms(path, &st);
		if (er < E_OK) {
			P("fs_stat(%s) ERR [%#x]\n", path, er);
			continue;
		}
		dt_localtime_ms(&st.st_mtime, NULL, &ctm);

		if (S_ISDIR(st.st_mode))	strcat(path, "/");
		else if (! S_ISREG(st.st_mode)) strcat(path, "#");

		P("%-16s %8d %04o %d/%02d/%02d %02d:%02d:%02d",
			&path[n], st.st_size, st.st_mode & 0x1FF,
			ctm.tm_year + 1900, ctm.tm_mon + 1, ctm.tm_mday,
			ctm.tm_hour, ctm.tm_min, ctm.tm_sec);
		if (opt & 0x01) {
			dt_localtime_ms(&st.st_ctime, NULL, &ctm);
			P(" c:%d/%02d/%02d %02d:%02d:%02d",
				ctm.tm_year + 1900, ctm.tm_mon + 1, ctm.tm_mday,
				ctm.tm_hour, ctm.tm_min, ctm.tm_sec);
			dt_localtime_ms(&st.st_atime, NULL, &ctm);
			P(" a:%d/%02d/%02d",
				ctm.tm_year + 1900, ctm.tm_mon + 1, ctm.tm_mday);
		}
		if (opt & 0x02) {
			P(" b:%-4d m:%#04x i:%d",
				(W)st.st_blocks, st.st_mode, (W)st.st_ino);
		}
		P("\n");
	}

	closedir(dir);
}
Esempio n. 27
0
 void TypeOfFE_RTmodif::FB(const bool * whatd,const Mesh & Th,const Triangle & K,const R2 & PHat,RNMK_ & val) const
{ //  
//  const Triangle & K(FE.T);
  R2 P(K(PHat));
  R2 A(K[0]), B(K[1]),C(K[2]);
  R la=1-PHat.x-PHat.y,lb=PHat.x,lc=PHat.y; 
  R2 Dla(K.H(0)), Dlb(K.H(1)), Dlc(K.H(2));
  if (val.N() <3) 
   throwassert(val.N() >=3);
  throwassert(val.M()==2 );

  R2 AB(A,B),AC(A,C),BA(B,A),BC(B,C),CA(C,A),CB(C,B);

  R aa0= 1./(((AB,Dlb) + (AC,Dlc))*K.area);
  R aa1= 1./(((BA,Dla) + (BC,Dlc))*K.area);
  R aa2= 1./(((CA,Dla) + (CB,Dlb))*K.area);
  int i=0;
  R a0=   &K[ (i+1)%3] < &K[ (i+2)%3] ? aa0 : -aa0 ;
  i=1;
  R a1=   &K[ (i+1)%3] < &K[ (i+2)%3] ? aa1 : -aa1 ;
  i=2;
  R a2=   &K[ (i+1)%3] < &K[ (i+2)%3] ? aa2 : -aa2 ;
 // if (Th(K)< 2) cout << Th(K) << " " <<  A << " "  << B << " " << C << "; " <<  a0 << " " << a1 << " "<< a2 << endl;;
 
  R2 Va= AB*(lb*a0) + AC*(lc*a0);
  R2 Vb= BA*(la*a1) + BC*(lc*a1);
  R2 Vc= CA*(la*a2) + CB*(lb*a2);
  R2 Va_x= AB*(Dlb.x*a0) + AC*(Dlc.x*a0);
  R2 Vb_x= BA*(Dla.x*a1) + BC*(Dlc.x*a1);
  R2 Vc_x= CA*(Dla.x*a2) + CB*(Dlb.x*a2);
  R2 Va_y= AB*(Dlb.y*a0) + AC*(Dlc.y*a0);
  R2 Vb_y= BA*(Dla.y*a1) + BC*(Dlc.y*a1);
  R2 Vc_y= CA*(Dla.y*a2) + CB*(Dlb.y*a2);
 
 if( whatd[op_id])
  {
    RN_ f0(val('.',0,0)); 
    RN_ f1(val('.',1,0)); 
    
    f0[0] = Va.x;
    f1[0] = Va.y;
    
    f0[1] = Vb.x;
    f1[1] = Vb.y;
    
    f0[2] = Vc.x;
    f1[2] = Vc.y;
  }
 // ----------------
 if( whatd[op_dx])
   {
     val(0,0,1) =  Va_x.x;  
     val(0,1,1) =  Va_x.y;  
     
     val(1,0,1) =  Vb_x.x;  
     val(1,1,1) =  Vb_x.y;  
     
     val(2,0,1) =  Vc_x.x;  
     val(2,1,1) =  Vc_x.y;
   }
 
 if( whatd[op_dy])
   {
     val(0,0,2) =  Va_y.x;  
     val(0,1,2) =  Va_y.y;  

     val(1,0,2) =  Vb_y.x;  
     val(1,1,2) =  Vb_y.y;  
     
  val(2,0,2) =  Vc_y.x;  
  val(2,1,2) =  Vc_y.y;  
   }
 
}
Esempio n. 28
0
/*
	cp command
*/
LOCAL	void	cmd_cp(INT ac, B *av[])
{
	INT	fsz, n, wofs, wlen;
	FILE	*sfp, *dfp;
	UB	*buf = NULL;
	B	dst[FILENAME_MAX + 1], *p;
	struct stat_ms	st;

	if (ac < 3) return;

	wofs = (ac < 4) ? 0 : strtol(av[3], NULL, 0);
	wlen = (ac < 5) ? 0 : strtol(av[4], NULL, 0);

	sfp = fopen(av[1], "r");
	if (!sfp) {
		P("%s open ERR\n", av[1]);
		goto exit0;
	}

	fseek(sfp, 0, SEEK_END);
	fsz = ftell(sfp);
	fseek(sfp, 0, SEEK_SET);
	if (fsz > 0) {
		buf = malloc(fsz + 1);
		if (!buf) {
			P("No memory\n");
			goto exit1;
		}
		if (fread(buf, fsz, 1, sfp) != 1) {
			P("read ERR\n");
			goto exit2;
		}
	}

	n = strlen(av[2]);
	if (n > FILENAME_MAX) {
		P("too long path: %s\n", av[2]);
		goto exit2;
	}
	strcpy(dst, av[2]);
	if (dst[n - 1] == '/' ||
		(fs_stat_ms(dst, &st) >= E_OK && S_ISDIR(st.st_mode)) ) {
		if (dst[n - 1] != '/') dst[n++] = '/';
		p = strrchr(av[1], '/');
		if (p != NULL)	p++;
		else		p = av[1];
		if (strlen(p) + n > FILENAME_MAX) {
			P("too long path: %s/%s\n", av[2], av[1]);
			goto exit2;
		}
		strcpy(&dst[n], p);
	}

	if (wofs > 0) {
		dfp = fopen(dst, "r+");
		if (!dfp) {
			P("%s open ERR\n", dst);
			goto exit2;
		}
		if (fseek(dfp, wofs, SEEK_SET) < 0) {
			P("%s fseek(%d) ERR\n", dst, wofs);
			goto exit3;
		}
	} else {
		dfp = fopen(dst, (wofs < 0) ? "a" : "w");
		if (!dfp) {
			P("%s open ERR\n", dst);
			goto exit2;
		}
	}
	if (fsz > 0) {
		if (wlen <= 0 || wlen > fsz) wlen = fsz;
		if (fwrite(buf, wlen, 1, dfp) != 1) {
			P("write ERR\n");
			goto exit3;
		}
		P("%s ", av[1]);
		if (fsz != wlen) P("[%d bytes] ", wlen);
		if (wofs == 0) {
			P("is copied to %s\n", dst);
		} else if (wofs < 0) {
			P("is appended to %s\n", dst);
		} else {
			P("is overwrited to %s at %d\n", dst, wofs);
		}
	}
exit3:
	fclose(dfp);
exit2:
	free(buf);
exit1:
	fclose(sfp);
exit0:
	;
}
Esempio n. 29
0
static void ext_vdef() {
	if (artificial_cell) { return; }
		if (electrode_current) {
			P("#if EXTRACELLULAR\n");
			P(" _nd = _ml->_nodelist[_iml];\n");
			P(" if (_nd->_extnode) {\n");
			P("    _v = NODEV(_nd) +_nd->_extnode->_v[0];\n");
			P(" }else\n");
			P("#endif\n");
			P(" {\n");
#if CACHEVEC == 0
			P("    _v = NODEV(_nd);\n");
#else
			P("#if CACHEVEC\n");
			P("  if (use_cachevec) {\n");
			P("    _v = VEC_V(_ni[_iml]);\n");
			P("  }else\n");
			P("#endif\n");
			P("  {\n");
			P("    _nd = _ml->_nodelist[_iml];\n");
			P("    _v = NODEV(_nd);\n");
			P("  }\n");
#endif
			
			P(" }\n");
		}else{
#if CACHEVEC == 0
			P(" _nd = _ml->_nodelist[_iml];\n");
			P(" _v = NODEV(_nd);\n");
#else
			P("#if CACHEVEC\n");
			P("  if (use_cachevec) {\n");
			P("    _v = VEC_V(_ni[_iml]);\n");
			P("  }else\n");
			P("#endif\n");
			P("  {\n");
			P("    _nd = _ml->_nodelist[_iml];\n");
			P("    _v = NODEV(_nd);\n");
			P("  }\n");
#endif
		}
}
Esempio n. 30
0
    V(pos1),
    V(pos2),

    V(velocity),
    V(avelocity),
    I(mass),
    F(air_finished),
    F(gravity),

    E(goalentity),
    E(movetarget),
    F(yaw_speed),
    F(ideal_yaw),

    F(nextthink),
    P(prethink, P_prethink),
    P(think, P_think),
    P(blocked, P_blocked),
    P(touch, P_touch),
    P(use, P_use),
    P(pain, P_pain),
    P(die, P_die),

    F(touch_debounce_time),
    F(pain_debounce_time),
    F(damage_debounce_time),
    F(fly_sound_debounce_time),
    F(last_move_time),

    I(health),
    I(max_health),