示例#1
0
static status
initialiseWinPrinter(WinPrinter prt, Name jobname)
{   if ( isDefault(jobname) )
        jobname = CtoName("XPCE");

    assign(prt, map_mode,   DEFAULT);
    assign(prt, device,     DEFAULT);
    assign(prt, job_name,   jobname);
    assign(prt, job,        NIL);
    assign(prt, resolution, DEFAULT);
    assign(prt, origin,	  newObject(ClassPoint, EAV));

    prt->ws_ref = alloc(sizeof(ws_printer));
    memset(prt->ws_ref, 0, sizeof(ws_printer));

    return prependChain(WinPrinters, prt);
}
示例#2
0
static status
deleteChainTable(ChainTable ct, Any name, Any value)
{ Chain ch;

  if ( isDefault(value) )
    return deleteHashTable((HashTable)ct, name);

  if ( (ch = getMemberHashTable((HashTable) ct, name)) )
  { TRY(deleteChain(ch, value));
    if ( emptyChain(ch) )
      deleteHashTable((HashTable) ct, name);

    succeed;
  }

  fail;
}
示例#3
0
void SDL::Variable::write(DS::Stream* stream) const
{
    uint8_t contents = 0;
    if (!m_data->m_notificationHint.is_empty())
        contents |= e_HasNotificationInfo;
    stream->write<uint8_t>(contents);
    if (contents & e_HasNotificationInfo) {
        stream->write<uint8_t>(0);
        stream->writeSafeString(m_data->m_notificationHint);
    }

    if (isDefault())
        m_data->m_flags |= e_SameAsDefault;
    stream->write<uint8_t>(m_data->m_flags & 0xFF);
    if (m_data->m_desc->m_type == e_VarStateDesc) {
        if (m_data->m_desc->m_size == -1)
            stream->write<uint32_t>(m_data->m_size);

        DS::BitVector dirty;
        size_t count = 0;
        for (size_t i=0; i<m_data->m_size; ++i) {
            dirty.set(i, m_data->m_child[i].isDirty());
            ++count;
        }
        size_t stupid = m_data->m_desc->m_size == -1 ? 0 : m_data->m_size;
        stupidLengthWrite(stream, stupid, count);
        bool useIndices = (count != m_data->m_size);
        for (size_t i=0; i<m_data->m_size; ++i) {
            if (dirty.get(i)) {
                if (useIndices)
                    stupidLengthWrite(stream, stupid, i);
                m_data->m_child[i].write(stream);
            }
        }
    } else {
        if (m_data->m_flags & e_HasTimeStamp)
            m_data->m_timestamp.write(stream);

        if (!(m_data->m_flags & e_SameAsDefault)) {
            if (m_data->m_desc->m_size == -1)
                stream->write<uint32_t>(m_data->m_size);
            m_data->write(stream);
        }
    }
}
示例#4
0
void
ws_open_display(DisplayObj d)
{ d->ws_ref = (WsRef) 1;	/* just flag; nothing to do yet */

  if ( isDefault(d->colour_map) )
  { if ( ws_has_colourmap(d) )
    { int depth = ws_depth_display(d);

      if ( depth == 8 )
      { send(d, NAME_colourMap,
	     newObject(ClassColourMap, CtoName("colour_cube_216"), EAV), EAV);
      }
    } else
      send(d, NAME_colourMap, NIL, EAV);
  }

  ws_init_loc_still_timer();
}
/**
 * Get the property held by this object. If the value is the default see if it
 * contained in the PropertyManager. @see Algorithm::getProperty(const string&)
 *
 * @param name
 * @return
 */
PropertyManagerOwner::TypedValue DataProcessorAlgorithm::getProperty(const std::string &name) const {
  // explicitely specifying a property wins
  if (!isDefault(name)) {
    return Algorithm::getProperty(name);
  }

  // return it if it is in the held property manager
  auto mapping = m_nameToPMName.find(name);
  if (mapping != m_nameToPMName.end()) {
    auto pm = this->getProcessProperties();
    if (pm->existsProperty(mapping->second)) {
      return pm->getProperty(mapping->second);
    }
  }

  // let the parent class version win
  return Algorithm::getProperty(name);
}
示例#6
0
QString Temperature::str()
{
    if ( _mode == Celcius )
    {
        if ( isDefault() )
        {
            return "-";
        }
        else
        {
            return QString::number(_value)+"°C";
        }
    }
    else
    {
        return "";
    }
}
示例#7
0
void UiController::parameterValueChanged(int moduleId, QString parameterName)
{
#if 0
   QString text = "Parameter value changed on ID: " + QString::number(moduleId) + ":" + parameterName;
   m_console->appendDebug(text);
#endif
   if (parameterName == "_position") {
      if (Module *m = m_scene->findModule(moduleId)) {
         auto p = vistle::VistleConnection::the().getParameter(moduleId, "_position");
         auto vp = std::dynamic_pointer_cast<vistle::VectorParameter>(p);
         if (vp && !vp->isDefault()) {
            vistle::ParamVector pos = vp->getValue();
            m->setPos(pos[0], pos[1]);
            m->setPositionValid();
         }
      }
   }
}
示例#8
0
void UiController::newParameter(int moduleId, QString parameterName)
{
#if 0
    QString text = "New parameter on ID: " + QString::number(moduleId) + ":" + parameterName;
    m_console->appendDebug(text);
#endif
#if 1
    if (parameterName == "_position") {
       if (Module *m = m_scene->findModule(moduleId)) {
          auto p = vistle::VistleConnection::the().getParameter(moduleId, "_position");
          auto vp = std::dynamic_pointer_cast<vistle::VectorParameter>(p);
          if (vp && vp->isDefault() && m->isPositionValid()) {
             m->sendPosition();
          }
       }
    }
#endif
}
int QPushButton::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QAbstractButton::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        if (_id < 2)
            qt_static_metacall(this, _c, _id, _a);
        _id -= 2;
    }
