예제 #1
0
def convert_ta(shyft_ta):
    ta = None
    if isinstance(shyft_ta, api.TimeAxisFixedDeltaT):
        # Fixed TA
        ta = TimeAxis(Calendar.Utc, UtcTime.CreateFromUnixTime(shyft_ta.start),
                      TimeSpan.FromSeconds(shyft_ta.delta_t), shyft_ta.n)
    elif isinstance(shyft_ta, api.PointTimeaxis):
        # Point TA
        ta = create_point_ta(shyft_ta)
    elif isinstance(shyft_ta, api.TimeAxis):
        # Generic TA: either Calendar | Fixed | Point
        if shyft_ta.timeaxis_type == api.TimeAxisType.FIXED:
            ta = TimeAxis(Calendar.Utc,
                          UtcTime.CreateFromUnixTime(shyft_ta.fixed_dt.start),
                          TimeSpan.FromSeconds(shyft_ta.fixed_dt.delta_t),
                          shyft_ta.fixed_dt.n)
        elif shyft_ta.timeaxis_type == api.TimeAxisType.CALENDAR:
            cal = Calendar(shyft_ta.calendar_dt.calendar.tz_info.name)
            ta = TimeAxis(
                cal, UtcTime.CreateFromUnixTime(shyft_ta.calendar_dt.start),
                TimeSpan.FromSeconds(shyft_ta.calendar_dt.delta_t),
                shyft_ta.calendar_dt.n)
        elif shyft_ta.timeaxis_type == api.TimeAxisType.POINT:
            ta = create_point_ta(shyft_ta.point_dt)
    if ta is None:
        raise SmgDataError('Unsupported shyft time-axis: ' + str(shyft_ta))
    return ta
예제 #2
0
    def __init__(self):
        rd = ResourceDictionary()
        rd.Source = Uri(
            "pack://application:,,,/ClassicAssist.Shared;component/Resources/DarkTheme.xaml"
        )
        self.Resources.MergedDictionaries.Add(rd)
        self.Background = self.Resources["ThemeWindowBackgroundBrush"]

        self.Content = XamlReader.Parse(xaml)
        self.Title = "Rudder"
        self.Topmost = True
        self.Height = 250
        self.Width = 250
        self.refreshTime = TimeSpan.FromSeconds(30)

        self.events = [('forwardLeft', 'Forward Left'), ('forward', 'Forward'),
                       ('forwardRight', 'Forward Right'), ('left', 'Left'),
                       ('turnAround', 'Turn Around'), ('right', 'Right'),
                       ('backLeft', 'Back Left'), ('back', 'Back'),
                       ('backRight', 'Back Right'), ('stop', 'Stop'),
                       ('raiseAnchor', 'Raise Anchor'),
                       ('dropAnchor', 'Drop Anchor'),
                       ('turnLeft', 'Turn Left'), ('turnRight', 'Turn Right'),
                       ('start', 'Start')]
        self.setEvents()
예제 #3
0
def onMouseLeftButtonUp(s, e):
	global y, storyboard

	if y is not None:
		if y > s.Top and storyboard is None:
			storyboard = Storyboard()
			da = DoubleAnimation(s.Top, y, TimeSpan.FromSeconds(Math.Sqrt(2 * ((y - s.Top) * 0.1) / 9.80665)))
			bounceEase = BounceEase()

			bounceEase.EasingMode = EasingMode.EaseOut
			bounceEase.Bounces = 5
			da.EasingFunction = bounceEase

			def onCurrentStateInvalidated(sender, args):
				global storyboard

				if sender.CurrentState == ClockState.Filling:
					s.Top = da.To
					storyboard.Remove(s)
					storyboard = None

			storyboard.CurrentStateInvalidated += onCurrentStateInvalidated
			storyboard.Children.Add(da)

			Storyboard.SetTargetProperty(da, PropertyPath(Window.TopProperty))
			s.BeginStoryboard(storyboard, HandoffBehavior.SnapshotAndReplace, True)

		y = None
예제 #4
0
    def on_loaded(self, s, e):
        bubble = Image()
        bubble.Name = "Bubble"
        #imageSource = System.Windows.Resources["think"]
        bubble.Source = self.thinkBubble
        bubble.SetValue(Canvas.TopProperty, self.currentY)
        bubble.SetValue(Canvas.LeftProperty, self.currentX)
        self.mainPanel.Children.Add(bubble)

        text = TextBox()
        text.Text = "???"
        text.FontSize = 65
        text.FontWeight = FontWeights.Bold
        text.BorderThickness = Thickness(0)
        text.SetValue(Canvas.TopProperty, self.currentY + 35)
        text.SetValue(Canvas.LeftProperty, self.currentX + 55)
        self.mainPanel.Children.Add(text)

        myDoubleAnimation = DoubleAnimation()
        myDoubleAnimation.From = 770.0
        myDoubleAnimation.To = 250.0

        myDoubleAnimation.Duration = Duration(TimeSpan.FromSeconds(3))

        myDoubleAnimationText = DoubleAnimation()
        myDoubleAnimationText.From = 770.0 + 35.0
        myDoubleAnimationText.To = 250.0 + 35.0

        myDoubleAnimationText.Duration = Duration(TimeSpan.FromSeconds(3))

        #myStoryboard = Storyboard()
        #myStoryboard.Children.Add(myDoubleAnimation)
        #Storyboard.SetTargetName(myDoubleAnimation, bubble.Name)
        #Storyboard.SetTargetProperty(myDoubleAnimation, PropertyPath(Canvas.TopProperty))

        #myStoryboard.Begin(self);

        bubble.BeginAnimation(Canvas.TopProperty, myDoubleAnimation)
        text.BeginAnimation(Canvas.TopProperty, myDoubleAnimationText)
예제 #5
0
    def connect(self):
        """Establish WebSocket connection to the ROS server defined for this factory.

        Returns:
            async_task: The async task for the connection.
        """
        LOGGER.debug('Started to connect...')
        socket = ClientWebSocket()
        socket.Options.KeepAliveInterval = TimeSpan.FromSeconds(5)
        connect_task = socket.ConnectAsync(self.url,
                                           self.manager.cancellation_token)

        protocol = CliRosBridgeProtocol(self, socket)
        connect_task.ContinueWith(protocol.on_open)

        return connect_task
	def __init__(self):
		rd = ResourceDictionary()
		rd.Source = Uri("pack://application:,,,/ClassicAssist.Shared;component/Resources/DarkTheme.xaml")
		self.Resources.MergedDictionaries.Add(rd)
		self.Background = self.Resources["ThemeWindowBackgroundBrush"]		
		
		self.Content = XamlReader.Parse(xaml)
		self.Title = "Durability"
		self.Topmost = True
		self.SizeToContent = SizeToContent.Width
		self.Height = 400
		self.refreshTime = TimeSpan.FromSeconds(30)
		
		self.listView = self.Content.FindName('listView')
		self.startButton = self.Content.FindName('startButton')
		self.startButton.Click += self.onClick
		
		self.timer = DispatcherTimer()
		self.timer.Tick += self.onTick
		self.timer.Interval = TimeSpan().FromSeconds(0)
		self.timer.Start()
		self.timer.Interval = self.refreshTime
		self.Running = True
