Ejemplo n.º 1
0
        def evaluate_js(self, script):
            def callback(result):
                self.js_result = None if result is None or result == '' else json.loads(
                    result)
                self.js_result_semaphore.release()

            self.syncContextTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext(
            )
            try:
                result = self.web_view.ExecuteScriptAsync(script).ContinueWith(
                    Action[Task[String]](
                        lambda task: callback(json.loads(task.Result))),
                    #CancellationToken.None,
                    #TaskContinuationOptions.OnlyOnCanceled,
                    self.syncContextTaskScheduler)
            except Exception as e:
                logger.exception('Error occurred in script')
                result = None
                self.js_result = None if result is None or result == '' else json.loads(
                    result)
                self.js_result_semaphore.release()
Ejemplo n.º 2
0
    def evaluate_js(self, script, id, callback=None):
        def _callback(result):
            if callback is None:
                self.js_results[id] = None if result is None or result == '' else json.loads(result)
                self.js_result_semaphore.release()
            else:
                # future js callback option to handle async js method
                callback(result)
                self.js_results[id] = None
                self.js_result_semaphore.release()

        self.syncContextTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext()
        try:
            result = self.web_view.ExecuteScriptAsync(script).ContinueWith(
            Action[Task[String]](
                lambda task: _callback(json.loads(task.Result))
            ),
            self.syncContextTaskScheduler)
        except Exception as e:
            logger.exception('Error occurred in script')
            self.js_results[id] = None
            self.js_result_semaphore.release()
Ejemplo n.º 3
0
        def onClick(source, args):
            global username, password

            if not String.IsNullOrEmpty(
                    usernameTextBox.Text) and not String.IsNullOrEmpty(
                        passwordBox.Password):
                username = usernameTextBox.Text
                password = passwordBox.Password

                def onSave():
                    try:
                        fs = None
                        sr = None
                        sw = None

                        try:
                            fs = FileStream(__file__, FileMode.Open,
                                            FileAccess.ReadWrite,
                                            FileShare.Read)
                            encoding = UTF8Encoding(False)
                            sr = StreamReader(fs, encoding, True)
                            lines = Regex.Replace(
                                Regex.Replace(
                                    sr.ReadToEnd(), "username\\s*=\\s*\"\"",
                                    String.Format("username = \"{0}\"",
                                                  username),
                                    RegexOptions.CultureInvariant),
                                "password\\s*=\\s*\"\"",
                                String.Format("password = \"{0}\"", password),
                                RegexOptions.CultureInvariant)
                            fs.SetLength(0)
                            sw = StreamWriter(fs, encoding)
                            sw.Write(lines)

                        finally:
                            if sw is not None:
                                sw.Close()

                            if sr is not None:
                                sr.Close()

                            if fs is not None:
                                fs.Close()

                    except Exception, e:
                        Trace.WriteLine(e.clsException.Message)
                        Trace.WriteLine(e.clsException.StackTrace)

                def onCompleted(task):
                    global menuItem

                    for window in Application.Current.Windows:
                        if window is Application.Current.MainWindow and window.ContextMenu is not None:
                            if window.ContextMenu.Items.Contains(menuItem):
                                window.ContextMenu.Items.Remove(menuItem)
                                window.ContextMenu.Opened -= onOpened

                                if window.ContextMenu.Items[10].GetType(
                                ).IsInstanceOfType(window.ContextMenu.Items[
                                        window.ContextMenu.Items.Count - 4]):
                                    window.ContextMenu.Items.RemoveAt(10)

                    menuItem = None

                Task.Factory.StartNew(
                    onSave, TaskCreationOptions.LongRunning).ContinueWith(
                        onCompleted,
                        TaskScheduler.FromCurrentSynchronizationContext())
Ejemplo n.º 4
0
                    if termList.Count > 0:
                        sequenceList = List[Sequence]()

                        for sequence in Script.Instance.Sequences:
                            if sequence.Name.Equals("Activate"):
                                sequenceList.Add(sequence)

                        if Script.Instance.TryEnqueue(
                                Script.Instance.Prepare(
                                    sequenceList, None, termList)):
                            break

    Task.Factory.StartNew(
        onUpdate, TaskCreationOptions.LongRunning).ContinueWith(
            onCompleted, TaskScheduler.FromCurrentSynchronizationContext())


