bool LightingSimulationControl_Impl::isRunSimulationforDesignDaysDefaulted() const {
   return isEmpty(OS_LightingSimulationControlFields::RunSimulationforDesignDays);
 }
Exemplo n.º 2
0
void convertToPostfix( char infix[], char postfix[] ){
	/* create the stack and add left bracket
	 * My stack implimentation uses a single node as the 
	 * head node (called 'stack') which only points to the first 
	 * item of the stack and itself holds no data. if the stack is
	 * empty the head node's nextPtr field will be NULL. Otherwise it
	 * will maintain a link to the actual first node in the stack */
	StackNodePtr stack = malloc(sizeN);
	push(&stack, '(');
	
	//append the ')' to the end of the infix expression
	int inf;
	for (inf = 0; inf < 79; inf++){
		if (infix[inf] == '\0'){
			infix[inf] = ')';
			infix[inf+1] = '\0';
			break;
		}
	}
	
	//begin conversion
	inf = 0;
	int post = 0;
	
	//while stack isnt empty
	while (!isEmpty(stack) && inf < 80){
		//look at next character in postfix
		char c = infix[inf];
		
		//check if operator
		if (isOperator(c)){
			//character is an operator
			
			if (isOperator(c) == 5){
				/* operator is right bracket so pop all operators
				 * from stack onto postfix until hit left bracket */				
				while (isOperator(stackTop(stack)) != 4){
					postfix[post++] = pop(&stack);
				}
				
				//finally pop the left bracket
				pop(&stack);
				inf++;
				
			} else if (precedence(stackTop(stack), c) >= 0 && isOperator(stackTop(stack)) != 4){
				/* operator on stack is higher/equal precedence, 
				 * have to pop it */
				postfix[post++] = pop(&stack);
				
			} else {
				/* character is operator of lower precedence (or
				 * is left bracket), so push onto stack */
				push(&stack, c);
				inf++;
			}
		} else {
			//character is a digit, so put onto postfix
			postfix[post++] = c;
			inf++;
		}
	}
	
}
Exemplo n.º 3
0
Arquivo: list.cpp Projeto: jakwuh/bsu
const Node& List::front() {
	if (isEmpty()) throw Empty();
	return *head;
}
 bool CoilHeatingLowTempRadiantVarFlow_Impl::isHeatingControlThrottlingRangeDefaulted() const 
 {
   return isEmpty(OS_Coil_Heating_LowTemperatureRadiant_VariableFlowFields::HeatingControlThrottlingRange);
 }
Real32 SphereVolume::getScalarVolume (void) const
{
    return isEmpty() ? 0.0f : (4.f / 3.f * Pi * _radius * _radius * _radius);
}
Exemplo n.º 6
0
 bool CoilHeatingDesuperheater_Impl::isHeatReclaimRecoveryEfficiencyDefaulted() const {
     return isEmpty(OS_Coil_Heating_DesuperheaterFields::HeatReclaimRecoveryEfficiency);
 }