#ifndef QT_NO_PROPERTIES
      else if (_c == QMetaObject::ReadProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0: *reinterpret_cast< bool*>(_v) = autoDefault(); break;
        case 1: *reinterpret_cast< bool*>(_v) = isDefault(); break;
        case 2: *reinterpret_cast< bool*>(_v) = isFlat(); break;
        }
        _id -= 3;
    } else if (_c == QMetaObject::WriteProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0: setAutoDefault(*reinterpret_cast< bool*>(_v)); break;
        case 1: setDefault(*reinterpret_cast< bool*>(_v)); break;
        case 2: setFlat(*reinterpret_cast< bool*>(_v)); break;
        }
        _id -= 3;
    } else if (_c == QMetaObject::ResetProperty) {
        _id -= 3;
    } else if (_c == QMetaObject::QueryPropertyDesignable) {
        _id -= 3;
    } else if (_c == QMetaObject::QueryPropertyScriptable) {
        _id -= 3;
    } else if (_c == QMetaObject::QueryPropertyStored) {
        _id -= 3;
    } else if (_c == QMetaObject::QueryPropertyEditable) {
        _id -= 3;
    } else if (_c == QMetaObject::QueryPropertyUser) {
        _id -= 3;
    }
#endif // QT_NO_PROPERTIES
    return _id;
}
示例#10
0
bool LaunchPoint::toFile() const
{
	// NOTE: we only support persisting dynamic launchpoints at this point
	if (!isRemovable() || isDefault())
		return false;

	// dynamic launch points have appinfo files named by their launchpointid's
	std::string	filePath = Settings::LunaSettings()->lunaLaunchPointsPath;
	if (filePath[filePath.size()-1] != '/')
		filePath += "/";
	filePath += launchPointId();

	// persist a launch points appinfo
	json_object* json = toJSON();
	int res = json_object_to_file((char*)filePath.c_str(), json);
	if (json && !is_error(json))
		json_object_put(json);
	return res != -1;
}
示例#11
0
文件: IKeyState.cpp 项目: 335/synergy
void
IKeyState::KeyInfo::split(const char* screens, std::set<String>& dst)
{
	dst.clear();
	if (isDefault(screens)) {
		return;
	}
	if (screens[0] == '*') {
		dst.insert("*");
		return;
	}

	const char* i = screens + 1;
	while (*i != '\0') {
		const char* j = strchr(i, ':');
		dst.insert(String(i, j - i));
		i = j + 1;
	}
}
示例#12
0
文件: IKeyState.cpp 项目: 335/synergy
bool
IKeyState::KeyInfo::contains(const char* screens, const String& name)
{
	// special cases
	if (isDefault(screens)) {
		return false;
	}
	if (screens[0] == '*') {
		return true;
	}

	// search
	String match;
	match.reserve(name.size() + 2);
	match += ":";
	match += name;
	match += ":";
	return (strstr(screens, match.c_str()) != NULL);
}
示例#13
0
static status
initialiseSpatial(Spatial s,
		  Equation xFrom, Equation yFrom,
		  Equation xTo, Equation yTo,
		  Equation wTo, Equation hTo)
{ assign(s, xFrom, isDefault(xFrom) ? (Equation) NIL : xFrom);
  assign(s, yFrom, isDefault(yFrom) ? (Equation) NIL : yFrom);
  assign(s, xTo, isDefault(xTo) ? (Equation) NIL : xTo);
  assign(s, yTo, isDefault(yTo) ? (Equation) NIL : yTo);
  assign(s, wTo, isDefault(wTo) ? (Equation) NIL : wTo);
  assign(s, hTo, isDefault(hTo) ? (Equation) NIL : hTo);

  succeed;
}
示例#14
0
void InfoControl::videoStreamChanged(){
	bool exist = false;
	int row = videoStream.getActiveItem(exist);
	if(exist){
		auto stream = actualMediaFile->getMediaInfo().getVideoStreams()[row];
		videoCodec << getAsString(stream, "", MediaFile::VideoStream::CODEC);
		colorSpace << getAsString(stream, "", MediaFile::VideoStream::COLORSPACE);
		resolution << (getAsString(stream, "", MediaFile::VideoStream::RESX) + "x" +
				getAsString(stream, "", MediaFile::VideoStream::RESY));
		fps << getAsString(stream, "", MediaFile::VideoStream::FPS);
		tbr << getAsString(stream, "", MediaFile::VideoStream::TBR);
		tbn << getAsString(stream, "", MediaFile::VideoStream::TBN);
		tbc << getAsString(stream, "", MediaFile::VideoStream::TBC);
		if(stream.isDefault()){
			extra << DEFAULT_STREAM;
		}else{
			extra << std::string();
		}
	}
}
/** Compute the detector rotation angle around origin and optionally set the
 *  OutputBeamPosition property.
 *  @return a rotation angle
 */