def getTermList(dictionary, text):
    stringBuilder = StringBuilder(text)
    selectedTermList = List[String]()

    while stringBuilder.Length > 0:
        s1 = stringBuilder.ToString()
        selectedTerm1 = None

        if dictionary.ContainsKey(s1[0]):
            for term in dictionary[s1[0]]:
                if s1.StartsWith(term,
                                 StringComparison.Ordinal) and term.Length > (
                                     0 if selectedTerm1 is None else
Ejemplo n.º 5
0
					rectangle.Height = height
					rectangle.Fill = solidColorBrush
					rectangle.Opacity = 0
					rectangle.OpacityMask = imageBrush
					rectangle.Clip = RectangleGeometry(Rect(0, height / max * i, width, height / max))
					rectangle.RenderTransform = TranslateTransform(0, 0)
					rectangle.Tag = i
					
					g.Children.Add(rectangle)

			window.Show()

			idList.Clear()
			idList.AddRange(task.Result.Value.Value.Value.Key)
	
	Task.Factory.StartNew[KeyValuePair[List[String], KeyValuePair[Double, KeyValuePair[KeyValuePair[Double, Double], KeyValuePair[List[Double], List[MemoryStream]]]]]](onUpdate, TaskCreationOptions.LongRunning).ContinueWith(Action[Task[KeyValuePair[List[String], KeyValuePair[Double, KeyValuePair[KeyValuePair[Double, Double], KeyValuePair[List[Double], List[MemoryStream]]]]]]](onCompleted), TaskScheduler.FromCurrentSynchronizationContext())

	timer.Stop()
	timer.Interval = TimeSpan.FromMinutes(5)
	timer.Start()

def urlEncode(value):
	unreserved = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"
	sb = StringBuilder()
	bytes = Encoding.UTF8.GetBytes(value)

	for b in bytes:
		if b < 0x80 and unreserved.IndexOf(Convert.ToChar(b)) != -1:
			sb.Append(Convert.ToChar(b))
		else:
			sb.Append('%' + String.Format("{0:X2}", Convert.ToInt32(b)))
Ejemplo n.º 6
0
def onOpened(s, e):
	global menuItem, uriList

	menuItem.Items.Clear()

	if uriList.Count > 0:
		maxLength = 50
		stack = Stack[Uri](uriList)

		while stack.Count > 0:
			uri = stack.Pop()
			
			def onClick(sender, args):
				def onUpdate():
					shortenedUri = None

					if NetworkInterface.GetIsNetworkAvailable():
						try:
							request = WebRequest.Create(Uri(String.Concat("http://nazr.in/api/shorten.json?url=", urlEncode(uri.ToString()))))
							response = None
							stream = None
							streamReader = None

							try:
								response = request.GetResponse()
								stream = response.GetResponseStream()
								streamReader = StreamReader(stream)
								jsonDictionary = JsonDecoder.decode(streamReader.ReadToEnd())

								if jsonDictionary is not None and clr.GetClrType(Dictionary[String, Object]).IsInstanceOfType(jsonDictionary) and jsonDictionary.ContainsKey("url"):
									shortenedUri = Uri(jsonDictionary["url"])

							finally:
								if streamReader is not None:
									streamReader.Close()

								if stream is not None:
									stream.Close()
			
								if response is not None:
									response.Close()

						except Exception, e:
							Trace.WriteLine(e.clsException.Message)
							Trace.WriteLine(e.clsException.StackTrace)

					return shortenedUri

				def onCompleted(task):
					if task.Result is not None:
						Clipboard.SetDataObject(DataObject(DataFormats.UnicodeText, task.Result.ToString(), True))

				Task.Factory.StartNew[Uri](onUpdate, TaskCreationOptions.LongRunning).ContinueWith(Action[Task[Uri]](onCompleted), TaskScheduler.FromCurrentSynchronizationContext())

			header = uri.ToString()
			
			if header.Length > maxLength:
				header = String.Concat(header.Remove(maxLength, header.Length - maxLength), "...")

			mi = MenuItem()
			mi.Click += onClick
			mi.Header = header
			mi.Tag = uri

			menuItem.Items.Add(mi)
Ejemplo n.º 7
0
		keyList = List[Int32](processDictionary.Keys)

		for key in keyList:
			removable = True

			for kvp in processList:
				if key == kvp.Key:
					removable = False

			if removable:
				processDictionary.Remove(key)

		dateTime = nowDateTime

	Task.Factory.StartNew(onUpdate).ContinueWith(onCompleted, TaskScheduler.FromCurrentSynchronizationContext())

def getTermList(dictionary, text):
	stringBuilder = StringBuilder(text)
	selectedTermList = List[String]()

	while stringBuilder.Length > 0:
		s1 = stringBuilder.ToString()
		selectedTerm1 = None

		if dictionary.ContainsKey(s1[0]):
			for term in dictionary[s1[0]]:
				if s1.StartsWith(term, StringComparison.Ordinal) and term.Length > (0 if selectedTerm1 is None else selectedTerm1.Length):
					selectedTerm1 = term
		
		if String.IsNullOrEmpty(selectedTerm1):
Ejemplo n.º 8
0
def onStartup(sender, args):
    global httpListener

    if HttpListener.IsSupported:
        context = TaskScheduler.FromCurrentSynchronizationContext()

        def onCompleted(task):
            if task.Result is not None and task.Result.Count > 0:
                Script.Instance.Alert(task.Result)

                dictionary = Dictionary[Char, List[String]]()

                for word in Script.Instance.Words:
                    if word.Name.Length > 0:
                        if not dictionary.ContainsKey(word.Name[0]):
                            dictionary.Add(word.Name[0], List[String]())

                        dictionary[word.Name[0]].Add(word.Name)

                for entry in newEntryList:
                    termList = getTermList(dictionary, entry.Title)

                    if termList.Count > 0:
                        sequenceList = List[Sequence]()

                        for sequence in Script.Instance.Sequences:
                            if sequence.Name.Equals("Activate"):
                                sequenceList.Add(sequence)

                        if Script.Instance.TryEnqueue(
                                Script.Instance.Prepare(
                                    sequenceList, None, termList)):
                            break

        def onDispatch(task):
            global httpListener

            if task.Exception is None:
                httpListener.GetContextAsync().ContinueWith[List[Entry]](
                    Func[Task[HttpListenerContext], List[Entry]](onDispatch),
                    TaskContinuationOptions.LongRunning).ContinueWith(
                        Action[Task[List[Entry]]](onCompleted), context)

                try:
                    if task.Result.Request.HttpMethod.Equals(
                            WebRequestMethods.Http.Post
                    ) and task.Result.Request.Url.AbsolutePath.Equals(
                            "/alert"):
                        if task.Result.Request.ContentType.Equals(
                                "application/json"):
                            stream = None
                            streamReader = None

                            try:
                                stream = task.Result.Request.InputStream
                                streamReader = StreamReader(stream)
                                jsonArray = JsonDecoder.decode(
                                    streamReader.ReadToEnd())

                                if jsonArray is not None and clr.GetClrType(
                                        Array).IsInstanceOfType(jsonArray):
                                    entryList = List[Entry]()

                                    for obj in jsonArray:
                                        if clr.GetClrType(Dictionary[
                                                String,
                                                Object]).IsInstanceOfType(obj):
                                            entry = Entry()

                                            if obj.ContainsKey(
                                                    "resource"
                                            ) and clr.GetClrType(
                                                    String).IsInstanceOfType(
                                                        obj["resource"]):
                                                entry.Resource = Uri(
                                                    obj["resource"])

                                            if obj.ContainsKey(
                                                    "title"
                                            ) and clr.GetClrType(
                                                    String).IsInstanceOfType(
                                                        obj["title"]):
                                                entry.Title = obj["title"]

                                            if obj.ContainsKey(
                                                    "description"
                                            ) and clr.GetClrType(
                                                    String).IsInstanceOfType(
                                                        obj["description"]):
                                                entry.Description = obj[
                                                    "description"]

                                            if obj.ContainsKey(
                                                    "author"
                                            ) and clr.GetClrType(
                                                    String).IsInstanceOfType(
                                                        obj["author"]):
                                                entry.Author = obj["author"]

                                            if obj.ContainsKey(
                                                    "created"
                                            ) and clr.GetClrType(
                                                    String).IsInstanceOfType(
                                                        obj["created"]):
                                                entry.Created = DateTime.Parse(
                                                    obj["created"])

                                            if obj.ContainsKey(
                                                    "modified"
                                            ) and clr.GetClrType(
                                                    String).IsInstanceOfType(
                                                        obj["modified"]):
                                                entry.Modified = DateTime.Parse(
                                                    obj["modified"])

                                            if obj.ContainsKey(
                                                    "image"
                                            ) and clr.GetClrType(
                                                    String).IsInstanceOfType(
                                                        obj["image"]):
                                                entry.Image = Uri(obj["image"])

                                            if obj.ContainsKey(
                                                    "tags") and clr.GetClrType(
                                                        Array
                                                    ).IsInstanceOfType(
                                                        obj["tags"]):
                                                for o in obj["tags"]:
                                                    if clr.GetClrType(
                                                            String
                                                    ).IsInstanceOfType(o):
                                                        entry.Tags.Add(o)

                                            entryList.Add(entry)

                                        else:
                                            task.Result.Response.StatusCode = Convert.ToInt32(
                                                HttpStatusCode.BadRequest)

                                            return None

                                    return entryList

                                else:
                                    task.Result.Response.StatusCode = Convert.ToInt32(
                                        HttpStatusCode.BadRequest)

                            finally:
                                if streamReader is not None:
                                    streamReader.Close()

                                if stream is not None:
                                    stream.Close()

                        else:
                            task.Result.Response.StatusCode = Convert.ToInt32(
                                HttpStatusCode.UnsupportedMediaType)

                    else:
                        task.Result.Response.StatusCode = Convert.ToInt32(
                            HttpStatusCode.Forbidden)

                except Exception, e:
                    Trace.WriteLine(e.clsException.Message)
                    Trace.WriteLine(e.clsException.StackTrace)

                finally:
                    task.Result.Response.Close()
Ejemplo n.º 9
0
def onClick(s, e):
    currentDirectory = Directory.GetCurrentDirectory()

    openFileDialog = OpenFileDialog()
    openFileDialog.Multiselect = False

    if CultureInfo.CurrentCulture.Equals(CultureInfo.GetCultureInfo("ja-JP")):
        openFileDialog.Filter = "XMLファイル (*.xml)|*.xml"
    else:
        openFileDialog.Filter = "XML files (*.xml)|*.xml"

    if openFileDialog.ShowDialog() == True:
        fileName = openFileDialog.FileName
        warningList = List[String]()
        errorList = List[String]()

        context = TaskScheduler.FromCurrentSynchronizationContext()

        def onValidate():
            fs = None

            try:
                fs = FileStream(fileName, FileMode.Open, FileAccess.Read,
                                FileShare.Read)

                doc = XmlDocument()
                doc.Load(fs)

                if doc.DocumentElement.Name.Equals("script"):
                    for childNode1 in doc.DocumentElement.ChildNodes:
                        if childNode1.Name.Equals("character"):
                            hasName = False

                            for xmlAttribute in childNode1.Attributes:
                                if xmlAttribute.Name.Equals("name"):
                                    hasName = True

                            if not hasName:
                                if CultureInfo.CurrentCulture.Equals(
                                        CultureInfo.GetCultureInfo("ja-JP")):
                                    errorList.Add("characterタグにname属性がありません。")
                                else:
                                    errorList.Add(
                                        "Could not find name attribute in character tag."
                                    )

                            for childNode2 in childNode1.ChildNodes:
                                if childNode2.Name.Equals("sequence"):
                                    parseSequence(
                                        childNode2,
                                        Path.GetDirectoryName(fileName),
                                        warningList, errorList)

                else:
                    if CultureInfo.CurrentCulture.Equals(
                            CultureInfo.GetCultureInfo("ja-JP")):
                        errorList.Add("scriptタグがありません。")
                    else:
                        errorList.Add("Could not find script tag.")

            except Exception, e:
                errorList.Add(e.clsException.Message)

            finally:
Ejemplo n.º 10
0
def onMouseUp(sender, args):
    if args.ChangedButton == MouseButton.Middle and Keyboard.Modifiers == ModifierKeys.Alt == ModifierKeys.Alt or args.ChangedButton == MouseButton.Left and Keyboard.Modifiers == ModifierKeys.Alt:

        def onLoad():
            streamList1 = List[MemoryStream]()
            streamList2 = List[MemoryStream]()

            for i in range(10):
                ms = None
                fs = None

                try:
                    fs = FileStream(
                        String.Format("Assets\\Number-{0}.png",
                                      i.ToString(
                                          CultureInfo.InvariantCulture)),
                        FileMode.Open, FileAccess.Read, FileShare.Read)
                    ms = MemoryStream()
                    buffer = Array.CreateInstance(Byte, fs.Length)
                    bytesRead = fs.Read(buffer, 0, buffer.Length)

                    while bytesRead > 0:
                        ms.Write(buffer, 0, bytesRead)
                        bytesRead = fs.Read(buffer, 0, buffer.Length)

                    ms.Seek(0, SeekOrigin.Begin)

                    streamList1.Add(ms)

                except:
                    if ms is not None:
                        ms.Close()
                        ms = None

                finally:
                    if fs is not None:
                        fs.Close()

            for path in [
                    "Assets\\Hour.png", "Assets\\Minute.png",
                    "Assets\\Second.png"
            ]:
                ms = None
                fs = None

                try:
                    fs = FileStream(path, FileMode.Open, FileAccess.Read,
                                    FileShare.Read)
                    ms = MemoryStream()
                    buffer = Array.CreateInstance(Byte, fs.Length)
                    bytesRead = fs.Read(buffer, 0, buffer.Length)

                    while bytesRead > 0:
                        ms.Write(buffer, 0, bytesRead)
                        bytesRead = fs.Read(buffer, 0, buffer.Length)

                    ms.Seek(0, SeekOrigin.Begin)

                    streamList2.Add(ms)

                except:
                    if ms is not None:
                        ms.Close()
                        ms = None

                finally:
                    if fs is not None:
                        fs.Close()

            return KeyValuePair[List[MemoryStream],
                                List[MemoryStream]](streamList1, streamList2)

        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()

        Task.Factory.StartNew[KeyValuePair[
            List[MemoryStream], List[MemoryStream]]](
                onLoad, TaskCreationOptions.LongRunning).ContinueWith(
                    Action[Task[KeyValuePair[
                        List[MemoryStream], List[MemoryStream]]]](onCompleted),
                    TaskScheduler.FromCurrentSynchronizationContext())