Exemplo n.º 7
0
void EQSANSLoad::exec()
{
  // Verify the validity of the inputs
  //TODO: this should be done by the new data management algorithm used for
  // live data reduction (when it's implemented...)
  const std::string fileName = getPropertyValue("Filename");
  EventWorkspace_sptr inputEventWS = getProperty("InputWorkspace");
  if (fileName.size()==0 && !inputEventWS)
  {
    g_log.error() << "EQSANSLoad input error: Either a valid file path or an input workspace must be provided" << std::endl;
    throw std::runtime_error("EQSANSLoad input error: Either a valid file path or an input workspace must be provided");
  }
  else if (fileName.size()>0 && inputEventWS)
  {
    g_log.error() << "EQSANSLoad input error: Either a valid file path or an input workspace must be provided, but not both" << std::endl;
    throw std::runtime_error("EQSANSLoad input error: Either a valid file path or an input workspace must be provided, but not both");
  }

  // Read in default TOF cuts
  const bool skipTOFCorrection = getProperty("SkipTOFCorrection");
  m_low_TOF_cut = getProperty("LowTOFCut");
  m_high_TOF_cut = getProperty("HighTOFCut");

  // Read in default beam center
  m_center_x = getProperty("BeamCenterX");
  m_center_y = getProperty("BeamCenterY");
  const bool noBeamCenter = getProperty("NoBeamCenter");

  // Reduction property manager
  const std::string reductionManagerName = getProperty("ReductionProperties");
  boost::shared_ptr<PropertyManager> reductionManager;
  if (PropertyManagerDataService::Instance().doesExist(reductionManagerName))
  {
    reductionManager = PropertyManagerDataService::Instance().retrieve(reductionManagerName);
  }
  else
  {
    reductionManager = boost::make_shared<PropertyManager>();
    PropertyManagerDataService::Instance().addOrReplace(reductionManagerName, reductionManager);
  }

  if (!reductionManager->existsProperty("LoadAlgorithm"))
  {
    AlgorithmProperty *loadProp = new AlgorithmProperty("LoadAlgorithm");
    setPropertyValue("InputWorkspace", "");
    setProperty("NoBeamCenter", false);
    loadProp->setValue(toString());
    reductionManager->declareProperty(loadProp);
  }

  if (!reductionManager->existsProperty("InstrumentName"))
  {
    reductionManager->declareProperty(new PropertyWithValue<std::string>("InstrumentName", "EQSANS") );
  }

  // Output log
  m_output_message = "";

  // Check whether we need to load the data
  if (!inputEventWS)
  {
    const bool loadMonitors = getProperty("LoadMonitors");
    IAlgorithm_sptr loadAlg = createChildAlgorithm("LoadEventNexus", 0, 0.2);
    loadAlg->setProperty("LoadMonitors", loadMonitors);
    loadAlg->setProperty("MonitorsAsEvents", false);
    loadAlg->setProperty("Filename", fileName);
    if (skipTOFCorrection)
    {
      if (m_low_TOF_cut>0.0) loadAlg->setProperty("FilterByTofMin", m_low_TOF_cut);
      if (m_high_TOF_cut>0.0) loadAlg->setProperty("FilterByTofMax", m_high_TOF_cut);
    }
    loadAlg->execute();
    IEventWorkspace_sptr dataWS_asWks = loadAlg->getProperty("OutputWorkspace");
    dataWS = boost::dynamic_pointer_cast<MatrixWorkspace>(dataWS_asWks);

    // Get monitor workspace as necessary
    std::string mon_wsname = getPropertyValue("OutputWorkspace")+"_monitors";
    if (loadMonitors && loadAlg->existsProperty("MonitorWorkspace"))
    {
      MatrixWorkspace_sptr monWS = loadAlg->getProperty("MonitorWorkspace");
      declareProperty(new WorkspaceProperty<>("MonitorWorkspace",
          mon_wsname, Direction::Output), "Monitors from the Event NeXus file");
      setProperty("MonitorWorkspace", monWS);
    }
  } else {
    MatrixWorkspace_sptr outputWS = getProperty("OutputWorkspace");
    EventWorkspace_sptr outputEventWS = boost::dynamic_pointer_cast<EventWorkspace>(outputWS);
    if (inputEventWS != outputEventWS)
    {
      IAlgorithm_sptr copyAlg = createChildAlgorithm("CloneWorkspace", 0, 0.2);
      copyAlg->setProperty("InputWorkspace", inputEventWS);
      copyAlg->executeAsChildAlg();
      Workspace_sptr dataWS_asWks = copyAlg->getProperty("OutputWorkspace");
      dataWS = boost::dynamic_pointer_cast<MatrixWorkspace>(dataWS_asWks);
    } else {
      dataWS = boost::dynamic_pointer_cast<MatrixWorkspace>(inputEventWS);
    }
  }

  // Get the sample-detector distance
  double sdd = 0.0;
  const double sample_det_dist = getProperty("SampleDetectorDistance");
  if (!isEmpty(sample_det_dist))
  {
    sdd = sample_det_dist;
  } else {
    if (!dataWS->run().hasProperty("detectorZ"))
    {
      g_log.error() << "Could not determine Z position: the SampleDetectorDistance property was not set "
          "and the run logs do not contain the detectorZ property" << std::endl;
      throw std::invalid_argument("Could not determine Z position: stopping execution");
    }
    Mantid::Kernel::Property* prop = dataWS->run().getProperty("detectorZ");
    Mantid::Kernel::TimeSeriesProperty<double>* dp = dynamic_cast<Mantid::Kernel::TimeSeriesProperty<double>* >(prop);
    sdd = dp->getStatistics().mean;

    // Modify SDD according to offset if given
    const double sample_det_offset = getProperty("SampleDetectorDistanceOffset");
    if (!isEmpty(sample_det_offset))
    {
      sdd += sample_det_offset;
    }
  }
  dataWS->mutableRun().addProperty("sample_detector_distance", sdd, "mm", true);

  // Move the detector to its correct position
  IAlgorithm_sptr mvAlg = createChildAlgorithm("MoveInstrumentComponent", 0.2, 0.4);
  mvAlg->setProperty<MatrixWorkspace_sptr>("Workspace", dataWS);
  mvAlg->setProperty("ComponentName", "detector1");
  mvAlg->setProperty("Z", sdd/1000.0);
  mvAlg->setProperty("RelativePosition", false);
  mvAlg->executeAsChildAlg();
  g_log.information() << "Moving detector to " << sdd/1000.0 << " meters" << std::endl;
  m_output_message += "   Detector position: " + Poco::NumberFormatter::format(sdd/1000.0, 3) + " m\n";

  // Get the run number so we can find the proper config file
  int run_number = 0;
  std::string config_file = "";
  if (dataWS->run().hasProperty("run_number"))
  {
    Mantid::Kernel::Property* prop = dataWS->run().getProperty("run_number");
    Mantid::Kernel::PropertyWithValue<std::string>* dp = dynamic_cast<Mantid::Kernel::PropertyWithValue<std::string>* >(prop);
    const std::string run_str = *dp;
    Poco::NumberParser::tryParse(run_str, run_number);
    // Find a proper config file
    config_file = findConfigFile(run_number);
  } else {
    g_log.error() << "Could not find run number for workspace " << getPropertyValue("OutputWorkspace") << std::endl;
    m_output_message += "   Could not find run number for data file\n";
  }

  // Process the config file
  bool use_config = getProperty("UseConfig");
  if (use_config && config_file.size()>0)
  {
    // Special case to force reading the beam center from the config file
    // We're adding this to be compatible with the original EQSANS load
    // written in python
    if (m_center_x==0.0 && m_center_y==0.0)
    {
      setProperty("UseConfigBeam", true);
    }

    readConfigFile(config_file);
  } else if (use_config) {
    use_config = false;
    g_log.error() << "Cound not find config file for workspace " << getPropertyValue("OutputWorkspace") << std::endl;
    m_output_message += "   Could not find configuration file for run " + Poco::NumberFormatter::format(run_number) + "\n";
  }

  // If we use the config file, move the moderator position
  if (use_config)
  {
      if (m_moderator_position > -13.0)
        g_log.error() << "Moderator position seems close to the sample, please check" << std::endl;
      g_log.information() << "Moving moderator to " << m_moderator_position << std::endl;
      m_output_message += "   Moderator position: " + Poco::NumberFormatter::format(m_moderator_position, 3) + " m\n";
      mvAlg = createChildAlgorithm("MoveInstrumentComponent", 0.4, 0.45);
      mvAlg->setProperty<MatrixWorkspace_sptr>("Workspace", dataWS);
      mvAlg->setProperty("ComponentName", "moderator");
      mvAlg->setProperty("Z", m_moderator_position);
      mvAlg->setProperty("RelativePosition", false);
      mvAlg->executeAsChildAlg();
  }

  // Get source aperture radius
  getSourceSlitSize();

  // Move the beam center to its proper position
  if (!noBeamCenter)
  {
    if (isEmpty(m_center_x) || isEmpty(m_center_y))
    {
      if (reductionManager->existsProperty("LatestBeamCenterX") &&
          reductionManager->existsProperty("LatestBeamCenterY"))
      {
        m_center_x = reductionManager->getProperty("LatestBeamCenterX");
        m_center_y = reductionManager->getProperty("LatestBeamCenterY");
      }
    }
    moveToBeamCenter();

    // Add beam center to reduction properties, as the last beam center position that was used.
    // This will give us our default position next time.
    if (!reductionManager->existsProperty("LatestBeamCenterX"))
      reductionManager->declareProperty(new PropertyWithValue<double>("LatestBeamCenterX", m_center_x) );
    else reductionManager->setProperty("LatestBeamCenterX", m_center_x);
    if (!reductionManager->existsProperty("LatestBeamCenterY"))
      reductionManager->declareProperty(new PropertyWithValue<double>("LatestBeamCenterY", m_center_y) );
    else reductionManager->setProperty("LatestBeamCenterY", m_center_y);
  }

  // Modify TOF
  const bool correct_for_flight_path = getProperty("CorrectForFlightPath");
  double wl_min = 0.0;
  double wl_max = 0.0;
  double wl_combined_max = 0.0;
  if (skipTOFCorrection)
  {
    m_output_message += "    Skipping EQSANS TOF correction: assuming a single frame\n";
    dataWS->mutableRun().addProperty("is_frame_skipping", 0, true);
    if (correct_for_flight_path)
    {
      g_log.error() << "CorrectForFlightPath and SkipTOFCorrection can't be set to true at the same time" << std::endl;
      m_output_message += "    Skipped flight path correction: see error log\n";
    }
  }
  else
  {
    m_output_message += "   Flight path correction ";
    if (!correct_for_flight_path) m_output_message += "NOT ";
    m_output_message += "applied\n";
    DataObjects::EventWorkspace_sptr dataWS_evt = boost::dynamic_pointer_cast<EventWorkspace>(dataWS);
    IAlgorithm_sptr tofAlg = createChildAlgorithm("EQSANSTofStructure", 0.5, 0.7);
    tofAlg->setProperty<EventWorkspace_sptr>("InputWorkspace", dataWS_evt);
    tofAlg->setProperty("LowTOFCut", m_low_TOF_cut);
    tofAlg->setProperty("HighTOFCut", m_high_TOF_cut);
    tofAlg->setProperty("FlightPathCorrection", correct_for_flight_path);
    tofAlg->executeAsChildAlg();
    wl_min = tofAlg->getProperty("WavelengthMin");
    wl_max = tofAlg->getProperty("WavelengthMax");
    if (wl_min != wl_min || wl_max != wl_max)
    {
      g_log.error() << "Bad wavelength range" << std::endl;
      g_log.error() << m_output_message << std::endl;
    }

    const bool frame_skipping = tofAlg->getProperty("FrameSkipping");
    dataWS->mutableRun().addProperty("wavelength_min", wl_min, "Angstrom", true);
    dataWS->mutableRun().addProperty("wavelength_max", wl_max, "Angstrom", true);
    dataWS->mutableRun().addProperty("is_frame_skipping", int(frame_skipping), true);
    wl_combined_max = wl_max;
    m_output_message += "   Wavelength range: " + Poco::NumberFormatter::format(wl_min, 1)
        + " - " + Poco::NumberFormatter::format(wl_max, 1);
    if (frame_skipping)
    {
      const double wl_min2 = tofAlg->getProperty("WavelengthMinFrame2");
      const double wl_max2 = tofAlg->getProperty("WavelengthMaxFrame2");
      wl_combined_max = wl_max2;
      dataWS->mutableRun().addProperty("wavelength_min_frame2", wl_min2, "Angstrom", true);
      dataWS->mutableRun().addProperty("wavelength_max_frame2", wl_max2, "Angstrom", true);
      m_output_message += " and " + Poco::NumberFormatter::format(wl_min2, 1)
          + " - " + Poco::NumberFormatter::format(wl_max2, 1) + " Angstrom\n";
    } else
      m_output_message += " Angstrom\n";
  }

  // Convert to wavelength
  const double ssd = fabs(dataWS->getInstrument()->getSource()->getPos().Z())*1000.0;
  const double conversion_factor = 3.9560346 / (sdd+ssd);
  m_output_message += "   TOF to wavelength conversion factor: " + Poco::NumberFormatter::format(conversion_factor) + "\n";

  if (skipTOFCorrection)
  {
    DataObjects::EventWorkspace_sptr dataWS_evt = boost::dynamic_pointer_cast<EventWorkspace>(dataWS);
    if (dataWS_evt->getNumberEvents()==0)
      throw std::invalid_argument("No event to process: check your TOF cuts");
    wl_min = dataWS_evt->getTofMin()*conversion_factor;
    wl_max = dataWS_evt->getTofMax()*conversion_factor;
    wl_combined_max = wl_max;
    g_log.information() << "Wavelength range: " << wl_min << " to " << wl_max << std::endl;
    dataWS->mutableRun().addProperty("wavelength_min", wl_min, "Angstrom", true);
    dataWS->mutableRun().addProperty("wavelength_max", wl_max, "Angstrom", true);
  }

  IAlgorithm_sptr scAlg = createChildAlgorithm("ScaleX", 0.7, 0.71);
  scAlg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", dataWS);
  scAlg->setProperty<MatrixWorkspace_sptr>("OutputWorkspace", dataWS);
  scAlg->setProperty("Factor", conversion_factor);
  scAlg->executeAsChildAlg();
  dataWS->getAxis(0)->setUnit("Wavelength");

  // Rebin so all the wavelength bins are aligned
  const bool preserveEvents = getProperty("PreserveEvents");
  const double wl_step = getProperty("WavelengthStep");
  std::string params = Poco::NumberFormatter::format(wl_min, 2) + ","
		  + Poco::NumberFormatter::format(wl_step, 2) + ","
		  + Poco::NumberFormatter::format(wl_combined_max, 2);
  IAlgorithm_sptr rebinAlg = createChildAlgorithm("Rebin", 0.71, 0.72);
  rebinAlg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", dataWS);
  if (preserveEvents) rebinAlg->setProperty<MatrixWorkspace_sptr>("OutputWorkspace", dataWS);
  rebinAlg->setPropertyValue("Params", params);
  rebinAlg->setProperty("PreserveEvents", preserveEvents);
  rebinAlg->executeAsChildAlg();

  if (!preserveEvents) dataWS = rebinAlg->getProperty("OutputWorkspace");

  dataWS->mutableRun().addProperty("event_ws", getPropertyValue("OutputWorkspace"), true);
  setProperty<MatrixWorkspace_sptr>("OutputWorkspace", boost::dynamic_pointer_cast<MatrixWorkspace>(dataWS));
  //m_output_message = "Loaded " + fileName + '\n' + m_output_message;
  setPropertyValue("OutputMessage", m_output_message);
}
Exemplo n.º 8
0
 bool RefrigerationSystem_Impl::isIntercoolerTypeDefaulted() const {
   return isEmpty(OS_Refrigeration_SystemFields::IntercoolerType);
 }