예제 #7
0
import clr
from System import DateTime, DateTimeOffset, TimeSpan
clr.AddReference("WorkTasks")
from WorkTasks import WorkTask

cut_start = DateTimeOffset(1997, 3, 3, 15, 31, 34, 361,
                           TimeSpan.FromMinutes(500))
cut_details = "artio"
account = WorkTask(cut_start, cut_details)

cut_duration = TimeSpan.FromSeconds(25570)
account.Duration = cut_duration

abutting_task = WorkTask(cut_start + cut_duration, "corollarii")
not_abutting_task = WorkTask(cut_start + cut_duration + TimeSpan.FromTicks(1),
                             "poenae")


def test_abutting():
    "Do two WorkTasks abut?"
    return account.IsAbutting(abutting_task)


def test_not_abutting():
    "Do two WorkTasks NOT abut?"
    return account.IsAbutting(not_abutting_task)
start_time = None
iframes = ''

for t in tests:
    # TODO delete any existing files in IsoStore from this test

    iframes += '<iframe width="25%%" height="100" id=%s src="sub.html?test=%s"></iframe>' % (
        t, t)

sl_ctl = HtmlPage.Document.CreateElement("span")
sl_ctl.Id = "test-domain-loading"
sl_ctl.SetProperty("innerHTML", iframes)
HtmlPage.Document.Body.AppendChild(sl_ctl)

ht = DispatcherTimer()
ht.Interval = TimeSpan.FromSeconds(TimerInterval)
timer_counter = 0


def CheckForDonFile(sender, args):
    # check for exception and signal
    global timer_counter
    global tests

    if remaining_tests:
        if timer_counter > MAXTIMERCOUNT - 1:
            print "Time out! %d tests didn't finish." % len(remaining_tests)
            # stop timer
            ht.Stop()

        else:
예제 #9
0
    def train(self, lr, ui_results_callback, ui_status_callback, ui_logger,
              tf_settings):

        lr = 0.01

        NUM_HIDDEN_LAYERS = 3
        HIDDEN_LAYER_NEURONS = 500
        TF_ACTIVATION = tf.nn.sigmoid
        TF_OPTIMIZER = tf.train.GradientDescentOptimizer(learning_rate=lr)

        n_nodes_hl1 = HIDDEN_LAYER_NEURONS
        n_nodes_hl2 = HIDDEN_LAYER_NEURONS
        n_nodes_hl3 = HIDDEN_LAYER_NEURONS

        ui_status_callback("Initializing...")

        tf.reset_default_graph()  #Clear the Tensorflow graph.

        #These lines established the feed-forward part of the network. The agent takes a state and produces an action.
        self.slot_in = tf.placeholder(shape=[1], dtype=tf.int32)
        slot_in_OH = slim.one_hot_encoding(self.slot_in, self.numSlots)

        hidden_1_layer = {
            'weights':
            tf.Variable(tf.random_uniform([self.numSlots, n_nodes_hl1], 0.9,
                                          1),
                        name="hl_w_1"),
            'biases':
            tf.Variable(tf.random_normal([n_nodes_hl1]), name="hl_b_1")
        }

        hidden_2_layer = {
            'weights':
            tf.Variable(tf.random_uniform([n_nodes_hl1, n_nodes_hl2], 0.9, 1),
                        name="hl_w_2"),
            'biases':
            tf.Variable(tf.random_normal([n_nodes_hl2]), name="hl_b_2")
        }

        hidden_3_layer = {
            'weights':
            tf.Variable(tf.random_uniform([n_nodes_hl3, self.numSlots], 0.9,
                                          1),
                        name="hl_w_3"),
            'biases':
            tf.Variable(tf.random_normal([self.numSlots]), name="hl_b_3")
        }

        output_layer = {
            'weights':
            tf.Variable(tf.random_uniform([self.numSlots, self.numOutputs],
                                          0.9, 1),
                        name="out_w"),
            'biases':
            tf.Variable(tf.random_normal([self.numSlots, self.numOutputs]),
                        name="out_b"),
        }

        l1 = tf.add(tf.matmul(slot_in_OH, hidden_1_layer['weights']),
                    hidden_1_layer['biases'])
        l1 = TF_ACTIVATION(l1)

        l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']),
                    hidden_2_layer['biases'])
        l2 = TF_ACTIVATION(l2)

        l3 = tf.add(tf.matmul(l2, hidden_3_layer['weights']),
                    hidden_3_layer['biases'])
        l3 = TF_ACTIVATION(l3)

        output = tf.matmul(l3,
                           output_layer['weights']) + output_layer['biases']
        output = TF_ACTIVATION(output)

        #self.output = tf.reshape(output,[-1])

        #The next six lines establish the training proceedure. We feed the reward and chosen action into the network
        #to compute the loss, and use it to update the network.
        self.reward_holder = tf.placeholder(shape=[1], dtype=tf.float32)
        self.action_holder = tf.placeholder(shape=[1], dtype=tf.int32)
        #self.chosen_action = tf.argmin(output[self.slot_in[0]], 0)
        self.responsible_weight = tf.slice(
            output, [self.slot_in[0], self.action_holder[0]], [1, 1])
        self.loss = tf.log(
            self.responsible_weight[0][0]) * self.reward_holder[0]
        optimizer = TF_OPTIMIZER  #tf.train.AdamOptimizer(learning_rate=lr)
        self.update = optimizer.minimize(self.loss)
        weights = tf.trainable_variables()[
            6]  #The weights we will evaluate to look into the network.

        self.chosen_action = tf.argmin(weights[self.slot_in[0]], 0)

        #get tensorflow current settings and pass to UI
        optimizerName = optimizer.__class__.__name__
        activationName = TF_ACTIVATION.__name__
        tf_settings(optimizerName, activationName, NUM_HIDDEN_LAYERS,
                    HIDDEN_LAYER_NEURONS, lr)

        print(tf.trainable_variables())
        totalMetricScoreArr = []
        avgMetricScoreLastTen = []
        flag = 0
        startTime = time.time()
        sessionCounter = 0
        init = tf.initialize_all_variables()
        randomness = 0.05
        currRandomness = randomness

        ui_status_callback("Training...")

        trainingNum = -1
        predictNum = 0
        doPredict = False
        interval = randomness / (self.randomReset -
                                 SimulationSettings.NUM_SCORE_HITS)

        # Launch the tensorflow graph
        with tf.Session() as sess:
            sess.run(init)
            highestPossibleSessionScore = self.simSettings.Score  #self.simSettings.ItemMetricMax * self.numSlots
            lowestPossibleSessionScore = -1  #self.simSettings.ItemMetricMin * self.numSlots

            matrix = None
            while (not self.endTraining(flag)):
                totalMetricScore = 0
                results = PlanogramOptResults()
                sessionStartTime = time.time()
                actionsPerSlot = {}
                hasDupItems = False

                if (not doPredict):
                    trainingNum += 1
                    if (trainingNum != 0 and trainingNum %
                        (self.randomReset - SimulationSettings.NUM_SCORE_HITS)
                            == 0):
                        doPredict = True
                    else:
                        currRandomness -= interval

                if (doPredict):
                    predictNum += 1
                    currRandomness = 0
                    if (predictNum > SimulationSettings.NUM_SCORE_HITS):
                        doPredict = False
                        predictNum = 0
                        currRandomness = randomness
                        trainingNum = 0

                #Reset facings list
                facingsList = {}
                for it in self.items:
                    facingsList[it.ID] = 0

                #Train
                hasDupItems = False
                action = 0
                for sl in range(self.numSlots):
                    #get an item randomly
                    if (np.random.rand(1) <= currRandomness):
                        action = np.random.randint(self.numOutputs)
                    else:
                        action = sess.run(self.chosen_action,
                                          feed_dict={self.slot_in: [sl]})

                    actionsPerSlot[sl] = action

                    #Get item reference and calculate metric score
                    item = self.items[action]
                    metricScore = PlanogramOptimizer.GetCalculatedWeightedMetrics(
                        item, self.simSettings)

                    dupItemVal = facingsList[
                        item.ID]  #Get item number of facings

                    if (not hasDupItems and dupItemVal < 10):
                        reward = 1
                        dupItemVal = dupItemVal + 1  #Increment item number of facings
                        facingsList[
                            item.
                            ID] = dupItemVal  #Update item number of facings in the list
                        totalMetricScore += metricScore
                    else:
                        totalMetricScore = 0
                        reward = -1
                        hasDupItems = True

                if (lowestPossibleSessionScore < 0):
                    lowestPossibleSessionScore = totalMetricScore

                #Update network
                #print (totalMetricScore)
                if (hasDupItems):
                    totalMetricScore = 0
                    sessionScoreNormalized = -1
                else:
                    sessionScoreNormalized = self.normalize(
                        lowestPossibleSessionScore,
                        highestPossibleSessionScore, 0, 1, totalMetricScore)

                previousValue = 0
                currentValue = 0
                if (not doPredict or (doPredict and predictNum <= 1)):
                    for sl in range(self.numSlots):
                        feed_dict = {
                            self.reward_holder: [sessionScoreNormalized],
                            self.action_holder: [actionsPerSlot[sl]],
                            self.slot_in: [sl]
                        }
                        if (matrix is not None):
                            previousValue = matrix[sl][actionsPerSlot[sl]]
                        loss, update, matrix = sess.run(
                            [self.loss, self.update, weights],
                            feed_dict=feed_dict)
                        currentValue = matrix[sl][actionsPerSlot[sl]]
                        if (sl != 0 and (sessionScoreNormalized > 0
                                         and previousValue < currentValue)
                                or (sessionScoreNormalized < 0
                                    and previousValue > currentValue)):
                            print("BAD: score:", sessionScoreNormalized,
                                  "previous:", previousValue, " current:",
                                  currentValue)

                #Reset facings list
                facingsList = {}
                for it in self.items:
                    facingsList[it.ID] = 0

                totalMetricScore = 0
                #Extract updated results from matrix
                shelfItems = []
                for slotIndex in range(self.numSlots):

                    #slotArr = matrix[slotIndex]
                    itemIndex = actionsPerSlot[slotIndex]  #np.argmin(slotArr)
                    item = self.items[itemIndex]
                    shelfItems.append(item)
                    #actionsPerSlot[slotIndex] = itemIndex

                    dupItemVal = facingsList[
                        item.ID]  #Get item number of facings

                    if (dupItemVal < 10):
                        dupItemVal = dupItemVal + 1  #Increment item number of facings
                        facingsList[
                            item.
                            ID] = dupItemVal  #Update item number of facings in the list
                    else:
                        hasDupItems = True

                    if ((slotIndex + 1) % 24 == 0):
                        shelf = Shelf()
                        for ii in range(len(shelfItems)):
                            metricScore = PlanogramOptimizer.GetCalculatedWeightedMetrics(
                                shelfItems[ii], self.simSettings)
                            totalMetricScore += metricScore
                            shelf.Add(shelfItems[ii], metricScore)
                        shelfItems = []
                        results.Shelves.Add(shelf)

                if (hasDupItems):
                    totalMetricScore = 0

                sessionCounter += 1
                currentTime = time.time()

                #Setup planogram results and stats
                totalMetricScoreArr.append(totalMetricScore)
                avgMetricScoreLastTen.append(totalMetricScore)
                if (len(avgMetricScoreLastTen) > 10):
                    avgMetricScoreLastTen.pop(0)

                results.Score = totalMetricScore
                results.AvgScore = np.average(totalMetricScoreArr)
                results.AvgLastTen = np.average(avgMetricScoreLastTen)
                results.MinScore = np.amin(totalMetricScoreArr)
                results.MaxScore = np.amax(totalMetricScoreArr)
                results.TimeElapsed = TimeSpan.FromSeconds(
                    float(currentTime - startTime))
                results.CurrentSession = sessionCounter

                #Update the training flag
                if (self.simType == 0):
                    flag = sessionCounter
                elif (self.simType == 1):
                    flag = currentTime
                else:
                    if (totalMetricScore >= self.simSettings.Score):
                        flag += 1
                        results.NumScoreHits = flag
                    else:
                        flag = 0

                ui_logger(sessionCounter, totalMetricScore,
                          float(currentTime - sessionStartTime))

                #Pass results to ui
                if (self.simSettings.EnableSimDisplay):
                    results.MetricMin = self.simSettings.ItemMetricMin
                    results.MetricMax = self.simSettings.ItemMetricMax
                    results.CalculateItemColorIntensity()
                ui_results_callback(results, self.simSettings.EnableSimDisplay)

            ui_results_callback(
                results, True
            )  #To ensure final output is displayed just in case the enableSimDisplay is turned off
            ui_status_callback("Done", True)