double LoadILLReflectometry::detectorRotation() {
  ITableWorkspace_const_sptr posTable = getProperty("DirectBeamPosition");
  const double peakCentre = reflectometryPeak();
  g_log.debug() << "Using detector angle (degrees): " << m_detectorAngle
                << '\n';
  const double deflection = collimationAngle();
  if (!isDefault("OutputBeamPosition")) {
    PeakInfo p;
    p.detectorAngle = m_detectorAngle;
    p.detectorDistance = m_detectorDistance;
    p.peakCentre = peakCentre;
    setProperty("OutputBeamPosition", createPeakPositionTable(p));
  }
  const double userAngle = getProperty("BraggAngle");
  const double offset =
      offsetAngle(peakCentre, PIXEL_CENTER, m_detectorDistance);
  m_log.debug() << "Beam offset angle: " << offset << '\n';
  if (userAngle != EMPTY_DBL()) {
    if (posTable) {
      g_log.notice()
          << "Ignoring DirectBeamPosition, using BraggAngle instead.";
    }
    return 2 * userAngle - offset;
  }
  if (!posTable) {
    if (deflection != 0) {
      g_log.debug() << "Using incident deflection angle (degrees): "
                    << deflection << '\n';
    }
    return m_detectorAngle + deflection;
  }
  const auto dbPeak = parseBeamPositionTable(*posTable);
  const double dbOffset =
      offsetAngle(dbPeak.peakCentre, PIXEL_CENTER, dbPeak.detectorDistance);
  m_log.debug() << "Direct beam offset angle: " << dbOffset << '\n';
  const double detectorAngle =
      m_detectorAngle - dbPeak.detectorAngle - dbOffset;
  m_log.debug() << "Direct beam calibrated detector angle: " << detectorAngle
                << '\n';
  return detectorAngle;
}
示例#16
0
int
GvField::io(AStream &a, const GvName &name)
{
    char c;

	if (a.IsInput()) {
    	setDefault(FALSE);
		c = a.Skip();
    	if (c == IGNORE_CHAR) {
			c = a.getc();
			setDefault(TRUE);
			setIgnored(TRUE);
    	} else {
	
		setIgnored(FALSE);


		if (!ioValue(a)) {
	    	a.Error("Couldn't read value for field \"%s\"", name.getString());
	    	return FALSE;
		}

		c = a.Skip();
	    if (c == IGNORE_CHAR) {
			c = a.getc();
			setIgnored(TRUE);
		}
      }
	}
	else { // write
	  if (isDefault()) {
		 a.putc(IGNORE_CHAR);
	  }	else {
	  		ioValue(a);
			if (isIgnored()) 
		 	   a.putc(IGNORE_CHAR);

	  }
	}
    return TRUE;
}
示例#17
0
Any
ws_event_in_subwindow(EventObj ev, Any root)
{ DisplayObj d = getDisplayEvent(ev);
  DisplayWsXref r = d->ws_ref;
  Window src_w = XtWindow(widgetWindow(ev->window));
  int dx, dy;
  Window child;
  int root_is_display;

  if ( isDefault(root) )
    root = d;

  if ( (root_is_display = instanceOfObject(root, ClassDisplay)) )
  { XWindowAttributes atts;
    int depth = MAX_DECORATION_NESTING;

    if ( d != root )
    { errorPce(ev, NAME_notSameDisplay, root);
      fail;
    }

    XGetWindowAttributes(r->display_xref, XtWindow(r->shell_xref), &atts);
    XTranslateCoordinates(r->display_xref, src_w, atts.root,
			  valInt(ev->x), valInt(ev->y),
			  &dx, &dy, &child);

#if 0
    DEBUG(NAME_pointer,
					/* TEST STUFF */
	  ({ Window rr, cr;
	    int rx, ry, wx, wy, mask;

	    if ( XQueryPointer(r->display_xref, atts.root, &rr, &cr,
			       &rx, &ry, &wx, &wy, &mask) )
	    { Cprintf("XTranslateCoordinates --> %d\nXQueryPointer --> %d\n",
		      child, cr);
	    }
	  }));
ControlStates RenderTheme::controlStatesForRenderer(const RenderObject* o) const
{
    ControlStates result = 0;
    if (isHovered(o))
        result |= HoverState;
    if (isPressed(o))
        result |= PressedState;
    if (isFocused(o) && o->style()->outlineStyleIsAuto())
        result |= FocusState;
    if (isEnabled(o))
        result |= EnabledState;
    if (isChecked(o))
        result |= CheckedState;
    if (isReadOnlyControl(o))
        result |= ReadOnlyState;
    if (isDefault(o))
        result |= DefaultState;
    if (!isActive(o))
        result |= WindowInactiveState;
    if (isIndeterminate(o))
        result |= IndeterminateState;
    return result;
}
示例#19
0
void JoyControlStick::writeConfig(QXmlStreamWriter *xml)
{
    if (!isDefault())
    {
        xml->writeStartElement("stick");
        xml->writeAttribute("index", QString::number(index+1));
        xml->writeTextElement("deadZone", QString::number(deadZone));
        xml->writeTextElement("maxZone", QString::number(maxZone));
        xml->writeTextElement("diagonalRange", QString::number(diagonalRange));
        if (currentMode == EightWayMode)
        {
            xml->writeTextElement("mode", "eight-way");
        }

        QHashIterator<JoyStickDirections, JoyControlStickButton*> iter(buttons);
        while (iter.hasNext())
        {
            JoyControlStickButton *button = iter.next().value();
            button->writeConfig(xml);
        }

        xml->writeEndElement();
    }
}
示例#20
0
status
initialiseStringv(StringObj str, CharArray fmt, int argc, Any *argv)
{ if ( isDefault(fmt) )
  { str_inithdr(&str->data, FALSE);
    str->data.s_size = 0;
    str_alloc(&str->data);
  } else if ( (Name) fmt == name_procent_s &&
	      argc == 1 && instanceOfObject(argv[0], ClassCharArray) )
  { CharArray v = argv[0];

    str_cphdr(&str->data, &v->data);
    if ( v->data.s_readonly )
    { str->data.s_textA = v->data.s_textA;

      DEBUG(NAME_readOnly, Cprintf("Shared %s\n", pp(str)));
    } else
    { str_alloc(&str->data);
      memcpy(str->data.s_textA, v->data.s_textA, str_datasize(&v->data));
    }
  } else
    TRY(str_writefv(&str->data, fmt, argc, argv));

  succeed;
}
示例#21
0
LLURI::LLURI(const std::string& scheme,
			 const std::string& userName,
			 const std::string& password,
			 const std::string& hostName,
			 U16 port,
			 const std::string& escapedPath,
			 const std::string& escapedQuery)
	: mScheme(scheme),
	  mEscapedPath(escapedPath),
	  mEscapedQuery(escapedQuery)
{
	std::ostringstream auth;
	std::ostringstream opaque;

	opaque << "//";
	
	if (!userName.empty())
	{
		auth << escape(userName);
		if (!password.empty())
		{
			auth << ':' << escape(password);
		}
		auth << '@';
	}
	auth << hostName;
	if (!isDefault(scheme, port))
	{
		auth << ':' << port;
	}
	mEscapedAuthority = auth.str();

	opaque << mEscapedAuthority << escapedPath << escapedQuery;

	mEscapedOpaque = opaque.str();
}
示例#22
0
bool LLControlVariable::shouldSave(bool nondefault_only)
{
	// This method is used to decide whether we should save a given
	// variable. Two of the three values of mPersist are easy.
	if (mPersist == PERSIST_NO)
		return false;

	if (mPersist == PERSIST_ALWAYS)
		return true;

	// PERSIST_NONDFT
	// If caller doesn't need us to filter, just save.
	if (! nondefault_only)
		return true;

	// PERSIST_NONDFT: caller only wants us to save this variable if its value
	// differs from default.
	if (isDefault())                // never been altered
		return false;

	// We've set at least one other value: compare it to default. Save only if
	// they differ.
	return ! llsd_compare(getSaveValue(), getDefault());
}
示例#23
0
文件: event.c 项目: brayc0/nlfetdb
static status
initialiseEvent(EventObj e, Name id, Any window,
		Int x, Int y, Int bts, Int time)
{ unsigned long t = valInt(time);

  initialiseProgramObject(e);

  if ( notNil(EVENT->value) )
  { EventObj parent = EVENT->value;

    if ( isDefault(x) )      x      = parent->x;
    if ( isDefault(y) )      y      = parent->y;
    if ( isDefault(bts) )    bts    = parent->buttons;
    if ( isDefault(window) ) window = parent->window;
    if ( isDefault(time) )   t      = max(last_time, parent->time);
  } else
  { if ( isDefault(x) )      x      = last_x;
    if ( isDefault(y) )      y      = last_y;
    if ( isDefault(bts) )    bts    = last_buttons;
    if ( isDefault(window) ) window = last_window;
    if ( isDefault(time) )   t      = last_time;
  }

  host_last_time = mclock();
  last_time      = t;
  last_buttons   = bts;			/* save these values */
  last_x         = x;
  last_y         = y;

  assign(e, window,	window);
  assign(e, receiver,	window);
  assign(e, id,		id);
  assign(e, x,		x);
  assign(e, y,		y);
  assign(e, buttons,	bts);
  e->time = t;

  if ( isDownEvent(e) )
  { int clt = CLICK_TYPE_single;
    int px  = valInt(x);
    int py  = valInt(y);

    DEBUG(NAME_multiclick, Cprintf("t: %ld (%ld), x: %d (%d), y: %d (%d) --> ",
				   t, last_down_time, px, last_down_x,
				   py, last_down_y));

    if ( (valInt(e->buttons) & CLICK_TYPE_mask) == CLICK_TYPE_double )
    { switch( last_click_type )
      { case CLICK_TYPE_single:	clt = CLICK_TYPE_double; break;
	case CLICK_TYPE_double:	clt = CLICK_TYPE_triple; break;
	default:		clt = CLICK_TYPE_single; break;
      }
      e->buttons = toInt(valInt(e->buttons) & ~CLICK_TYPE_mask);
    } else
    { if ( (t - last_down_time) < multi_click_time &&
	   abs(last_down_x - px) <= multi_click_diff &&
	   abs(last_down_y - py) <= multi_click_diff &&
	   (valInt(last_down_bts)&BUTTON_mask) == (valInt(bts)&BUTTON_mask) &&
	   last_window == window )
      { switch( last_click_type )
	{ case CLICK_TYPE_single:	clt = CLICK_TYPE_double; break;
	  case CLICK_TYPE_double:	clt = CLICK_TYPE_triple; break;
	}
      }
    }

    last_click_type = clt;
    assign(e, buttons, toInt(valInt(e->buttons) | clt));

    DEBUG(NAME_multiclick, Cprintf("%s\n", strName(getMulticlickEvent(e))));

    last_down_bts     = bts;
    last_down_time    = t;
    last_down_x       = px;
    last_down_y       = py;
  } else if ( isUpEvent(e) )
  { assign(e, buttons, toInt(valInt(e->buttons) | last_click_type));
  }

  if ( !onFlag(window, F_FREED|F_FREEING) )
    last_window = window;

  if ( loc_still_posted )
  { if ( isAEvent(e, NAME_locMove) )
    { DEBUG(NAME_locStill, Cprintf("Re-enabled loc-still on %s\n", pp(e->id)));
      loc_still_posted = FALSE;
    }
  } else if ( isAEvent(e, NAME_area) ||
	      isAEvent(e, NAME_deactivateKeyboardFocus) )
  { DEBUG(NAME_locStill, Cprintf("Disabled loc-still on %s\n", pp(e->id)));
    loc_still_posted = TRUE;
  }

  succeed;
}
示例#24
0
// called only by factories, treat as private
UObject* 
ICUService::getKey(ICUServiceKey& key, UnicodeString* actualReturn, const ICUServiceFactory* factory, UErrorCode& status) const 
{
    if (U_FAILURE(status)) {
        return NULL;
    }

    if (isDefault()) {
        return handleDefault(key, actualReturn, status);
    }

    ICUService* ncthis = (ICUService*)this; // cast away semantic const

    CacheEntry* result = NULL;
    {
        // The factory list can't be modified until we're done, 
        // otherwise we might update the cache with an invalid result.
        // The cache has to stay in synch with the factory list.
        // ICU doesn't have monitors so we can't use rw locks, so 
        // we single-thread everything using this service, for now.

        // if factory is not null, we're calling from within the mutex,
        // and since some unix machines don't have reentrant mutexes we
        // need to make sure not to try to lock it again.
        XMutex mutex(&lock, factory != NULL);

        if (serviceCache == NULL) {
            ncthis->serviceCache = new Hashtable(status);
            if (ncthis->serviceCache == NULL) {
                return NULL;
            }
            if (U_FAILURE(status)) {
                delete serviceCache;
                return NULL;
            }
            serviceCache->setValueDeleter(cacheDeleter);
        }

        UnicodeString currentDescriptor;
        UVectorDeleter cacheDescriptorList;
        UBool putInCache = FALSE;

        int32_t startIndex = 0;
        int32_t limit = factories->size();
        UBool cacheResult = TRUE;

        if (factory != NULL) {
            for (int32_t i = 0; i < limit; ++i) {
                if (factory == (const ICUServiceFactory*)factories->elementAt(i)) {
                    startIndex = i + 1;
                    break;
                }
            }
            if (startIndex == 0) {
                // throw new InternalError("Factory " + factory + "not registered with service: " + this);
                status = U_ILLEGAL_ARGUMENT_ERROR;
                return NULL;
            }
            cacheResult = FALSE;
        }

        do {
            currentDescriptor.remove();
            key.currentDescriptor(currentDescriptor);
            result = (CacheEntry*)serviceCache->get(currentDescriptor);
            if (result != NULL) {
                break;
            }

            // first test of cache failed, so we'll have to update
            // the cache if we eventually succeed-- that is, if we're 
            // going to update the cache at all.
            putInCache = TRUE;

            int32_t index = startIndex;
            while (index < limit) {
                ICUServiceFactory* f = (ICUServiceFactory*)factories->elementAt(index++);
                UObject* service = f->create(key, this, status);
                if (U_FAILURE(status)) {
                    delete service;
                    return NULL;
                }
                if (service != NULL) {
                    result = new CacheEntry(currentDescriptor, service);
                    if (result == NULL) {
                        delete service;
                        status = U_MEMORY_ALLOCATION_ERROR;
                        return NULL;
                    }

                    goto outerEnd;
                }
            }

            // prepare to load the cache with all additional ids that 
            // will resolve to result, assuming we'll succeed.  We
            // don't want to keep querying on an id that's going to
            // fallback to the one that succeeded, we want to hit the
            // cache the first time next goaround.
            if (cacheDescriptorList._obj == NULL) {
                cacheDescriptorList._obj = new UVector(uprv_deleteUObject, NULL, 5, status);
                if (U_FAILURE(status)) {
                    return NULL;
                }
            }
            UnicodeString* idToCache = new UnicodeString(currentDescriptor);
            if (idToCache == NULL || idToCache->isBogus()) {
                status = U_MEMORY_ALLOCATION_ERROR;
                return NULL;
            }

            cacheDescriptorList._obj->addElement(idToCache, status);
            if (U_FAILURE(status)) {
                return NULL;
            }
        } while (key.fallback());
outerEnd:

        if (result != NULL) {
            if (putInCache && cacheResult) {
                serviceCache->put(result->actualDescriptor, result, status);
                if (U_FAILURE(status)) {
                    delete result;
                    return NULL;
                }

                if (cacheDescriptorList._obj != NULL) {
                    for (int32_t i = cacheDescriptorList._obj->size(); --i >= 0;) {
                        UnicodeString* desc = (UnicodeString*)cacheDescriptorList._obj->elementAt(i);
                        serviceCache->put(*desc, result, status);
                        if (U_FAILURE(status)) {
                            delete result;
                            return NULL;
                        }

                        result->ref();
                        cacheDescriptorList._obj->removeElementAt(i);
                    }
                }
            }

            if (actualReturn != NULL) {
                // strip null prefix
                if (result->actualDescriptor.indexOf((UChar)0x2f) == 0) { // U+002f=slash (/)
                    actualReturn->remove();
                    actualReturn->append(result->actualDescriptor, 
                        1, 
                        result->actualDescriptor.length() - 1);
                } else {
                    *actualReturn = result->actualDescriptor;
                }

                if (actualReturn->isBogus()) {
                    status = U_MEMORY_ALLOCATION_ERROR;
                    delete result;
                    return NULL;
                }
            }

            UObject* service = cloneInstance(result->service);
            if (putInCache && !cacheResult) {
                delete result;
            }
            return service;
        }
    }

    return handleDefault(key, actualReturn, status);
}
//----------------------------------------------------------------------------------------------
/// Execute the algorithm.
void EstimateFitParameters::execConcrete() {
  auto costFunction = getCostFunctionInitialized();
  auto func = costFunction->getFittingFunction();

  // Use additional constraints on parameters tied in some way
  // to the varied parameters to exculde unwanted results.
  std::vector<std::unique_ptr<IConstraint>> constraints;
  std::string constraintStr = getProperty("Constraints");
  if (!constraintStr.empty()) {
    Expression expr;
    expr.parse(constraintStr);
    expr.toList();
    for (auto &term : expr.terms()) {
      IConstraint *c =
          ConstraintFactory::Instance().createInitialized(func.get(), term);
      constraints.push_back(std::unique_ptr<IConstraint>(c));
    }
  }

  // Ranges to use with random number generators: one for each free parameter.
  std::vector<std::pair<double, double>> ranges;
  ranges.reserve(costFunction->nParams());
  for (size_t i = 0; i < func->nParams(); ++i) {
    if (!func->isActive(i)) {
      continue;
    }
    auto constraint = func->getConstraint(i);
    if (constraint == nullptr) {
      func->fix(i);
      continue;
    }
    auto boundary = dynamic_cast<Constraints::BoundaryConstraint *>(constraint);
    if (boundary == nullptr) {
      throw std::runtime_error("Parameter " + func->parameterName(i) +
                               " must have a boundary constraint. ");
    }
    if (!boundary->hasLower()) {
      throw std::runtime_error("Constraint of " + func->parameterName(i) +
                               " must have a lower bound.");
    }
    if (!boundary->hasUpper()) {
      throw std::runtime_error("Constraint of " + func->parameterName(i) +
                               " must have an upper bound.");
    }
    // Use the lower and upper bounds of the constraint to set the range
    // of a generator with uniform distribution.
    ranges.push_back(std::make_pair(boundary->lower(), boundary->upper()));
  }
  // Number of parameters could have changed
  costFunction->reset();
  if (costFunction->nParams() == 0) {
    throw std::runtime_error("No parameters are given for which to estimate "
                             "initial values. Set boundary constraints to "
                             "parameters that need to be estimated.");
  }

  size_t nSamples = static_cast<int>(getProperty("NSamples"));
  unsigned int seed = static_cast<int>(getProperty("Seed"));

  if (getPropertyValue("Type") == "Monte Carlo") {
    int nOutput = getProperty("NOutputs");
    auto outputWorkspaceProp = getPointerToProperty("OutputWorkspace");
    if (outputWorkspaceProp->isDefault() || nOutput <= 0) {
      nOutput = 1;
    }
    auto output = runMonteCarlo(*costFunction, ranges, constraints, nSamples,
                                static_cast<size_t>(nOutput), seed);

    if (!outputWorkspaceProp->isDefault()) {
      auto table = API::WorkspaceFactory::Instance().createTable();
      auto column = table->addColumn("str", "Name");
      column->setPlotType(6);
      for (size_t i = 0; i < output.size(); ++i) {
        column = table->addColumn("double", std::to_string(i + 1));
        column->setPlotType(2);
      }

      for (size_t i = 0, ia = 0; i < m_function->nParams(); ++i) {
        if (m_function->isActive(i)) {
          TableRow row = table->appendRow();
          row << m_function->parameterName(i);
          for (auto &j : output) {
            row << j[ia];
          }
          ++ia;
        }
      }
      setProperty("OutputWorkspace", table);
    }
  } else {
    size_t nSelection = static_cast<int>(getProperty("Selection"));
    size_t nIterations = static_cast<int>(getProperty("NIterations"));
    runCrossEntropy(*costFunction, ranges, constraints, nSamples, nSelection,
                    nIterations, seed);
  }
  bool fixBad = getProperty("FixBadParameters");
  if (fixBad) {
    fixBadParameters(*costFunction, ranges);
  }
}
/**
  * Gaussian fit to determine peak position if no user position given.
  *
  * @return :: detector position of the peak: Gaussian fit and position
  * of the maximum (serves as start value for the optimization)
  */
double LoadILLReflectometry::reflectometryPeak() {
  if (!isDefault("BeamCentre")) {
    return getProperty("BeamCentre");
  }
  size_t startIndex;
  size_t endIndex;
  std::tie(startIndex, endIndex) =
      fitIntegrationWSIndexRange(*m_localWorkspace);
  IAlgorithm_sptr integration = createChildAlgorithm("Integration");
  integration->initialize();
  integration->setProperty("InputWorkspace", m_localWorkspace);
  integration->setProperty("OutputWorkspace", "__unused_for_child");
  integration->setProperty("StartWorkspaceIndex", static_cast<int>(startIndex));
  integration->setProperty("EndWorkspaceIndex", static_cast<int>(endIndex));
  integration->execute();
  MatrixWorkspace_sptr integralWS = integration->getProperty("OutputWorkspace");
  IAlgorithm_sptr transpose = createChildAlgorithm("Transpose");
  transpose->initialize();
  transpose->setProperty("InputWorkspace", integralWS);
  transpose->setProperty("OutputWorkspace", "__unused_for_child");
  transpose->execute();
  integralWS = transpose->getProperty("OutputWorkspace");
  rebinIntegralWorkspace(*integralWS);
  // determine initial height: maximum value
  const auto maxValueIt =
      std::max_element(integralWS->y(0).cbegin(), integralWS->y(0).cend());
  const double height = *maxValueIt;
  // determine initial centre: index of the maximum value
  const size_t maxIndex = std::distance(integralWS->y(0).cbegin(), maxValueIt);
  const double centreByMax = static_cast<double>(maxIndex);
  g_log.debug() << "Peak maximum position: " << centreByMax << '\n';
  // determine sigma
  const auto &ys = integralWS->y(0);
  auto lessThanHalfMax = [height](const double x) { return x < 0.5 * height; };
  using IterType = HistogramData::HistogramY::const_iterator;
  std::reverse_iterator<IterType> revMaxValueIt{maxValueIt};
  auto revMinFwhmIt = std::find_if(revMaxValueIt, ys.crend(), lessThanHalfMax);
  auto maxFwhmIt = std::find_if(maxValueIt, ys.cend(), lessThanHalfMax);
  std::reverse_iterator<IterType> revMaxFwhmIt{maxFwhmIt};
  if (revMinFwhmIt == ys.crend() || maxFwhmIt == ys.cend()) {
    g_log.warning() << "Couldn't determine fwhm of beam, using position of max "
                       "value as beam center.\n";
    return centreByMax;
  }
  const double fwhm =
      static_cast<double>(std::distance(revMaxFwhmIt, revMinFwhmIt) + 1);
  g_log.debug() << "Initial fwhm (full width at half maximum): " << fwhm
                << '\n';
  // generate Gaussian
  auto func =
      API::FunctionFactory::Instance().createFunction("CompositeFunction");
  auto sum = boost::dynamic_pointer_cast<API::CompositeFunction>(func);
  func = API::FunctionFactory::Instance().createFunction("Gaussian");
  auto gaussian = boost::dynamic_pointer_cast<API::IPeakFunction>(func);
  gaussian->setHeight(height);
  gaussian->setCentre(centreByMax);
  gaussian->setFwhm(fwhm);
  sum->addFunction(gaussian);
  func = API::FunctionFactory::Instance().createFunction("LinearBackground");
  func->setParameter("A0", 0.);
  func->setParameter("A1", 0.);
  sum->addFunction(func);
  // call Fit child algorithm
  API::IAlgorithm_sptr fit = createChildAlgorithm("Fit");
  fit->initialize();
  fit->setProperty("Function",
                   boost::dynamic_pointer_cast<API::IFunction>(sum));
  fit->setProperty("InputWorkspace", integralWS);
  fit->setProperty("StartX", centreByMax - 3 * fwhm);
  fit->setProperty("EndX", centreByMax + 3 * fwhm);
  fit->execute();
  const std::string fitStatus = fit->getProperty("OutputStatus");
  if (fitStatus != "success") {
    g_log.warning("Fit not successful, using position of max value.\n");
    return centreByMax;
  }
  const auto centre = gaussian->centre();
  g_log.debug() << "Sigma: " << gaussian->fwhm() << '\n';
  g_log.debug() << "Estimated peak position: " << centre << '\n';
  return centre;
}
示例#27
0
/*!\brief TODO
//
// \param A TODO
// \param b TODO
// \param x TODO
// \return TODO
// \exception std::invalid_argument Invalid matrix size.
// \exception std::invalid_argument Invalid right-hand side vector size.
//
// TODO: description
// TODO: problem formulation \f$ A \cdot x + b = 0 \f$ !!
*/
bool GaussianElimination::solve( const CMatMxN& A, const VecN& b, VecN& x )
{
   if( A.rows() != A.columns() )
      throw std::invalid_argument( "Invalid matrix size" );

   if( A.rows() != b.size() )
      throw std::invalid_argument( "Invalid right-hand side vector size" );

   const size_t n( b.size() );

   // Allocating helper data
   A_ =  A;
   b_ = -b;
   x.resize( n, false );

   size_t pi, pj;
   lastPrecision_ = real(0);

   // Initializing the pivot vector
   DynamicVector<size_t> p( n );
   for( size_t j=0; j<n; ++j ) {
      p[j] = j;
   }

   // Performing the Gaussian elimination
   for( size_t j=0; j<n; ++j )
   {
      size_t max( j );
      real max_val( std::fabs( A_(p[max],j) ) );

      // Partial search for pivot
      for( size_t i=j+1; i<n; ++i ) {
         if( std::fabs( A_(p[i],j) ) > max_val ) {
            max = i;
            max_val = std::fabs( A_(p[max],j) );
         }
      }

      // Swapping rows such the pivot lies on the diagonal
      std::swap( p[max], p[j] );
      pj = p[j];

      if( !isDefault( A_(pj,j) ) )
      {
         // Eliminating the column below the diagonal
         for( size_t i=j+1; i<n; ++i )
         {
            pi = p[i];
            const real f = A_(pi,j) / A_(pj,j);

            reset( A_(pi,j) );

            for( size_t k=j+1; k<n; ++k ) {
               A_(pi,k) -= A_(pj,k) * f;
            }

            b_[pi] -= b_[pj] * f;
         }
      }
      else {
         // Asserting that the column is zero below the diagonal
         for( size_t i=j+1; i<n; ++i ) {
            BLAZE_INTERNAL_ASSERT( isDefault( A_(p[i],j) ), "Fatal error in Gaussian elimination" );
         }
      }
   }

   // Performing the backward substitution
   for( size_t i=n-1; i<n; --i )
   {
      pi = p[i];
      real rhs = b_[pi];

      for( size_t j=i+1; j<n; ++j ) {
         rhs -= x[j] * A_(pi,j);
      }

      if( std::fabs( A_(pi,i) ) > accuracy ) {
         x[i] = rhs / A_(pi,i);
      }
      else {
         // This will introduce errors in the solution
         reset( x[i] );
         lastPrecision_ = max( lastPrecision_, std::fabs( rhs ) );
      }
   }

   BLAZE_LOG_DEBUG_SECTION( log ) {
      if( lastPrecision_ < threshold_ )
         log << "      Solved the linear system using Gaussian elimination.";
      else
         log << BLAZE_YELLOW << "      WARNING: Did not solve the linear system within accuracy. (" << lastPrecision_ << ")" << BLAZE_OLDCOLOR;
   }

   lastIterations_ = 1;

   return lastPrecision_ < threshold_;
}
示例#28
0
BOOL LLURI::defaultPort() const
{
	return isDefault(mScheme, hostPort());
}
//! Draws the button text or pixmap. 
void QwtPushButton::drawButtonLabel(QPainter *painter)
{
#ifndef QT_NO_PICTURE
    // Unfortunately QStyle doesn´t offer an API to add
    // the alignment and rich text features. But we don´t want
    // to paint the button label on our own, as we would lose
    // the flexibility of the styles. So we let the style
    // paint the button label to a QPicture first, change
    // the paint commands and replay the manipulated commands
    // to the button.

    QwtPBPaintFilter paintFilter(this);

    QPainter picPainter(&paintFilter);
    picPainter.setFont(painter->font());

#if QT_VERSION >= 300
    // When painting to QPicture the dotted line of the focus rect is
    // set to solid. ( 06.08.2003 )
    // So we don´t set the Style_HasFocus flag and paint the focus rect
    // later directly to the button.

    QStyle::SFlags flags = QStyle::Style_Default;
    if (isEnabled())
        flags |= QStyle::Style_Enabled;
    if (isDown())
        flags |= QStyle::Style_Down;
    if (isOn())
        flags |= QStyle::Style_On;
    if (! isFlat() && ! isDown())
        flags |= QStyle::Style_Raised;
    if (isDefault())
        flags |= QStyle::Style_ButtonDefault;

    style().drawControl(QStyle::CE_PushButtonLabel, &picPainter, this,
            style().subRect(QStyle::SR_PushButtonContents, this),
            colorGroup(), flags);
#else
    // For Qt <= 2.x the focus rect is not painted in
    // drawButtonLabel. So we don´t need a workaround here.

    QPushButton::drawButtonLabel(&picPainter);
#endif

    picPainter.end();

    paintFilter.play(painter); 

#if QT_VERSION >= 300
    if (hasFocus())
    {
        // Paint the focus rect on top of the button label.

        flags |= QStyle::Style_HasFocus;
        style().drawPrimitive(QStyle::PE_FocusRect, painter, 
            style().subRect(QStyle::SR_PushButtonFocusRect, this), 
            colorGroup(), flags);
    }
#endif

#else // QT_NO_PICTURE
    QPushButton::drawButtonLabel(painter);
#endif
}
示例#30
0
	StartSampleStride(const char* timebase) {
		init();
		update();

		int rc = 0;
		const char* tok;


		// create from timebase 
		Tokenizer<vector<string> > args(timebase, ",");

		for (vector<string>::const_iterator i = args.list().begin();
		     i != args.list().end(); ++i){
			
			dbg(1, "element [%d] %s %s", 
			    rc, i->c_str(), args.list()[rc].c_str());

			++rc;
		}

		if (rc == 3 && !isDefault(tok = args.list()[2].c_str())){
			stride = atoi(tok);
			stride = MAX(1, stride);
		}else{
			stride = 1;
		}

		if (rc >= 1 && !isDefault(tok = args.list()[0].c_str())){
			start = MAX(0, atoi(tok));
			start = MIN(start, s2-s0);
		}else{
			start = 0;
		}

		start += s0;	/* s0 is negative */
		start /= stride;

		if (rc >= 2){
			if (isDefault(tok = args.list()[1].c_str())){
				samples = (s2 - s0)/stride;
			}else{
				int ss = atoi(tok);

				ss = MAX(1, ss);
				ss = MIN((s2 - s0)/stride, ss);
				samples = ss;
			}
		}else{
			samples = (s2 - s0)/stride;	
		}

		_sysstart = start*stride - s0;
		_sysstride = stride;

		ws0 = start;
       		ws2 = start + samples;				      

		dbg(1, "s0 %d $2 %d", s0, s2);
		dbg(1, "_sysstart %d _sysstride %d",
		    _sysstart, _sysstride);
		dbg(1, "start:%d ws0:%d samples:%d ws2:%d",
		    start, ws0, samples, ws2);
	}