Exemplo n.º 9
0
 bool RefrigerationSystem_Impl::isShellandCoilIntercoolerEffectivenessDefaulted() const {
   return isEmpty(OS_Refrigeration_SystemFields::ShellandCoilIntercoolerEffectiveness);
 }
Exemplo n.º 10
0
 bool RefrigerationSystem_Impl::isSumUASuctionPipingDefaulted() const {
   return isEmpty(OS_Refrigeration_SystemFields::SumUASuctionPiping);
 }
Exemplo n.º 11
0
 bool RefrigerationSystem_Impl::isEndUseSubcategoryDefaulted() const {
   return isEmpty(OS_Refrigeration_SystemFields::EndUseSubcategory);
 }
Exemplo n.º 12
0
 bool RefrigerationSystem_Impl::isSuctionTemperatureControlTypeDefaulted() const {
   return isEmpty(OS_Refrigeration_SystemFields::SuctionTemperatureControlType);
 }
Exemplo n.º 13
0
 void startObject()
 {
     const char *curname = tagname();
     if (!isEmpty()) 
         xml.appendf("<%s>", tagname());
 }
 bool LightingSimulationControl_Impl::isRunSimulationforWeatherFileRunPeriodsDefaulted() const {
   return isEmpty(OS_LightingSimulationControlFields::RunSimulationforWeatherFileRunPeriods);
 }
Exemplo n.º 15
0
static void *processingThreadFun(void *param)
{
    (void) param;

    while(!end_flag) {
        pthread_mutex_lock(&state_mx);
        while((!new_frame_flag) && (!end_flag)) {
            struct timeval now;
            gettimeofday(&now, NULL);
            struct timespec absTime;
            absTime.tv_sec = now.tv_sec + 3;
            absTime.tv_nsec = now.tv_usec * 1000;
            pthread_cond_timedwait(&state_cv, &state_mx, &absTime);
        }
        new_frame_flag = false;
        pthread_mutex_unlock(&state_mx);
//    printf("Processing frame!\n");
        if(isEmpty(reader)) {
//      printf("No new buffer!\n");
        } else {
//      printf("Processing buffer %d @ %p\n", reader, getCurrentBuffer(reader));
            image_t img = {
                .bitmap = getCurrentBuffer(reader),
                .w = width,
                .h = height,
                .ratio = 1.0f
            };
            struct blob_type blobs_array[MAX_BLOBS] = {{0.0f, 0.0f, 0}};
            struct bloblist_type bloblist = {
                .num_blobs = MAX_BLOBS,
                .blobs = blobs_array
            };

            bool res;
#ifdef OPENCV
            if(facetrack) {
                ltr_int_face_detect(&img, &bloblist);
                res = (bloblist.num_blobs == 1);
            } else {
#endif
                ltr_int_to_stripes(&img);
                res = (ltr_int_stripes_to_blobs(MAX_BLOBS, &bloblist, ltr_int_getMinBlob(mmm), ltr_int_getMaxBlob(mmm), &img) == 0);
#ifdef OPENCV
            }
#endif
            if(res) {
                ltr_int_setBlobs(mmm, blobs_array, bloblist.num_blobs);
                if(!ltr_int_getFrameFlag(mmm)) {
//	  printf("Copying buffer!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
                    memcpy(ltr_int_getFramePtr(mmm), img.bitmap, width * height);
                    ltr_int_setFrameFlag(mmm);
                }
            }
            bufferRead(&reader);
        }
    }
#ifdef OPENCV
    if(facetrack) {
        ltr_int_stop_face_detect();
    }
    ltr_int_cleanup_after_processing();
#endif
    return NULL;
}