def SnapImage():
    '''
    Snap and save an image
    '''
    image = snapsink.SnapSingle(TimeSpan.FromSeconds(1))
    TIS.Imaging.FrameExtensions.SaveAsBitmap(image, "test.bmp")
예제 #11
0
    def train(self, lr, ui_results_callback, ui_status_callback, ui_logger):
        n_nodes_hl1 = 500
        n_nodes_hl2 = 500
        n_nodes_hl3 = 500

        ui_status_callback("Initializing...")

        tf.reset_default_graph()  #Clear the Tensorflow graph.

        #These lines established the feed-forward part of the network. The agent takes a state and produces an action.
        self.slot_in = tf.placeholder(shape=[1], dtype=tf.int32)
        slot_in_OH = slim.one_hot_encoding(self.slot_in, self.numSlots)
        #output = slim.fully_connected([slot_in_OH],self.numOutputs,\
        #    biases_initializer=None,activation_fn=tf.nn.sigmoid,weights_initializer=tf.zeros_initializer())

        hidden_1_layer = {
            'weights':
            tf.Variable(tf.random_normal([self.numSlots, n_nodes_hl1]),
                        name="hl_w_1"),
            'biases':
            tf.Variable(tf.random_normal([n_nodes_hl1]), name="hl_b_1")
        }

        hidden_2_layer = {
            'weights':
            tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2]),
                        name="hl_w_2"),
            'biases':
            tf.Variable(tf.random_normal([n_nodes_hl2]), name="hl_b_2")
        }

        hidden_3_layer = {
            'weights':
            tf.Variable(tf.random_normal([n_nodes_hl3, self.numSlots]),
                        name="hl_w_3"),
            'biases':
            tf.Variable(tf.random_normal([self.numSlots]), name="hl_b_3")
        }

        output_layer = {
            'weights':
            tf.Variable(tf.random_normal([self.numSlots, self.numOutputs]),
                        name="out_w"),
            'biases':
            tf.Variable(tf.random_normal([self.numSlots, self.numOutputs]),
                        name="out_b"),
        }

        l1 = tf.add(tf.matmul(slot_in_OH, hidden_1_layer['weights']),
                    hidden_1_layer['biases'])
        l1 = tf.nn.sigmoid(l1)

        l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']),
                    hidden_2_layer['biases'])
        l2 = tf.nn.sigmoid(l2)

        l3 = tf.add(tf.matmul(l2, hidden_3_layer['weights']),
                    hidden_3_layer['biases'])
        l3 = tf.nn.sigmoid(l3)

        output = tf.matmul(l3,
                           output_layer['weights']) + output_layer['biases']

        self.output = tf.reshape(output, [-1])
        self.chosen_action = tf.argmax(self.output, 0)

        #The next six lines establish the training proceedure. We feed the reward and chosen action into the network
        #to compute the loss, and use it to update the network.
        self.reward_holder = tf.placeholder(shape=[1], dtype=tf.float32)
        self.action_holder = tf.placeholder(shape=[1], dtype=tf.int32)
        self.responsible_weight = tf.slice(self.output, self.action_holder,
                                           [1])
        self.loss = -(tf.log(self.responsible_weight) * self.reward_holder)
        optimizer = tf.train.GradientDescentOptimizer(
            learning_rate=lr
        )  #tf.train.GradientDescentOptimizer(learning_rate=lr)
        self.update = optimizer.minimize(self.loss)
        weights = tf.trainable_variables()[
            6]  #The weights we will evaluate to look into the network.

        print(tf.trainable_variables())
        totalMetricScoreArr = []
        avgMetricScoreLastTen = []
        flag = 0
        startTime = time.time()
        sessionCounter = 0
        init = tf.initialize_all_variables()
        randomness = 0.1

        ui_status_callback("Training...")

        # Launch the tensorflow graph
        with tf.Session() as sess:
            sess.run(init)
            highestPossibleSessionScore = self.simSettings.ItemMetricMax * self.numSlots
            lowestPossibleSessionScore = self.simSettings.ItemMetricMin * self.numSlots

            matrix = {}
            while (not self.endTraining(flag)):
                totalMetricScore = 0
                results = PlanogramOptResults()
                sessionStartTime = time.time()
                actionsPerSlot = {}
                hasDupItems = False

                #Reset facings list
                facingsList = {}
                for it in self.items:
                    facingsList[it.ID] = 0

                #Train
                hasDupItems = False
                for sl in range(self.numSlots):
                    reward = 0
                    while (reward != 1):
                        #get an item randomly
                        action = np.random.randint(self.numOutputs)

                        #Get item reference and calculate metric score
                        item = self.items[action]
                        metricScore = PlanogramOptimizer.GetCalculatedWeightedMetrics(
                            item, self.simSettings)

                        dupItemVal = facingsList[
                            item.ID]  #Get item number of facings

                        if (dupItemVal < 10):
                            reward = 1
                            dupItemVal = dupItemVal + 1  #Increment item number of facings
                            facingsList[
                                item.
                                ID] = dupItemVal  #Update item number of facings in the list
                            actionsPerSlot[sl] = action
                            totalMetricScore += metricScore
                        else:
                            reward = -1
                            hasDupItems = True

                #Update network
                #print (totalMetricScore)
                if (hasDupItems):
                    totalMetricScore = 0
                    sessionScoreNormalized = 0
                else:
                    sessionScoreNormalized = self.normalize(
                        lowestPossibleSessionScore,
                        highestPossibleSessionScore, 0, 1, totalMetricScore)

                for sl in range(self.numSlots):
                    feed_dict = {
                        self.reward_holder: [sessionScoreNormalized],
                        self.action_holder: [actionsPerSlot[sl]],
                        self.slot_in: [sl]
                    }
                    _, matrix = sess.run([self.update, output],
                                         feed_dict=feed_dict)

                #if (sessionCounter == 0):
                #    matrix = sess.run([output], feed_dict={self.slot_in: [0]})

                #Reset facings list
                facingsList = {}
                for it in self.items:
                    facingsList[it.ID] = 0

                totalMetricScore = 0
                #Extract updated results from matrix
                shelfItems = []
                for slotIndex in range(self.numSlots):
                    #itemIndex = -1

                    #if (np.random.rand(1) < randomness):
                    #    itemIndex = np.random.randint(self.numOutputs)
                    #else:
                    #    slotArr = 0
                    #    if (sessionCounter == 0) :
                    #        slotArr = matrix[0][slotIndex]
                    #    else:
                    #        slotArr = matrix[slotIndex]

                    #    itemIndex = np.argmax(slotArr)

                    slotArr = matrix[slotIndex]
                    itemIndex = np.argmax(slotArr)
                    item = self.items[itemIndex]
                    shelfItems.append(item)
                    #actionsPerSlot[slotIndex] = itemIndex

                    dupItemVal = facingsList[
                        item.ID]  #Get item number of facings

                    if (dupItemVal < 10):
                        dupItemVal = dupItemVal + 1  #Increment item number of facings
                        facingsList[
                            item.
                            ID] = dupItemVal  #Update item number of facings in the list
                    else:
                        hasDupItems = True

                    if ((slotIndex + 1) % 24 == 0):
                        shelf = Shelf()
                        for ii in range(len(shelfItems)):
                            metricScore = PlanogramOptimizer.GetCalculatedWeightedMetrics(
                                shelfItems[ii], self.simSettings)
                            totalMetricScore += metricScore
                            shelf.Add(shelfItems[ii], metricScore)
                        shelfItems = []
                        results.Shelves.Add(shelf)

                if (hasDupItems):
                    totalMetricScore = 0
                #    sessionScoreNormalized = 0
                #else:
                #    sessionScoreNormalized = self.normalize(lowestPossibleSessionScore, highestPossibleSessionScore, 0, 1, totalMetricScore)

                #for sl in range(self.numSlots):
                #    feed_dict={self.reward_holder:[sessionScoreNormalized],self.action_holder:[actionsPerSlot[sl]],self.slot_in:[sl]}
                #    _,matrix = sess.run([self.update,output], feed_dict=feed_dict)

                sessionCounter += 1
                currentTime = time.time()

                #Setup planogram results and stats
                totalMetricScoreArr.append(totalMetricScore)
                avgMetricScoreLastTen.append(totalMetricScore)
                if (len(avgMetricScoreLastTen) > 10):
                    avgMetricScoreLastTen.pop(0)

                results.Score = totalMetricScore
                results.AvgScore = np.average(totalMetricScoreArr)
                results.AvgLastTen = np.average(avgMetricScoreLastTen)
                results.MinScore = np.amin(totalMetricScoreArr)
                results.MaxScore = np.amax(totalMetricScoreArr)
                results.TimeElapsed = TimeSpan.FromSeconds(
                    float(currentTime - startTime))
                results.CurrentSession = sessionCounter

                #Update the training flag
                if (self.simType == 0):
                    flag = sessionCounter
                elif (self.simType == 1):
                    flag = currentTime
                else:
                    if (totalMetricScore >= self.simSettings.Score):
                        flag += 1
                        results.NumScoreHits = flag
                    else:
                        flag = 0

                ui_logger(sessionCounter, totalMetricScore,
                          float(currentTime - sessionStartTime))

                #Pass results to ui
                if (self.simSettings.EnableSimDisplay):
                    results.MetricMin = self.simSettings.ItemMetricMin
                    results.MetricMax = self.simSettings.ItemMetricMax
                    results.CalculateItemColorIntensity()
                ui_results_callback(results, self.simSettings.EnableSimDisplay)

            ui_results_callback(
                results, True
            )  #To ensure final output is displayed just in case the enableSimDisplay is turned off
            ui_status_callback("Done", True)
예제 #12
0
			if not String.IsNullOrEmpty(selectedTerm2) and selectedTerm1.Length < selectedTerm2.Length:
				if not selectedTermList.Contains(selectedTerm2):
					selectedTermList.Add(selectedTerm2)

				stringBuilder.Remove(0, max)

			else:
				if not selectedTermList.Contains(selectedTerm1):
					selectedTermList.Add(selectedTerm1)

				stringBuilder.Remove(0, selectedTerm1.Length)

	return selectedTermList

def onStart(s, e):
	global timer

	timer.Start()

def onStop(s, e):
	global timer
	
	timer.Stop()

dateTime = DateTime.Now
processDictionary = Dictionary[Int32, String]()
timer = DispatcherTimer(DispatcherPriority.Background)
timer.Tick += onTick
timer.Interval = TimeSpan.FromSeconds(15)
Script.Instance.Start += onStart
Script.Instance.Stop += onStop
예제 #13
0
# Disable Gain automatic
if GainAuto is not None:
    GainAuto.Switch = False

# Set minimum gain
if GainValue is not None:
    GainValue.Value = GainValue.RangeMin

# Disable Exposure automatic
if ExposureAuto is not None:
    ExposureAuto.Switch = False

# Set 1/30 second exosure time
if ExposureValue is not None:
    ExposureValue.Value = 0.0303

# Snap two frames in order to be sure, the set values became effective in the sensor.
# It is not necessary, if we do not change properties directly before snapping an image.
# use the second frame
snapsink.SnapSingle(TimeSpan.FromSeconds(5))
frame = snapsink.SnapSingle(TimeSpan.FromSeconds(5))

# Save the frame as JPG with 75% quality.
TIS.Imaging.FrameExtensions.SaveAsJpeg(frame, "image.jpg", 75)