bool startProcessing(int w, int h, int buffers, struct mmap_s *mmm_p)
{
    mmm = mmm_p;
    new_frame_flag = 0;
    end_flag = false;
    width = w;
    height = h;
    if(!createBuffers(buffers, w * h)) {
//    printf("Problem creating buffers!\n");
        return false;
    }
    ltr_int_prepare_for_processing(w, h);
#ifdef OPENCV
    facetrack = doFacetrack();
    if(facetrack && (!ltr_int_init_face_detect())) {
        return false;
    }
#endif
//  printf("Starting processing thread!\n");
    return 0 == pthread_create(&processing_thread, NULL, processingThreadFun, NULL);
}
Exemplo n.º 16
0
 bool Timestep_Impl::isNumberOfTimestepsPerHourDefaulted() const {
   return isEmpty(OS_TimestepFields::NumberofTimestepsperHour);
 }
Exemplo n.º 17
0
Map *ReadMap(char *filename)
{
    if(!filename)
    {
        printf("Could not read map; null filename. Talk to a MapMerge dev about it, this is an internal error.\n");
        return NULL;
    }

    FILE *mapFile = fopen(filename, "r");
    if(!mapFile)
    {
        printf("Could not read map; invalid filename.\n");
        Usage();
        return NULL;
    }

    TileList *tileList = newTileList();
    if(!tileList)
    {
        fclose(mapFile);
        return NULL;
    }

    char buffer[65536]; //Arbitrary size, probably excessive, but far better than insufficient. 
    char *line;

    line = fgets(buffer, sizeof(buffer), mapFile);

    while(!isEmpty(line))
    {
        //printf("Adding %s\n", line);
        if(!TileList_AddLine(tileList, line))
        {
            deleteTileList(tileList);
            fclose(mapFile);
            return NULL;
        }

        line = fgets(buffer, sizeof(buffer), mapFile);
    }


    Map *map = newMap();
    if(!map)
    {
        fclose(mapFile);
        return NULL;
    }

    line = fgets(buffer, sizeof(buffer), mapFile);
    int x, y, z;
    char c;
    while(line)
    {
        if(line[0] == '(')
        {
            if(sscanf(line, "(%d,%d,%d) = {%c", &x, &y, &z, &c) != 4 || c != '"')
            {
                printf("Could not read map; could not read coordinates.\n");
                fclose(mapFile);
                return NULL;
            }
            if(x != 1 || y != 1 || z != map->levels + 1)
            {
                printf("Could not read map; unexpected coordinates.\n");
                fclose(mapFile);
                return NULL;
            }
            else
            {
                x = 0;
                y = 0;
                z = map->levels;
                map->levels++;
                map = Map_Resized(map);
                if(!map)
                {
                    fclose(mapFile);
                    return NULL;
                }
            }
        }
        else if(isEmpty(line) || strcmp(line, "\"}\n") == 0 || map->levels == 0)
        {
        }
        else
        {
            int len = strlen(line) - 1;
            int width = len/tileList->charsPerTile;

            if(map->width == 0)
            {
                map->width = width;
                map->height = 0;
            }
            else if(map->width != width)
            {
                printf("Could not read map; width varies.\n");
                fclose(mapFile);
                return NULL;
            }

            if(map->levels == 1)
            {
                map->height++;
                map = Map_Resized(map);
                if(!map)
                {
                    fclose(mapFile);
                    return NULL;
                }
            }
            else if(y >= map->height)
            {
                printf("Could not read map; height varies.\n");
                fclose(mapFile);
                return NULL;
            }

            for(x=0; x < width; x++)
            {
                int i, index = 0;
                for(i = 0; i < tileList->charsPerTile; i++)
                {
                    char c = line[tileList->charsPerTile * x + i];
                    if(c >= 'a' && c <= 'z')
                      index = index * 52 + c - 'a';
                    else if(c >= 'A' && c <= 'Z')
                      index = index * 52 + c - 'A' + 26;
                }

                Map_SetTile(map, TileList_GetTile(tileList, index), x, y, z);
            }

            y++;
        }

        line = fgets(buffer, sizeof(buffer), mapFile);
    }

    deleteTileList(tileList);

    fclose(mapFile);

    return map;
}
Exemplo n.º 18
0
void TxOutLayout::removeWidgets()
{
    while(!isEmpty()) {
        delete itemAt(0)->widget();
    }
}
Exemplo n.º 19
0
 bool CoilHeatingDesuperheater_Impl::isParasiticElectricLoadDefaulted() const {
     return isEmpty(OS_Coil_Heating_DesuperheaterFields::ParasiticElectricLoad);
 }
 bool SolarCollectorIntegralCollectorStorage_Impl::isBottomSurfaceBoundaryConditionsTypeDefaulted() const {
   return isEmpty(OS_SolarCollector_IntegralCollectorStorageFields::BottomSurfaceBoundaryConditionsType);
 }
 bool CoilHeatingLowTempRadiantVarFlow_Impl::isMaximumHotWaterFlowDefaulted() const 
 {
   return isEmpty(OS_Coil_Heating_LowTemperatureRadiant_VariableFlowFields::MaximumHotWaterFlow);
 }
Exemplo n.º 22
0
static int LYLoadCGI(const char *arg,
		     HTParentAnchor *anAnchor,
		     HTFormat format_out,
		     HTStream *sink)
{
    int status = 0;

#ifdef LYNXCGI_LINKS
#ifndef VMS
    char *cp;
    struct stat stat_buf;
    char *pgm = NULL;		/* executable */
    char *pgm_args = NULL;	/* and its argument(s) */
    int statrv;
    char *orig_pgm = NULL;	/* Path up to ? as given, URL-escaped */
    char *document_root = NULL;	/* Corrected value of DOCUMENT_ROOT  */
    char *path_info = NULL;	/* PATH_INFO extracted from pgm      */
    char *pgm_buff = NULL;	/* PATH_INFO extraction buffer       */
    char *path_translated;	/* From document_root/path_info      */

    if (isEmpty(arg) || strlen(arg) <= 8) {
	HTAlert(BAD_REQUEST);
	status = -2;
	return (status);

    } else {
	if (StrNCmp(arg, "lynxcgi://localhost", 19) == 0) {
	    StrAllocCopy(pgm, arg + 19);
	} else {
	    StrAllocCopy(pgm, arg + 8);
	}
	if ((cp = StrChr(pgm, '?')) != NULL) {	/* Need to terminate executable */
	    *cp++ = '\0';
	    pgm_args = cp;
	}
    }

    StrAllocCopy(orig_pgm, pgm);
    if (trimPoundSelector(pgm) != NULL) {
	/*
	 * Strip a #fragment from path.  In this case any pgm_args found above
	 * will also be bogus, since the '?' came after the '#' and is part of
	 * the fragment.  Note that we don't handle the case where a '#'
	 * appears after a '?' properly according to URL rules.  - kw
	 */
	pgm_args = NULL;
    }
    HTUnEscape(pgm);

    /* BEGIN WebSter Mods */
    /* If pgm is not stat-able, see if PATH_INFO data is at the end of pgm */
    if ((statrv = stat(pgm, &stat_buf)) < 0) {
	StrAllocCopy(pgm_buff, pgm);
	while (statrv < 0 || (statrv = stat(pgm_buff, &stat_buf)) < 0) {
	    if ((cp = strrchr(pgm_buff, '/')) != NULL) {
		*cp = '\0';
		statrv = 1;	/* force new stat()  - kw */
	    } else {
		PERROR("strrchr(pgm_buff, '/') returned NULL");
		break;
	    }
	}

	if (statrv < 0) {
	    /* Did not find PATH_INFO data */
	    PERROR("stat() of pgm_buff failed");
	} else {
	    /* Found PATH_INFO data.  Strip it off of pgm and into path_info. */
	    StrAllocCopy(path_info, pgm + strlen(pgm_buff));
	    /* The following is safe since pgm_buff was derived from pgm
	       by stripping stuff off its end and by HTUnEscaping, so we
	       know we have enough memory allocated for pgm.  Note that
	       pgm_args may still point into that memory, so we cannot
	       reallocate pgm here. - kw */
	    strcpy(pgm, pgm_buff);
	    CTRACE((tfp,
		    "LYNXCGI: stat() of %s succeeded, path_info=\"%s\".\n",
		    pgm_buff, path_info));
	}
	FREE(pgm_buff);
    }
    /* END WebSter Mods */

    if (statrv != 0) {
	/*
	 * Neither the path as given nor any components examined by backing up
	 * were stat()able.  - kw
	 */
	HTAlert(gettext("Unable to access cgi script"));
	PERROR("stat() failed");
	status = -4;

    } else
#ifdef _WINDOWS			/* 1998/01/14 (Wed) 09:16:04 */
#define isExecutable(mode) (mode & (S_IXUSR))
#else
#define isExecutable(mode) (mode & (S_IXUSR|S_IXGRP|S_IXOTH))
#endif
    if (!(S_ISREG(stat_buf.st_mode) && isExecutable(stat_buf.st_mode))) {
	/*
	 * Not a runnable file, See if we can load it using "file:" code.
	 */
	char *new_arg = NULL;

	/*
	 * But try "file:" only if the file we are looking at is the path as
	 * given (no path_info was extracted), otherwise it will be to
	 * confusing to know just what file is loaded.  - kw
	 */
	if (path_info) {
	    CTRACE((tfp,
		    "%s is not a file and %s not an executable, giving up.\n",
		    orig_pgm, pgm));
	    FREE(path_info);
	    FREE(pgm);
	    FREE(orig_pgm);
	    status = -4;
	    return (status);
	}

	LYLocalFileToURL(&new_arg, orig_pgm);

	CTRACE((tfp, "%s is not an executable file, passing the buck.\n", arg));
	status = HTLoadFile(new_arg, anAnchor, format_out, sink);
	FREE(new_arg);

    } else if (path_info &&
	       anAnchor != HTMainAnchor &&
	       !(reloading && anAnchor->document) &&
	       strcmp(arg, HTLoadedDocumentURL()) &&
	       HText_AreDifferent(anAnchor, arg) &&
	       HTUnEscape(orig_pgm) &&
	       !can_exec_cgi(orig_pgm, "")) {
	/*
	 * If we have extra path info and are not just reloading the current,
	 * check the full file path (after unescaping) now to catch forbidden
	 * segments.  - kw
	 */
	status = HT_NOT_LOADED;

    } else if (no_lynxcgi) {
	HTUserMsg(CGI_DISABLED);
	status = HT_NOT_LOADED;

    } else if (no_bookmark_exec &&
	       anAnchor != HTMainAnchor &&
	       !(reloading && anAnchor->document) &&
	       strcmp(arg, HTLoadedDocumentURL()) &&
	       HText_AreDifferent(anAnchor, arg) &&
	       HTLoadedDocumentBookmark()) {
	/*
	 * If we are reloading a lynxcgi document that had already been loaded,
	 * the various checks above should allow it even if no_bookmark_exec is
	 * TRUE an we are not now coming from a bookmark page.  - kw
	 */
	HTUserMsg(BOOKMARK_EXEC_DISABLED);
	status = HT_NOT_LOADED;

    } else if (anAnchor != HTMainAnchor &&
	       !(reloading && anAnchor->document) &&
	       strcmp(arg, HTLoadedDocumentURL()) &&
	       HText_AreDifferent(anAnchor, arg) &&
	       !can_exec_cgi(pgm, pgm_args)) {
	/*
	 * If we are reloading a lynxcgi document that had already been loaded,
	 * the various checks above should allow it even if exec_ok() would
	 * reject it because we are not now coming from a document with a URL
	 * allowed by TRUSTED_LYNXCGI rules.  - kw
	 */
	status = HT_NOT_LOADED;

    } else {
	HTFormat format_in;
	HTStream *target = NULL;	/* Unconverted data */
	int fd1[2], fd2[2];
	char buf[MAX_LINE];
	int pid;

#ifdef HAVE_TYPE_UNIONWAIT
	union wait wstatus;

#else
	int wstatus;
#endif

	fd1[0] = -1;
	fd1[1] = -1;
	fd2[0] = -1;
	fd2[1] = -1;

	if (anAnchor->isHEAD || keep_mime_headers) {

	    /* Show output as plain text */
	    format_in = WWW_PLAINTEXT;
	} else {

	    /* Decode full HTTP response */
	    format_in = HTAtom_for("www/mime");
	}

	target = HTStreamStack(format_in,
			       format_out,
			       sink, anAnchor);

	if (!target || target == NULL) {
	    char *tmp = 0;

	    HTSprintf0(&tmp, CANNOT_CONVERT_I_TO_O,
		       HTAtom_name(format_in),
		       HTAtom_name(format_out));
	    HTAlert(tmp);
	    FREE(tmp);
	    status = HT_NOT_LOADED;

	} else if (anAnchor->post_data && pipe(fd1) < 0) {
	    HTAlert(CONNECT_SET_FAILED);
	    PERROR("pipe() failed");
	    status = -3;

	} else if (pipe(fd2) < 0) {
	    HTAlert(CONNECT_SET_FAILED);
	    PERROR("pipe() failed");
	    close(fd1[0]);
	    close(fd1[1]);
	    status = -3;

	} else {
	    static BOOL first_time = TRUE;	/* One time setup flag */

	    if (first_time) {	/* Set up static environment variables */
		first_time = FALSE;	/* Only once */

		add_environment_value("REMOTE_HOST=localhost");
		add_environment_value("REMOTE_ADDR=127.0.0.1");

		HTSprintf0(&user_agent, "HTTP_USER_AGENT=%s/%s libwww/%s",
			   LYNX_NAME, LYNX_VERSION, HTLibraryVersion);
		add_environment_value(user_agent);

		HTSprintf0(&server_software, "SERVER_SOFTWARE=%s/%s",
			   LYNX_NAME, LYNX_VERSION);
		add_environment_value(server_software);
	    }
	    fflush(stdout);
	    fflush(stderr);
	    CTRACE_FLUSH(tfp);

	    if ((pid = fork()) > 0) {	/* The good, */
		ssize_t chars;
		off_t total_chars;

		close(fd2[1]);

		if (anAnchor->post_data) {
		    ssize_t written;
		    int remaining, total_written = 0;

		    close(fd1[0]);

		    /* We have form data to push across the pipe */
		    if (TRACE) {
			CTRACE((tfp,
				"LYNXCGI: Doing post, content-type '%s'\n",
				anAnchor->post_content_type));
			CTRACE((tfp, "LYNXCGI: Writing:\n"));
			trace_bstring(anAnchor->post_data);
			CTRACE((tfp, "----------------------------------\n"));
		    }
		    remaining = BStrLen(anAnchor->post_data);
		    while ((written = write(fd1[1],
					    BStrData(anAnchor->post_data) + total_written,
					    (size_t) remaining)) != 0) {
			if (written < 0) {
#ifdef EINTR
			    if (errno == EINTR)
				continue;
#endif /* EINTR */
#ifdef ERESTARTSYS
			    if (errno == ERESTARTSYS)
				continue;
#endif /* ERESTARTSYS */
			    PERROR("write() of POST data failed");
			    break;
			}
			CTRACE((tfp, "LYNXCGI: Wrote %d bytes of POST data.\n",
				(int) written));
			total_written += (int) written;
			remaining -= (int) written;
			if (remaining == 0)
			    break;
		    }
		    if (remaining != 0) {
			CTRACE((tfp, "LYNXCGI: %d bytes remain unwritten!\n",
				remaining));
		    }
		    close(fd1[1]);
		}

		HTReadProgress(total_chars = 0, (off_t) 0);
		while ((chars = read(fd2[0], buf, sizeof(buf))) != 0) {
		    if (chars < 0) {
#ifdef EINTR
			if (errno == EINTR)
			    continue;
#endif /* EINTR */
#ifdef ERESTARTSYS
			if (errno == ERESTARTSYS)
			    continue;
#endif /* ERESTARTSYS */
			PERROR("read() of CGI output failed");
			break;
		    }
		    total_chars += (int) chars;
		    HTReadProgress(total_chars, (off_t) 0);
		    CTRACE((tfp, "LYNXCGI: Rx: %.*s\n", (int) chars, buf));
		    (*target->isa->put_block) (target, buf, (int) chars);
		}

		if (chars < 0 && total_chars == 0) {
		    status = HT_NOT_LOADED;
		    (*target->isa->_abort) (target, NULL);
		    target = NULL;
		} else if (chars != 0) {
		    status = HT_PARTIAL_CONTENT;
		} else {
		    status = HT_LOADED;
		}

#ifndef HAVE_WAITPID
		while (wait(&wstatus) != pid) ;		/* do nothing */
#else
		while (-1 == waitpid(pid, &wstatus, 0)) {	/* wait for child */
#ifdef EINTR
		    if (errno == EINTR)
			continue;
#endif /* EINTR */
#ifdef ERESTARTSYS
		    if (errno == ERESTARTSYS)
			continue;
#endif /* ERESTARTSYS */
		    break;
		}
#endif /* !HAVE_WAITPID */
		close(fd2[0]);

	    } else if (pid == 0) {	/* The Bad, */
		char **argv = NULL;
		int argv_cnt = 3;	/* name, one arg and terminator */
		char **cur_argv = NULL;
		int exec_errno;

		/* Set up output pipe */
		close(fd2[0]);
		dup2(fd2[1], fileno(stdout));	/* Should check success code */
		dup2(fd2[1], fileno(stderr));
		close(fd2[1]);

		if (non_empty(language)) {
		    HTSprintf0(&accept_language, "HTTP_ACCEPT_LANGUAGE=%s", language);
		    add_environment_value(accept_language);
		}

		if (non_empty(pref_charset)) {
		    cp = NULL;
		    StrAllocCopy(cp, "HTTP_ACCEPT_CHARSET=");
		    StrAllocCat(cp, pref_charset);
		    add_environment_value(cp);
		}

		if (anAnchor->post_data &&
		    anAnchor->post_content_type) {
		    cp = NULL;
		    StrAllocCopy(cp, "CONTENT_TYPE=");
		    StrAllocCat(cp, anAnchor->post_content_type);
		    add_environment_value(cp);
		}

		if (anAnchor->post_data) {	/* post script, read stdin */
		    close(fd1[1]);
		    dup2(fd1[0], fileno(stdin));
		    close(fd1[0]);

		    /* Build environment variables */

		    add_environment_value("REQUEST_METHOD=POST");

		    HTSprintf0(&post_len, "CONTENT_LENGTH=%d",
			       BStrLen(anAnchor->post_data));
		    add_environment_value(post_len);
		} else {
		    close(fileno(stdin));

		    if (anAnchor->isHEAD) {
			add_environment_value("REQUEST_METHOD=HEAD");
		    }
		}

		/*
		 * Set up argument line, mainly for <index> scripts
		 */
		if (pgm_args != NULL) {
		    for (cp = pgm_args; *cp != '\0'; cp++) {
			if (*cp == '+') {
			    argv_cnt++;
			}
		    }
		}

		argv = (char **) malloc((unsigned) argv_cnt * sizeof(char *));

		if (argv == NULL) {
		    outofmem(__FILE__, "LYCgi");
		}
		assert(argv != NULL);

		cur_argv = argv + 1;	/* For argv[0] */
		if (pgm_args != NULL) {
		    char *cr;

		    /* Data for a get/search form */
		    if (is_www_index) {
			add_environment_value("REQUEST_METHOD=SEARCH");
		    } else if (!anAnchor->isHEAD && !anAnchor->post_data) {
			add_environment_value("REQUEST_METHOD=GET");
		    }

		    cp = NULL;
		    StrAllocCopy(cp, "QUERY_STRING=");
		    StrAllocCat(cp, pgm_args);
		    add_environment_value(cp);

		    /*
		     * Split up arguments into argv array
		     */
		    cp = pgm_args;
		    cr = cp;
		    while (1) {
			if (*cp == '\0') {
			    *(cur_argv++) = HTUnEscape(cr);
			    break;

			} else if (*cp == '+') {
			    *cp++ = '\0';
			    *(cur_argv++) = HTUnEscape(cr);
			    cr = cp;
			}
			cp++;
		    }
		} else if (!anAnchor->isHEAD && !anAnchor->post_data) {
		    add_environment_value("REQUEST_METHOD=GET");
		}
		*cur_argv = NULL;	/* Terminate argv */
		argv[0] = pgm;

		/* Begin WebSter Mods  -jkt */
		if (LYCgiDocumentRoot != NULL) {
		    /* Add DOCUMENT_ROOT to env */
		    cp = NULL;
		    StrAllocCopy(cp, "DOCUMENT_ROOT=");
		    StrAllocCat(cp, LYCgiDocumentRoot);
		    add_environment_value(cp);
		}
		if (path_info != NULL) {
		    /* Add PATH_INFO to env */
		    cp = NULL;
		    StrAllocCopy(cp, "PATH_INFO=");
		    StrAllocCat(cp, path_info);
		    add_environment_value(cp);
		}
		if (LYCgiDocumentRoot != NULL && path_info != NULL) {
		    /* Construct and add PATH_TRANSLATED to env */
		    StrAllocCopy(document_root, LYCgiDocumentRoot);
		    LYTrimHtmlSep(document_root);
		    path_translated = document_root;
		    StrAllocCat(path_translated, path_info);
		    cp = NULL;
		    StrAllocCopy(cp, "PATH_TRANSLATED=");
		    StrAllocCat(cp, path_translated);
		    add_environment_value(cp);
		    FREE(path_translated);
		}
		/* End WebSter Mods  -jkt */

		execve(argv[0], argv, env);
		exec_errno = errno;
		PERROR("execve failed");
		printf("Content-Type: text/plain\r\n\r\n");
		if (!anAnchor->isHEAD) {
		    printf("exec of %s failed", pgm);
		    printf(": %s.\r\n", LYStrerror(exec_errno));
		}
		fflush(stdout);
		fflush(stderr);
		_exit(1);

	    } else {		/* and the Ugly */
		HTAlert(CONNECT_FAILED);
		PERROR("fork() failed");
		close(fd1[0]);
		close(fd1[1]);
		close(fd2[0]);
		close(fd2[1]);
		status = -1;
	    }

	}
	if (target != NULL) {
	    (*target->isa->_free) (target);
	}
    }
    FREE(path_info);
    FREE(pgm);
    FREE(orig_pgm);
#else /* VMS */
    HTStream *target;
    char *buf = 0;

    target = HTStreamStack(WWW_HTML,
			   format_out,
			   sink, anAnchor);

    HTSprintf0(&buf, "<html>\n<head>\n<title>%s</title>\n</head>\n<body>\n",
	       gettext("Good Advice"));
    PUTS(buf);

    HTSprintf0(&buf, "<h1>%s</h1>\n", gettext("Good Advice"));
    PUTS(buf);

    HTSprintf0(&buf, "%s <a\n",
	       gettext("An excellent http server for VMS is available via"));
    PUTS(buf);

    HTSprintf0(&buf,
	       "href=\"http://www.ecr6.ohio-state.edu/www/doc/serverinfo.html\"\n");
    PUTS(buf);

    HTSprintf0(&buf, ">%s</a>.\n", gettext("this link"));
    PUTS(buf);

    HTSprintf0(&buf, "<p>%s\n",
	       gettext("It provides state of the art CGI script support.\n"));
    PUTS(buf);

    HTSprintf0(&buf, "</body>\n</html>\n");
    PUTS(buf);

    (*target->isa->_free) (target);
    FREE(buf);
    status = HT_LOADED;
#endif /* VMS */
#else /* LYNXCGI_LINKS */
    HTUserMsg(CGI_NOT_COMPILED);
    status = HT_NOT_LOADED;
#endif /* LYNXCGI_LINKS */

    (void) arg;
    (void) anAnchor;
    (void) format_out;
    (void) sink;

    return (status);
}
Exemplo n.º 23
0
bool MP3Metadata::WriteMetadata(CFErrorRef *error)
{
	UInt8 buf [PATH_MAX];
	if(!CFURLGetFileSystemRepresentation(mURL, false, buf, PATH_MAX))
		return false;

	// TODO: Use unique_ptr once the switch to C++11 STL is made
	std::auto_ptr<TagLib::FileStream> stream(new TagLib::FileStream(reinterpret_cast<const char *>(buf)));
	if(!stream->isOpen()) {
		if(error) {
			CFStringRef description = CFCopyLocalizedString(CFSTR("The file “%@” could not be opened for writing."), "");
			CFStringRef failureReason = CFCopyLocalizedString(CFSTR("Input/output error"), "");
			CFStringRef recoverySuggestion = CFCopyLocalizedString(CFSTR("The file may have been renamed, moved, deleted, or you may not have appropriate permissions."), "");

			*error = CreateErrorForURL(AudioMetadataErrorDomain, AudioMetadataInputOutputError, description, mURL, failureReason, recoverySuggestion);

			CFRelease(description), description = nullptr;
			CFRelease(failureReason), failureReason = nullptr;
			CFRelease(recoverySuggestion), recoverySuggestion = nullptr;
		}

		return false;
	}

	TagLib::MPEG::File file(stream.get(), TagLib::ID3v2::FrameFactory::instance(), false);
	if(!file.isValid()) {
		if(error) {
			CFStringRef description = CFCopyLocalizedString(CFSTR("The file “%@” is not a valid MPEG file."), "");
			CFStringRef failureReason = CFCopyLocalizedString(CFSTR("Not an MPEG file"), "");
			CFStringRef recoverySuggestion = CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), "");
			
			*error = CreateErrorForURL(AudioMetadataErrorDomain, AudioMetadataInputOutputError, description, mURL, failureReason, recoverySuggestion);
			
			CFRelease(description), description = nullptr;
			CFRelease(failureReason), failureReason = nullptr;
			CFRelease(recoverySuggestion), recoverySuggestion = nullptr;
		}
		
		return false;
	}

	// APE and ID3v1 tags are only written if present, but ID3v2 tags are always written

	auto APETag = file.APETag();
	if(APETag && !APETag->isEmpty())
		SetAPETagFromMetadata(*this, APETag);

	auto ID3v1Tag = file.ID3v1Tag();
	if(ID3v1Tag && !ID3v1Tag->isEmpty())
		SetID3v1TagFromMetadata(*this, ID3v1Tag);

	SetID3v2TagFromMetadata(*this, file.ID3v2Tag(true));

	if(!file.save()) {
		if(error) {
			CFStringRef description = CFCopyLocalizedString(CFSTR("The file “%@” is not a valid MPEG file."), "");
			CFStringRef failureReason = CFCopyLocalizedString(CFSTR("Unable to write metadata"), "");
			CFStringRef recoverySuggestion = CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), "");
			
			*error = CreateErrorForURL(AudioMetadataErrorDomain, AudioMetadataInputOutputError, description, mURL, failureReason, recoverySuggestion);
			
			CFRelease(description), description = nullptr;
			CFRelease(failureReason), failureReason = nullptr;
			CFRelease(recoverySuggestion), recoverySuggestion = nullptr;
		}
		
		return false;
	}
	
	MergeChangedMetadataIntoMetadata();
	
	return true;
}
Exemplo n.º 24
0
int decrypt_pgd(unsigned char* pgd_data, int pgd_size, int flag, unsigned char* key)
{
	int result;
	PGD_HEADER *PGD;
	MAC_KEY mkey;
	CIPHER_KEY ckey;
	unsigned char*fkey;

	// Read in the PGD header parameters.
	PGD = (PGD_HEADER*)malloc(sizeof(PGD_HEADER));
	memset(PGD, 0, sizeof(PGD_HEADER));

	PGD->buf = pgd_data;
	PGD->key_index = *(u32*)(pgd_data + 4);
	PGD->drm_type  = *(u32*)(pgd_data + 8);

	// Set the hashing, crypto and open modes.
	if (PGD->drm_type == 1)
	{
		PGD->mac_type = 1;
		flag |= 4;

		if(PGD->key_index > 1)
		{
			PGD->mac_type = 3;
			flag |= 8;
		}
		PGD->cipher_type = 1;
	}
	else
	{
		PGD->mac_type = 2;
		PGD->cipher_type = 2;
	}
	PGD->open_flag = flag;

	// Get the fixed DNAS key.
	fkey = NULL;
	if((flag & 0x2) == 0x2)
		fkey = dnas_key1A90;
	if((flag & 0x1) == 0x1)
		fkey = dnas_key1AA0;

	if (fkey == NULL)
	{
		printf("PGD: Invalid DNAS flag! %08x\n", flag);
		return -1;
	}

	// Test MAC hash at 0x80 (DNAS hash).
	sceDrmBBMacInit(&mkey, PGD->mac_type);
	sceDrmBBMacUpdate(&mkey, pgd_data, 0x80);
	result = sceDrmBBMacFinal2(&mkey, pgd_data + 0x80, fkey);

	if (result)
	{
		printf("PGD: Invalid 0x80 MAC hash!\n");
		return -1;
	}

	// Test MAC hash at 0x70 (key hash).
	sceDrmBBMacInit(&mkey, PGD->mac_type);
	sceDrmBBMacUpdate(&mkey, pgd_data, 0x70);

	// If a key was provided, check it against MAC 0x70.
	if (!isEmpty(key, 0x10))
	{
		result = sceDrmBBMacFinal2(&mkey, pgd_data + 0x70, key);
		if (result)
		{
			printf("PGD: Invalid 0x70 MAC hash!\n");
			return -1;
		}
		else
		{
			memcpy(PGD->vkey, key, 16);
		}
	}
	else
	{
		// Generate the key from MAC 0x70.
		bbmac_getkey(&mkey, pgd_data + 0x70, PGD->vkey);
	}

	// Decrypt the PGD header block (0x30 bytes).
	sceDrmBBCipherInit(&ckey, PGD->cipher_type, 2, pgd_data + 0x10, PGD->vkey, 0);
	sceDrmBBCipherUpdate(&ckey, pgd_data + 0x30, 0x30);
	sceDrmBBCipherFinal(&ckey);

	// Get the decryption parameters from the decrypted header.
	PGD->data_size   = *(u32*)(pgd_data + 0x44);
	PGD->block_size  = *(u32*)(pgd_data + 0x48);
	PGD->data_offset = *(u32*)(pgd_data + 0x4c);

	// Additional size variables.
	PGD->align_size = (PGD->data_size + 15) &~ 15;
	PGD->table_offset = PGD->data_offset + PGD->align_size;
	PGD->block_nr = (PGD->align_size + PGD->block_size - 1) &~ (PGD->block_size - 1);
	PGD->block_nr = PGD->block_nr / PGD->block_size;

	if ((PGD->align_size + PGD->block_nr * 16) > pgd_size)
	{
		printf("PGD: Invalid data size!\n");
		return -1;
	}

	// Test MAC hash at 0x60 (table hash).
	sceDrmBBMacInit(&mkey, PGD->mac_type);
	sceDrmBBMacUpdate(&mkey, pgd_data + PGD->table_offset, PGD->block_nr * 16);
	result = sceDrmBBMacFinal2(&mkey, pgd_data + 0x60, PGD->vkey);

	if(result)
	{
		printf("PGD: Invalid 0x60 MAC hash!\n");
		return -1;
	}

	// Decrypt the data.
	sceDrmBBCipherInit(&ckey, PGD->cipher_type, 2, pgd_data + 0x30, PGD->vkey, 0);
	sceDrmBBCipherUpdate(&ckey, pgd_data + 0x90, PGD->align_size);
	sceDrmBBCipherFinal(&ckey);

	return PGD->data_size;
}
/*
    Activate pending timers, returning how many where activated.
*/
int QTimerInfoList::activateTimers()
{
    if (qt_disable_lowpriority_timers || isEmpty())
        return 0; // nothing to do

    bool firstTime = true;
    timeval currentTime;
    int n_act = 0, maxCount = count();

    QTimerInfo *saveFirstTimerInfo = firstTimerInfo;
    QTimerInfo *saveCurrentTimerInfo = currentTimerInfo;
    firstTimerInfo = currentTimerInfo = 0;

    while (maxCount--) {
        currentTime = updateCurrentTime();
        if (firstTime) {
            repairTimersIfNeeded();
            firstTime = false;
        }

        if (isEmpty())
            break;

        currentTimerInfo = first();
        if (currentTime < currentTimerInfo->timeout)
            break; // no timer has expired

        if (!firstTimerInfo) {
            firstTimerInfo = currentTimerInfo;
        } else if (firstTimerInfo == currentTimerInfo) {
            // avoid sending the same timer multiple times
            break;
        } else if (currentTimerInfo->interval <  firstTimerInfo->interval
                   || currentTimerInfo->interval == firstTimerInfo->interval) {
            firstTimerInfo = currentTimerInfo;
        }

        // remove from list
        removeFirst();

        // determine next timeout time
        currentTimerInfo->timeout += currentTimerInfo->interval;
        if (currentTimerInfo->timeout < currentTime)
            currentTimerInfo->timeout = currentTime + currentTimerInfo->interval;

        // reinsert timer
        timerInsert(currentTimerInfo);
        if (currentTimerInfo->interval.tv_usec > 0 || currentTimerInfo->interval.tv_sec > 0)
            n_act++;

        if (!currentTimerInfo->inTimerEvent) {
            // send event, but don't allow it to recurse
            currentTimerInfo->inTimerEvent = true;

            QTimerEvent e(currentTimerInfo->id);
            QCoreApplication::sendEvent(currentTimerInfo->obj, &e);

            if (currentTimerInfo)
                currentTimerInfo->inTimerEvent = false;
        }
    }

    firstTimerInfo = saveFirstTimerInfo;
    currentTimerInfo = saveCurrentTimerInfo;

    return n_act;
}
Exemplo n.º 26
0
 bool LightsDefinition_Impl::isReturnAirFractionCalculatedfromPlenumTemperatureDefaulted() const {
   return isEmpty(OS_Lights_DefinitionFields::ReturnAirFractionCalculatedfromPlenumTemperature);
 }
Exemplo n.º 27
0
// Function to get top item from stack
char peek(struct Stack* stack)
{
    if (isEmpty(stack))
        return CHAR_MIN;
    return stack->array[stack->top];
}
Exemplo n.º 28
0
 bool LightsDefinition_Impl::isReturnAirFractionFunctionofPlenumTemperatureCoefficient2Defaulted() const {
   return isEmpty(OS_Lights_DefinitionFields::ReturnAirFractionFunctionofPlenumTemperatureCoefficient2);
 }
Exemplo n.º 29
0
Arquivo: list.cpp Projeto: jakwuh/bsu
void List::pop_front() {
	if (isEmpty()) throw Empty();
	Node *tmp = head->next;
	delete head;
	head = tmp;
}
Exemplo n.º 30
0
 bool WaterUseEquipmentDefinition_Impl::isEndUseSubcategoryDefaulted() const {
   return isEmpty(OS_WaterUse_Equipment_DefinitionFields::EndUseSubcategory);
 }