print("Image saved.")
#End the live video
ic.LiveStop()
ic.Dispose()
예제 #14
0
파일: Clock.py 프로젝트: soracoder/Apricot
        def onCompleted(task):
            global maxWidth, maxHeight

            window = Window()
            contentControl = ContentControl()
            grid1 = Grid()
            tickTimer = DispatcherTimer(DispatcherPriority.Normal)
            closeTimer = DispatcherTimer(DispatcherPriority.Background)

            def onLoaded(sender, args):
                global rectList, digits

                storyboard = Storyboard()

                def onCurrentStateInvalidated(sender, args):
                    if sender.CurrentState == ClockState.Filling:
                        for element in grid1.Children:
                            element.Opacity = 1

                        storyboard.Remove(contentControl)

                        if not grid1.Tag:
                            closeTimer.Start()

                storyboard.CurrentStateInvalidated += onCurrentStateInvalidated

                r = Random(Environment.TickCount)
                dateTime = DateTime.Now

                digits[0] = dateTime.Hour / 10
                digits[1] = dateTime.Hour % 10
                digits[2] = dateTime.Minute / 10
                digits[3] = dateTime.Minute % 10
                digits[4] = dateTime.Second / 10
                digits[5] = dateTime.Second % 10

                for i in range(digits.Length):
                    beginTime = Nullable[TimeSpan](TimeSpan.FromMilliseconds(
                        r.Next(500)))

                    for element1 in grid1.Children:
                        if Grid.GetColumn(element1) == i:
                            doubleAnimation = DoubleAnimation(
                                element1.Opacity, 1,
                                TimeSpan.FromMilliseconds(500))
                            doubleAnimation.BeginTime = beginTime
                            sineEase = SineEase()

                            sineEase.EasingMode = EasingMode.EaseOut
                            doubleAnimation.EasingFunction = sineEase

                            storyboard.Children.Add(doubleAnimation)

                            Storyboard.SetTarget(doubleAnimation, element1)
                            Storyboard.SetTargetProperty(
                                doubleAnimation,
                                PropertyPath(UIElement.OpacityProperty))

                            if Grid.GetRow(element1) == 0:
                                scale1 = Math.Max(
                                    element1.ActualWidth / maxWidth,
                                    element1.ActualHeight / maxHeight)

                                if rectList[digits[Grid.GetColumn(
                                        element1
                                )]].Width > maxWidth and rectList[digits[
                                        Grid.GetColumn(
                                            element1)]].Height > maxHeight:
                                    translateX = Math.Round(
                                        -(rectList[digits[Grid.GetColumn(
                                            element1)]].X +
                                          (rectList[digits[Grid.GetColumn(
                                              element1)]].Width - maxWidth) /
                                          2.0))
                                    translateY = Math.Round(
                                        -(rectList[digits[Grid.GetColumn(
                                            element1)]].Y +
                                          (rectList[digits[Grid.GetColumn(
                                              element1)]].Height - maxHeight) /
                                          2.0))

                                elif rectList[digits[Grid.GetColumn(
                                        element1)]].Width > maxWidth:
                                    translateX = Math.Round(
                                        -(rectList[digits[Grid.GetColumn(
                                            element1)]].X +
                                          (rectList[digits[Grid.GetColumn(
                                              element1)]].Width - maxWidth) /
                                          2.0))
                                    translateY = Math.Round(-rectList[digits[
                                        Grid.GetColumn(element1)]].Y)

                                elif rectList[digits[Grid.GetColumn(
                                        element1)]].Height > maxHeight:
                                    translateX = Math.Round(-rectList[digits[
                                        Grid.GetColumn(element1)]].X)
                                    translateY = Math.Round(
                                        -(rectList[digits[Grid.GetColumn(
                                            element1)]].Y +
                                          (rectList[digits[Grid.GetColumn(
                                              element1)]].Height - maxHeight) /
                                          2.0))

                                else:
                                    translateX = Math.Round(-rectList[digits[
                                        Grid.GetColumn(element1)]].X)
                                    translateY = Math.Round(-rectList[digits[
                                        Grid.GetColumn(element1)]].Y)

                                scale2 = Math.Max(
                                    maxWidth / rectList[digits[Grid.GetColumn(
                                        element1)]].Width,
                                    maxHeight / rectList[digits[Grid.GetColumn(
                                        element1)]].Height)

                                if scale2 > 1:
                                    scale2 = 1

                                for element2 in element1.Child.Children:
                                    transformGroup1 = TransformGroup()
                                    transformGroup1.Children.Add(
                                        TranslateTransform(
                                            (element2.ActualWidth - maxWidth) /
                                            2,
                                            (element2.ActualHeight - maxHeight)
                                            / 2))
                                    transformGroup1.Children.Add(
                                        ScaleTransform(
                                            scale1, scale1,
                                            element2.ActualWidth / 2,
                                            element2.ActualHeight / 2))

                                    element2.RenderTransform = transformGroup1

                                    for element3 in element2.Children:
                                        transformGroup2 = TransformGroup()
                                        transformGroup2.Children.Add(
                                            TranslateTransform(
                                                translateX, translateY))
                                        transformGroup2.Children.Add(
                                            ScaleTransform(
                                                scale2, scale2, maxWidth / 2,
                                                maxHeight / 2))

                                        element3.RenderTransform = transformGroup2

                contentControl.BeginStoryboard(
                    storyboard, HandoffBehavior.SnapshotAndReplace, True)

                tickTimer.Start()

            def onWindowMouseEnter(sender, args):
                closeTimer.Stop()
                grid1.Tag = True

            def onWindowMouseLeave(sender, args):
                if closeTimer.Tag:
                    closeTimer.Start()

                grid1.Tag = False

            def onTick(sender, args):
                global rectList, digits

                if rectList.Count > 0:
                    dateTime = DateTime.Now

                    for element1 in grid1.Children:
                        if Grid.GetRow(element1) == 0:
                            if Grid.GetColumn(element1) == 0:
                                digit = dateTime.Hour / 10
                            elif Grid.GetColumn(element1) == 1:
                                digit = dateTime.Hour % 10
                            elif Grid.GetColumn(element1) == 2:
                                digit = dateTime.Minute / 10
                            elif Grid.GetColumn(element1) == 3:
                                digit = dateTime.Minute % 10
                            elif Grid.GetColumn(element1) == 4:
                                digit = dateTime.Second / 10
                            else:
                                digit = dateTime.Second % 10

                            if digit != digits[Grid.GetColumn(element1)]:
                                for element2 in element1.Child.Children:
                                    for element3 in element2.Children:
                                        storyboard = Storyboard()

                                        for transform in element3.RenderTransform.Children:
                                            if clr.GetClrType(
                                                    TranslateTransform
                                            ).IsInstanceOfType(transform):
                                                if rectList[
                                                        digit].Width > maxWidth and rectList[
                                                            digit].Height > maxHeight:
                                                    translateX = Math.Round(-(
                                                        rectList[digits[
                                                            Grid.GetColumn(
                                                                element1)]].X +
                                                        (rectList[digit].X +
                                                         (rectList[digit].Width
                                                          - maxWidth) / 2.0 -
                                                         rectList[digits[
                                                             Grid.GetColumn(
                                                                 element1)]].X)
                                                    ))
                                                    translateY = Math.Round(-(
                                                        rectList[digits[
                                                            Grid.GetColumn(
                                                                element1)]].Y +
                                                        (rectList[digit].Y +
                                                         (rectList[digit].
                                                          Height - maxHeight) /
                                                         2.0 - rectList[digits[
                                                             Grid.GetColumn(
                                                                 element1)]].Y)
                                                    ))

                                                elif rectList[
                                                        digit].Width > maxWidth:
                                                    translateX = Math.Round(-(
                                                        rectList[digits[
                                                            Grid.GetColumn(
                                                                element1)]].X +
                                                        (rectList[digit].X +
                                                         (rectList[digit].Width
                                                          - maxWidth) / 2.0 -
                                                         rectList[digits[
                                                             Grid.GetColumn(
                                                                 element1)]].X)
                                                    ))
                                                    translateY = Math.Round(-(
                                                        rectList[digits[
                                                            Grid.GetColumn(
                                                                element1)]].Y +
                                                        (rectList[digit].Y -
                                                         rectList[digits[
                                                             Grid.GetColumn(
                                                                 element1)]].Y)
                                                    ))

                                                elif rectList[
                                                        digit].Height > maxHeight:
                                                    translateX = Math.Round(-(
                                                        rectList[digits[
                                                            Grid.GetColumn(
                                                                element1)]].X +
                                                        (rectList[digit].X -
                                                         rectList[digits[
                                                             Grid.GetColumn(
                                                                 element1)]].X)
                                                    ))
                                                    translateY = Math.Round(-(
                                                        rectList[digits[
                                                            Grid.GetColumn(
                                                                element1)]].Y +
                                                        (rectList[digit].Y +
                                                         (rectList[digit].
                                                          Height - maxHeight) /
                                                         2.0 - rectList[digits[
                                                             Grid.GetColumn(
                                                                 element1)]].Y)
                                                    ))

                                                else:
                                                    translateX = Math.Round(-(
                                                        rectList[digits[
                                                            Grid.GetColumn(
                                                                element1)]].X +
                                                        (rectList[digit].X -
                                                         rectList[digits[
                                                             Grid.GetColumn(
                                                                 element1)]].X)
                                                    ))
                                                    translateY = Math.Round(-(
                                                        rectList[digits[
                                                            Grid.GetColumn(
                                                                element1)]].Y +
                                                        (rectList[digit].Y -
                                                         rectList[digits[
                                                             Grid.GetColumn(
                                                                 element1)]].Y)
                                                    ))

                                                doubleAnimation1 = DoubleAnimation(
                                                    translateX,
                                                    TimeSpan.FromMilliseconds(
                                                        500))
                                                doubleAnimation2 = DoubleAnimation(
                                                    translateY,
                                                    TimeSpan.FromMilliseconds(
                                                        500))
                                                sineEase = SineEase()

                                                sineEase.EasingMode = EasingMode.EaseInOut
                                                doubleAnimation1.EasingFunction = sineEase
                                                doubleAnimation2.EasingFunction = sineEase

                                                storyboard.Children.Add(
                                                    doubleAnimation1)
                                                storyboard.Children.Add(
                                                    doubleAnimation2)

                                                Storyboard.SetTarget(
                                                    doubleAnimation1, element3)
                                                Storyboard.SetTarget(
                                                    doubleAnimation2, element3)
                                                Storyboard.SetTargetProperty(
                                                    doubleAnimation1,
                                                    PropertyPath(
                                                        "(0).(1)[0].(2)",
                                                        Canvas.
                                                        RenderTransformProperty,
                                                        TransformGroup.
                                                        ChildrenProperty,
                                                        TranslateTransform.
                                                        XProperty))
                                                Storyboard.SetTargetProperty(
                                                    doubleAnimation2,
                                                    PropertyPath(
                                                        "(0).(1)[0].(2)",
                                                        Canvas.
                                                        RenderTransformProperty,
                                                        TransformGroup.
                                                        ChildrenProperty,
                                                        TranslateTransform.
                                                        YProperty))

                                            else:
                                                scale1 = Math.Max(
                                                    maxWidth / rectList[digits[
                                                        Grid.GetColumn(
                                                            element1)]].Width,
                                                    maxHeight / rectList[
                                                        digits[Grid.GetColumn(
                                                            element1)]].Height)
                                                scale2 = Math.Max(
                                                    maxWidth /
                                                    rectList[digit].Width,
                                                    maxHeight /
                                                    rectList[digit].Height)

                                                if scale1 > 1:
                                                    scale1 = 1

                                                if scale2 > 1:
                                                    scale2 = 1

                                                transform.ScaleX = transform.ScaleY = scale1 + (
                                                    scale2 - scale1)

                                                doubleAnimation1 = DoubleAnimation(
                                                    scale1 + (scale2 - scale1),
                                                    TimeSpan.FromMilliseconds(
                                                        500))
                                                doubleAnimation2 = DoubleAnimation(
                                                    scale1 + (scale2 - scale1),
                                                    TimeSpan.FromMilliseconds(
                                                        500))
                                                sineEase = SineEase()

                                                sineEase.EasingMode = EasingMode.EaseInOut
                                                doubleAnimation1.EasingFunction = sineEase
                                                doubleAnimation2.EasingFunction = sineEase

                                                storyboard.Children.Add(
                                                    doubleAnimation1)
                                                storyboard.Children.Add(
                                                    doubleAnimation2)

                                                Storyboard.SetTarget(
                                                    doubleAnimation1, element3)
                                                Storyboard.SetTarget(
                                                    doubleAnimation2, element3)
                                                Storyboard.SetTargetProperty(
                                                    doubleAnimation1,
                                                    PropertyPath(
                                                        "(0).(1)[1].(2)",
                                                        Canvas.
                                                        RenderTransformProperty,
                                                        TransformGroup.
                                                        ChildrenProperty,
                                                        ScaleTransform.
                                                        ScaleXProperty))
                                                Storyboard.SetTargetProperty(
                                                    doubleAnimation2,
                                                    PropertyPath(
                                                        "(0).(1)[1].(2)",
                                                        Canvas.
                                                        RenderTransformProperty,
                                                        TransformGroup.
                                                        ChildrenProperty,
                                                        ScaleTransform.
                                                        ScaleYProperty))

                                        element3.BeginStoryboard(
                                            storyboard,
                                            HandoffBehavior.SnapshotAndReplace)

                                digits[Grid.GetColumn(element1)] = digit

            def onClose(sender, args):
                global digits

                closeTimer.Stop()

                storyboard = Storyboard()

                def onCurrentStateInvalidated(sender, args):
                    if sender.CurrentState == ClockState.Filling:
                        for element in grid1.Children:
                            element.Opacity = 0

                        storyboard.Remove(contentControl)
                        tickTimer.Stop()
                        window.Close()

                storyboard.CurrentStateInvalidated += onCurrentStateInvalidated

                r = Random(Environment.TickCount)

                for i in range(digits.Length):
                    beginTime = Nullable[TimeSpan](TimeSpan.FromMilliseconds(
                        r.Next(500)))

                    for element in grid1.Children:
                        if Grid.GetColumn(element) == i:
                            doubleAnimation = DoubleAnimation(
                                element.Opacity, 0,
                                TimeSpan.FromMilliseconds(500))
                            doubleAnimation.BeginTime = beginTime
                            sineEase = SineEase()

                            sineEase.EasingMode = EasingMode.EaseIn
                            doubleAnimation.EasingFunction = sineEase

                            storyboard.Children.Add(doubleAnimation)

                            Storyboard.SetTarget(doubleAnimation, element)
                            Storyboard.SetTargetProperty(
                                doubleAnimation,
                                PropertyPath(UIElement.OpacityProperty))

                contentControl.BeginStoryboard(
                    storyboard, HandoffBehavior.SnapshotAndReplace, True)
                closeTimer.Tag = False

            tickTimer.Tick += onTick
            tickTimer.Interval = TimeSpan.FromMilliseconds(100)

            closeTimer.Tick += onClose
            closeTimer.Interval = TimeSpan.FromSeconds(3)
            closeTimer.Tag = True

            window.Owner = Application.Current.MainWindow
            window.Title = Application.Current.MainWindow.Title
            window.WindowStartupLocation = WindowStartupLocation.CenterScreen
            window.AllowsTransparency = True
            window.WindowStyle = WindowStyle.None
            window.ResizeMode = ResizeMode.NoResize
            window.ShowActivated = False
            window.ShowInTaskbar = Application.Current.MainWindow.ContextMenu.Items[
                5].IsChecked
            window.Topmost = True
            window.SizeToContent = SizeToContent.WidthAndHeight
            window.Background = Brushes.Transparent
            window.Loaded += onLoaded
            window.MouseEnter += onWindowMouseEnter
            window.MouseLeave += onWindowMouseLeave

            contentControl.UseLayoutRounding = True
            contentControl.HorizontalAlignment = HorizontalAlignment.Stretch
            contentControl.VerticalAlignment = VerticalAlignment.Stretch

            window.Content = contentControl

            grid1.HorizontalAlignment = HorizontalAlignment.Center
            grid1.VerticalAlignment = VerticalAlignment.Center
            grid1.Background = Brushes.Transparent
            grid1.Tag = False

            contentControl.Content = grid1

            bitmapImageList1 = List[BitmapImage]()
            bitmapImageList2 = List[BitmapImage]()
            width = 0
            height = 0

            for stream in task.Result.Key:
                try:
                    bitmapImage = BitmapImage()
                    bitmapImage.BeginInit()
                    bitmapImage.StreamSource = stream
                    bitmapImage.CacheOption = BitmapCacheOption.OnLoad
                    bitmapImage.CreateOptions = BitmapCreateOptions.None
                    bitmapImage.EndInit()

                    width += bitmapImage.PixelWidth

                    if bitmapImage.PixelHeight > height:
                        height = bitmapImage.PixelHeight

                    bitmapImageList1.Add(bitmapImage)

                finally:
                    stream.Close()

            for stream in task.Result.Value:
                try:
                    bitmapImage = BitmapImage()
                    bitmapImage.BeginInit()
                    bitmapImage.StreamSource = stream
                    bitmapImage.CacheOption = BitmapCacheOption.OnLoad
                    bitmapImage.CreateOptions = BitmapCreateOptions.None
                    bitmapImage.EndInit()

                    bitmapImageList2.Add(bitmapImage)

                finally:
                    stream.Close()

            x = 0
            kvpList = List[KeyValuePair[Point, BitmapImage]]()

            for bitmapImage in bitmapImageList1:
                rect = Rect(x, (height - bitmapImage.PixelHeight) / 2,
                            bitmapImage.PixelWidth, bitmapImage.PixelHeight)

                rectList.Add(rect)
                kvpList.Add(KeyValuePair[Point, BitmapImage](rect.Location,
                                                             bitmapImage))

                x += bitmapImage.PixelWidth

            rowDefinition1 = RowDefinition()
            rowDefinition1.Height = GridLength(1, GridUnitType.Auto)

            grid1.RowDefinitions.Add(rowDefinition1)

            for i in range(digits.Length):
                columnDefinition = ColumnDefinition()
                columnDefinition.Width = GridLength(1, GridUnitType.Star)

                grid1.ColumnDefinitions.Add(columnDefinition)

                border = Border()
                border.HorizontalAlignment = HorizontalAlignment.Stretch
                border.VerticalAlignment = VerticalAlignment.Stretch
                border.Margin = Thickness(4)
                border.BorderBrush = Brushes.Black
                border.BorderThickness = Thickness(1)
                border.Padding = Thickness(0)
                border.Width = 160
                border.Height = 480
                border.Background = Brushes.White
                border.Opacity = 0

                grid1.Children.Add(border)

                Grid.SetColumn(border, i)
                Grid.SetRow(border, 0)

                grid2 = Grid()
                grid2.HorizontalAlignment = HorizontalAlignment.Stretch
                grid2.VerticalAlignment = VerticalAlignment.Stretch
                grid2.Background = Brushes.Transparent
                grid2.ClipToBounds = True

                border.Child = grid2

                grid3 = Grid()
                grid3.HorizontalAlignment = HorizontalAlignment.Left
                grid3.VerticalAlignment = VerticalAlignment.Top
                grid3.Width = 160
                grid3.Height = 480
                grid3.Background = Brushes.Transparent

                grid2.Children.Add(grid3)

                canvas = Canvas()
                canvas.HorizontalAlignment = HorizontalAlignment.Left
                canvas.VerticalAlignment = VerticalAlignment.Top
                canvas.Width = width
                canvas.Height = maxHeight
                canvas.Background = Brushes.Transparent

                grid3.Children.Add(canvas)

                for kvp in kvpList:
                    image = Image()
                    image.HorizontalAlignment = HorizontalAlignment.Left
                    image.VerticalAlignment = VerticalAlignment.Top
                    image.Source = kvp.Value
                    image.Width = kvp.Value.PixelWidth
                    image.Height = kvp.Value.PixelHeight
                    image.Stretch = Stretch.Fill

                    canvas.Children.Add(image)

                    Canvas.SetLeft(image, kvp.Key.X)
                    Canvas.SetTop(image, kvp.Key.Y)

            column = 1

            rowDefinition2 = RowDefinition()
            rowDefinition2.Height = GridLength(1, GridUnitType.Auto)

            grid1.RowDefinitions.Add(rowDefinition2)

            for bitmapImage in bitmapImageList2:
                image = Image()
                image.HorizontalAlignment = HorizontalAlignment.Right
                image.VerticalAlignment = VerticalAlignment.Top
                image.Margin = Thickness(0, 0, 8, 0)
                image.Source = bitmapImage
                image.Width = bitmapImage.PixelWidth / 2
                image.Height = bitmapImage.PixelHeight / 2
                image.Stretch = Stretch.Fill

                grid1.Children.Add(image)

                Grid.SetColumn(image, column)
                Grid.SetRow(image, 1)

                column += 2

            window.Show()
예제 #15
0
 def __init__(self, ip_address, adminpassword = ""):
     self.ip_address = ip_address
     self.port = 9222
     self.omni_service = OmniTesterClient(ip_address, TimeSpan.FromSeconds(30))
     OmniUI.connected = False