module Basics exposing
  ( (==), (/=)
  , (<), (>), (<=), (>=), max, min, Order (..), compare
  , not, (&&), (||), xor
  , (+), (-), (*), (/), (^), (//), rem, (%), negate, abs, sqrt, clamp, logBase, e
  , pi, cos, sin, tan, acos, asin, atan, atan2
  , round, floor, ceiling, truncate, toFloat
  , degrees, radians, turns
  , toPolar, fromPolar
  , isNaN, isInfinite
  , toString, (++)
  , identity, always, (<|), (|>), (<<), (>>), flip, curry, uncurry, Never, never
  )

{-| Tons of useful functions that get imported by default.

# Equality
@docs (==), (/=)

# Comparison

These functions only work on `comparable` types. This includes numbers,
characters, strings, lists of comparable things, and tuples of comparable
things. Note that tuples with 7 or more elements are not comparable; why
are your tuples so big?

@docs (<), (>), (<=), (>=), max, min, Order, compare

# Booleans
@docs not, (&&), (||), xor

# Mathematics
@docs (+), (-), (*), (/), (^), (//), rem, (%), negate, abs, sqrt, clamp, logBase, e

# Trigonometry
@docs pi, cos, sin, tan, acos, asin, atan, atan2

# Number Conversions
@docs round, floor, ceiling, truncate, toFloat

# Angle Conversions
All angle conversions result in “standard Elm angles”
which happen to be radians.

@docs degrees, radians, turns

# Polar Coordinates
@docs toPolar, fromPolar

# Floating Point Checks
@docs isNaN, isInfinite

# Strings and Lists
@docs toString, (++)

# Higher-Order Helpers
@docs identity, always, (<|), (|>), (<<), (>>), flip, curry, uncurry, Never, never

-}

import Native.Basics
import Native.Utils

{-| Convert radians to standard Elm angles (radians). -}
radians : Float -> Float
radians t =
  t

{-| Convert degrees to standard Elm angles (radians). -}
degrees : Float -> Float
degrees =
  Native.Basics.degrees

{-| Convert turns to standard Elm angles (radians).
One turn is equal to 360°.
-}
turns : Float -> Float
turns =
  Native.Basics.turns

{-| Convert polar coordinates (r,θ) to Cartesian coordinates (x,y). -}
fromPolar : (Float,Float) -> (Float,Float)
fromPolar =
  Native.Basics.fromPolar

{-| Convert Cartesian coordinates (x,y) to polar coordinates (r,θ). -}
toPolar : (Float,Float) -> (Float,Float)
toPolar =
  Native.Basics.toPolar

{-|-}
(+) : number -> number -> number
(+) =
  Native.Basics.add

{-|-}
(-) : number -> number -> number
(-) =
  Native.Basics.sub

{-|-}
(*) : number -> number -> number
(*) =
  Native.Basics.mul

{-| Floating point division. -}
(/) : Float -> Float -> Float
(/) =
  Native.Basics.floatDiv

infixl 6 +
infixl 6 -
infixl 7 *
infixl 7 /
infixr 8 ^

infixl 7 //
infixl 7 %

{-| Integer division. The remainder is discarded. -}
(//) : Int -> Int -> Int
(//) =
  Native.Basics.div

{-| Find the remainder after dividing one number by another.

    rem 11 4 == 3
    rem 12 4 == 0
    rem 13 4 == 1
    rem -1 4 == -1
-}
rem : Int -> Int -> Int
rem =
  Native.Basics.rem

{-| Perform [modular arithmetic](http://en.wikipedia.org/wiki/Modular_arithmetic).

     7 % 2 == 1
    -1 % 4 == 3
-}
(%) : Int -> Int -> Int
(%) =
  Native.Basics.mod

{-| Exponentiation

    3^2 == 9
-}
(^) : number -> number -> number
(^) =
  Native.Basics.exp

{-|-}
cos : Float -> Float
cos =
  Native.Basics.cos

{-|-}
sin : Float -> Float
sin =
  Native.Basics.sin

{-|-}
tan : Float -> Float
tan =
  Native.Basics.tan

{-|-}
acos : Float -> Float
acos =
  Native.Basics.acos

{-|-}
asin : Float -> Float
asin =
  Native.Basics.asin

{-| You probably do not want to use this. It takes `(y/x)` as the
argument, so there is no way to know whether the negative signs comes from
the `y` or `x`. Thus, the resulting angle is always between π/2 and -π/2
(in quadrants I and IV). You probably want to use `atan2` instead.
-}
atan : Float -> Float
atan =
  Native.Basics.atan

{-| This helps you find the angle of a Cartesian coordinate.
You will almost certainly want to use this instead of `atan`.
So `atan2 y x` computes *atan(y/x)* but also keeps track of which
quadrant the angle should really be in. The result will be between
π and -π, giving you the full range of angles.
-}
atan2 : Float -> Float -> Float
atan2 =
  Native.Basics.atan2

{-| Take the square root of a number. -}
sqrt : Float -> Float
sqrt =
  Native.Basics.sqrt

{-| Negate a number.

    negate 42 == -42
    negate -42 == 42
    negate 0 == 0
-}
negate : number -> number
negate =
  Native.Basics.negate

{-| Take the absolute value of a number. -}
abs : number -> number
abs =
  Native.Basics.abs

{-| Calculate the logarithm of a number with a given base.

    logBase 10 100 == 2
    logBase 2 256 == 8
-}
logBase : Float -> Float -> Float
logBase =
  Native.Basics.logBase

{-| Clamps a number within a given range. With the expression
`clamp 100 200 x` the results are as follows:

    100     if x < 100
     x      if 100 <= x < 200
    200     if 200 <= x
-}
clamp : number -> number -> number -> number
clamp =
  Native.Basics.clamp

{-| An approximation of pi. -}
pi : Float
pi =
  Native.Basics.pi

{-| An approximation of e. -}
e : Float
e =
  Native.Basics.e

{-| Check if values are “the same”.

**Note:** Elm uses structural equality on tuples, records, and user-defined
union types. This means the values `(3, 4)` and `(3, 4)` are definitely equal.
This is not true in languages like JavaScript that use reference equality on
objects.

**Note:** Equality (in the Elm sense) is not possible for certain types. For
example, the functions `(\n -> n + 1)` and `(\n -> 1 + n)` are “the
same” but detecting this in general is [undecidable][]. In a future
release, the compiler will detect when `(==)` is used with problematic
types and provide a helpful error message. This will require quite serious
infrastructure work that makes sense to batch with another big project, so the
stopgap is to crash as quickly as possible. Problematic types include functions
and JavaScript values like `Json.Encode.Value` which could contain functions
if passed through a port.

[undecidable]: https://en.wikipedia.org/wiki/Undecidable_problem
-}
(==) : a -> a -> Bool
(==) =
  Native.Basics.eq

{-| Check if values are not “the same”.

So `(a /= b)` is the same as `(not (a == b))`.
-}
(/=) : a -> a -> Bool
(/=) =
  Native.Basics.neq

{-|-}
(<) : comparable -> comparable -> Bool
(<) =
  Native.Basics.lt

{-|-}
(>) : comparable -> comparable -> Bool
(>) =
  Native.Basics.gt

{-|-}
(<=) : comparable -> comparable -> Bool
(<=) =
  Native.Basics.le

{-|-}
(>=) : comparable -> comparable -> Bool
(>=) =
  Native.Basics.ge

infix 4 ==
infix 4 /=
infix 4 <
infix 4 >
infix 4 <=
infix 4 >=

{-| Compare any two comparable values. Comparable values include `String`, `Char`,
`Int`, `Float`, `Time`, or a list or tuple containing comparable values.
These are also the only values that work as `Dict` keys or `Set` members.
-}
compare : comparable -> comparable -> Order
compare =
  Native.Basics.compare

{-| Represents the relative ordering of two things.
The relations are less than, equal to, and greater than.
-}
type Order = LT | EQ | GT

{-| Find the smaller of two comparables. -}
min : comparable -> comparable -> comparable
min =
  Native.Basics.min

{-| Find the larger of two comparables. -}
max : comparable -> comparable -> comparable
max =
  Native.Basics.max

{-| The logical AND operator. `True` if both inputs are `True`.

**Note:** When used in the infix position, like `(left && right)`, the operator
short-circuits. This means if `left` is `False` we do not bother evaluating `right`
and just return `False` overall.
-}
(&&) : Bool -> Bool -> Bool
(&&) =
  Native.Basics.and

{-| The logical OR operator. `True` if one or both inputs are `True`.

**Note:** When used in the infix position, like `(left || right)`, the operator
short-circuits. This means if `left` is `True` we do not bother evaluating `right`
and just return `True` overall.
-}
(||) : Bool -> Bool -> Bool
(||) =
  Native.Basics.or

infixr 3 &&
infixr 2 ||

{-| The exclusive-or operator. `True` if exactly one input is `True`. -}
xor : Bool -> Bool -> Bool
xor =
  Native.Basics.xor

{-| Negate a boolean value.

    not True == False
    not False == True
-}
not : Bool -> Bool
not =
  Native.Basics.not

-- Conversions

{-| Round a number to the nearest integer. -}
round : Float -> Int
round =
  Native.Basics.round

{-| Truncate a number, rounding towards zero. -}
truncate : Float -> Int
truncate =
  Native.Basics.truncate

{-| Floor function, rounding down. -}
floor : Float -> Int
floor =
  Native.Basics.floor

{-| Ceiling function, rounding up. -}
ceiling : Float -> Int
ceiling =
  Native.Basics.ceiling

{-| Convert an integer into a float. -}
toFloat : Int -> Float
toFloat =
  Native.Basics.toFloat

{-| Determine whether a float is an undefined or unrepresentable number.
NaN stands for *not a number* and it is [a standardized part of floating point
numbers](http://en.wikipedia.org/wiki/NaN).

    isNaN (0/0)     == True
    isNaN (sqrt -1) == True
    isNaN (1/0)     == False  -- infinity is a number
    isNaN 1         == False
-}
isNaN : Float -> Bool
isNaN =
  Native.Basics.isNaN

{-| Determine whether a float is positive or negative infinity.

    isInfinite (0/0)     == False
    isInfinite (sqrt -1) == False
    isInfinite (1/0)     == True
    isInfinite 1         == False

Notice that NaN is not infinite! For float `n` to be finite implies that
`not (isInfinite n || isNaN n)` evaluates to `True`.
-}
isInfinite : Float -> Bool
isInfinite =
  Native.Basics.isInfinite

{-| Turn any kind of value into a string. When you view the resulting string
with `Text.fromString` it should look just like the value it came from.

    toString 42 == "42"
    toString [1,2] == "[1,2]"
    toString "he said, \"hi\"" == "\"he said, \\\"hi\\\"\""
-}
toString : a -> String
toString =
  Native.Utils.toString

{-| Put two appendable things together. This includes strings, lists, and text.

    "hello" ++ "world" == "helloworld"
    [1,1,2] ++ [3,5,8] == [1,1,2,3,5,8]
-}
(++) : appendable -> appendable -> appendable
(++) =
  Native.Utils.append

infixr 5 ++

-- Function Helpers

{-| Function composition, passing results along in the suggested direction. For
example, the following code checks if the square root of a number is odd:

    not << isEven << sqrt

You can think of this operator as equivalent to the following:

    (g << f)  ==  (\x -> g (f x))

So our example expands out to something like this:

    \n -> not (isEven (sqrt n))
-}
(<<) : (b -> c) -> (a -> b) -> (a -> c)
(<<) g f x =
  g (f x)

{-| Function composition, passing results along in the suggested direction. For
example, the following code checks if the square root of a number is odd:

    sqrt >> isEven >> not

This direction of function composition seems less pleasant than `(<<)` which
reads nicely in expressions like: `filter (not << isRegistered) students`
-}
(>>) : (a -> b) -> (b -> c) -> (a -> c)
(>>) f g x =
  g (f x)

{-| Forward function application `x |> f == f x`. This function is useful
for avoiding parentheses and writing code in a more natural way.
Consider the following code to create a pentagon:

    scale 2 (move (10,10) (filled blue (ngon 5 30)))

This can also be written as:

    ngon 5 30
      |> filled blue
      |> move (10,10)
      |> scale 2
-}
(|>) : a -> (a -> b) -> b
(|>) x f =
  f x

{-| Backward function application `f <| x == f x`. This function is useful for
avoiding parentheses. Consider the following code to create a text element:

    leftAligned (monospace (fromString "code"))

This can also be written as:

    leftAligned <| monospace <| fromString "code"
-}
(<|) : (a -> b) -> a -> b
(<|) f x =
  f x

infixr 9 <<
infixl 9 >>
infixr 0 <|
infixl 0 |>

{-| Given a value, returns exactly the same value. This is called
[the identity function](http://en.wikipedia.org/wiki/Identity_function).
-}
identity : a -> a
identity x =
  x

{-| Create a function that *always* returns the same value. Useful with
functions like `map`:

    List.map (always 0) [1,2,3,4,5] == [0,0,0,0,0]

    -- List.map (\_ -> 0) [1,2,3,4,5] == [0,0,0,0,0]
    -- always = (\x _ -> x)
-}
always : a -> b -> a
always a _ =
  a

{-| Flip the order of the first two arguments to a function. -}
flip : (a -> b -> c) -> (b -> a -> c)
flip f b a =
  f a b

{-| Change how arguments are passed to a function.
This splits paired arguments into two separate arguments.
-}
curry : ((a,b) -> c) -> a -> b -> c
curry f a b =
  f (a,b)

{-| Change how arguments are passed to a function.
This combines two arguments into a single pair.
-}
uncurry : (a -> b -> c) -> (a,b) -> c
uncurry f (a,b) =
  f a b

{-| A value that can never happen! For context:

  - The boolean type `Bool` has two values: `True` and `False`
  - The unit type `()` has one value: `()`
  - The never type `Never` has no values!

You may see it in the wild in `Html Never` which means this HTML will never
produce any messages. You would need to write an event handler like
`onClick ??? : Attribute Never` but how can we fill in the question marks?!
So there cannot be any event handlers on that HTML.

You may also see this used with tasks that never fail, like `Task Never ()`.

The `Never` type is useful for restricting *arguments* to a function. Maybe my
API can only accept HTML without event handlers, so I require `Html Never` and
users can give `Html msg` and everything will go fine. Generally speaking, you
do not want `Never` in your return types though.
-}
type Never = JustOneMore Never

{-| A function that can never be called. Seems extremely pointless, but it
*can* come in handy. Imagine you have some HTML that should never produce any
messages. And say you want to use it in some other HTML that *does* produce
messages. You could say:

    import Html exposing (..)

    embedHtml : Html Never -> Html msg
    embedHtml staticStuff =
      div []
        [ text "hello"
        , Html.map never staticStuff
        ]

So the `never` function is basically telling the type system, make sure no one
ever calls me!
-}
never : Never -> a
never (JustOneMore nvr) =
  never nvr


name = 'Eigen'
version = '3.2.3'

homepage = 'http://eigen.tuxfamily.org/index.php?title=Main_Page'
description = """Eigen is a C++ template library for linear algebra:
 matrices, vectors, numerical solvers, and related algorithms."""

toolchain = {'name': 'foss', 'version': '2015a'}

source_urls = [BITBUCKET_SOURCE]
sources = ['%(version)s.tar.bz2']

moduleclass = 'math'


/**
 * @author mrdoob / http://www.mrdoob.com
 *
 * Simple test shader
 */

var BasicShader = {

	uniforms: {},

	vertexShader: [

		"void main() {",

			"gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",

		"}"

	].join( "\n" ),

	fragmentShader: [

		"void main() {",

			"gl_FragColor = vec4( 1.0, 0.0, 0.0, 0.5 );",

		"}"

	].join( "\n" )

};

export { BasicShader };


-- jucit - Just compile it!

local function readRegistry(key, value, type)
   local type = type or 'REG_SZ'
   local sysroot = assert(os.getenv('SystemRoot'))
   for _, reg in ipairs{"\\syswow64\\reg.exe", "\\system32\\reg.exe"} do
      for k,v in assert(io.popen(sysroot..reg..' QUERY "'..key..'" /v "'..value..'" 2>nul')):lines() do
	 local data
	 string.gsub(
	    k, "%s+(%S+)%s+(%S+)%s+(.+)",
	    function(v,t,d) data = value==v and type==t and d or data end)
	 if data ~= nil then
	    return data
	 end
      end
   end
end

local sdks = {
   ddk71 = {
      'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\KitSetup\\configured-kits\\' ..
	 '{B4285279-1846-49B4-B8FD-B9EAF0FF17DA}\\{68656B6B-555E-5459-5E5D-6363635E5F61}',
      'setup-install-location'
   },
   sdk60A = {
      'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v6.0A',
      'InstallationFolder'
   },
   sdk70 = {
      'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v7.0',
      'InstallationFolder'
   },
   sdk70A = {
      'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v7.0A',
      'InstallationFolder'
   },
   sdk71 = {
      'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v7.1',
      'InstallationFolder'
   },
   sdk80 = {
      'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v8.0',
      'InstallationFolder'
   },
   xbox360 = {
      'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Xbox\\2.0\\SDK',
      'InstallPath'
   },
   webos = {
      'HKEY_LOCAL_MACHINE\\SOFTWARE\\HP webOS\\SDK',
      'InstallDir'
   },
   sourcery_gcc = {
      'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\'..
	 'Sourcery G++ Lite for ARM GNU/Linux',
      'InstallLocation'
   },
   cygwin = {
      'HKEY_LOCAL_MACHINE\\SOFTWARE\\Cygwin\\setup',
      'rootdir'
   },
   bbndk_10_04_beta = {
      'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\'..
	 'BlackBerry 10 Native SDK 10.0.4-beta',
      'InstallLocation'
   },
   bbndk_2_00 = {
      'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\'..
	 'BlackBerry Native SDK for Tablet OS 2.0.0',
      'InstallLocation'
   },
   bbndk_2_00 = {
      'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\'..
	 'BlackBerry Native SDK for Tablet OS 2.0.0',
      'InstallLocation'
   },
   bbndk_2_01 = {
      'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\'..
	 'BlackBerry Native SDK for Tablet OS 2.0.1',
      'InstallLocation'
   },
   bbndk_2_10_beta1 = {
      'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\'..
	 'BlackBerry Native SDK for Tablet OS 2.1.0-beta1',
      'InstallLocation'
   },
   msvc8 = {
      'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\8.0\\Setup\\VC',
      'ProductDir'
   },
   msvc9 = {
      'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\9.0\\Setup\\VC',
      'ProductDir'
   },
   msvc10 = {
      'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\10.0\\Setup\\VC',
      'ProductDir'
   },
   msvc11 = {
      'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\11.0\\Setup\\VC',
      'ProductDir'
   },
   dia8 = {
      'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\SxS\\DIA_SDK',
      '8.0'
   },
   dia9 = {
      'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\SxS\\DIA_SDK',
      '9.0'
   },
   dia10 = {
      'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\SxS\\DIA_SDK',
      '10.0'
   },
   dia11 = {
      'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\SxS\\DIA_SDK',
      '11.0'
   },
   wdk8 = {
      'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows Kits\\WDK',
      'WDKContentRoot'
   },
   nvidia_gpusdk_40 = {
      'HKEY_LOCAL_MACHINE\\SOFTWARE\\NVIDIA Corporation\\Installed Products\\'..
	 'NVIDIA GPU Computing SDK 4.0',
      'InstallDir',
   },
   nvidia_gpusdk_41 = {
      'HKEY_LOCAL_MACHINE\\SOFTWARE\\NVIDIA Corporation\\Installed Products\\'..
	 'NVIDIA GPU Computing SDK 4.1',
      'InstallDir',
   },
}

print()
for k,v in pairs(sdks) do
   print( k, readRegistry( v[1], v[2] ))
end


/*
Copyright 2014 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Package errors provides detailed error types for api field validation.
package errors


using System;
using NetOffice;
using NetOffice.Attributes;
namespace NetOffice.ExcelApi.Enums
{
	 /// <summary>
	 /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
	 /// </summary>
	 ///<remarks> MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff835313.aspx </remarks>
	[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
	[EntityType(EntityType.IsEnum)]
	public enum xlQueryType
	{
		 /// <summary>
		 /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
		 /// </summary>
		 /// <remarks>1</remarks>
		 [SupportByVersion("Excel", 9,10,11,12,14,15,16)]
		 xlODBCQuery = 1,

		 /// <summary>
		 /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
		 /// </summary>
		 /// <remarks>2</remarks>
		 [SupportByVersion("Excel", 9,10,11,12,14,15,16)]
		 xlDAORecordSet = 2,

		 /// <summary>
		 /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
		 /// </summary>
		 /// <remarks>4</remarks>
		 [SupportByVersion("Excel", 9,10,11,12,14,15,16)]
		 xlWebQuery = 4,

		 /// <summary>
		 /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
		 /// </summary>
		 /// <remarks>5</remarks>
		 [SupportByVersion("Excel", 9,10,11,12,14,15,16)]
		 xlOLEDBQuery = 5,

		 /// <summary>
		 /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
		 /// </summary>
		 /// <remarks>6</remarks>
		 [SupportByVersion("Excel", 9,10,11,12,14,15,16)]
		 xlTextImport = 6,

		 /// <summary>
		 /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
		 /// </summary>
		 /// <remarks>7</remarks>
		 [SupportByVersion("Excel", 9,10,11,12,14,15,16)]
		 xlADORecordset = 7
	}
}


 Improve this Doc

   View Source

$q

      - service in module ng

A promise/deferred implementation inspired by Kris Kowal's Q.

$q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
implementations, and the other which resembles ES6 promises to some degree.

$q constructor

The streamlined ES6 style promise is essentially just using $q as a constructor which takes a resolver
function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,
see MDN.

While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are
available yet.

It can be used like so:

// for the purpose of this example let's assume that variables `$q` and `okToGreet`
// are available in the current lexical scope (they could have been injected or passed in).

function asyncGreet(name) {
  // perform some asynchronous operation, resolve or reject the promise when appropriate.
  return $q(function(resolve, reject) {
    setTimeout(function() {
      if (okToGreet(name)) {
        resolve('Hello, ' + name + '!');
      } else {
        reject('Greeting ' + name + ' is not allowed.');
      }
    }, 1000);
  });
}

var promise = asyncGreet('Robin Hood');
promise.then(function(greeting) {
  alert('Success: ' + greeting);
}, function(reason) {
  alert('Failed: ' + reason);
});

Note: progress/notify callbacks are not currently supported via the ES6-style interface.

However, the more traditional CommonJS-style usage is still available, and documented below.

The CommonJS Promise proposal describes a promise as an
interface for interacting with an object that represents the result of an action that is
performed asynchronously, and may or may not be finished at any given point in time.

From the perspective of dealing with error handling, deferred and promise APIs are to
asynchronous programming what try, catch and throw keywords are to synchronous programming.

// for the purpose of this example let's assume that variables `$q` and `okToGreet`
// are available in the current lexical scope (they could have been injected or passed in).

function asyncGreet(name) {
  var deferred = $q.defer();

  setTimeout(function() {
    deferred.notify('About to greet ' + name + '.');

    if (okToGreet(name)) {
      deferred.resolve('Hello, ' + name + '!');
    } else {
      deferred.reject('Greeting ' + name + ' is not allowed.');
    }
  }, 1000);

  return deferred.promise;
}

var promise = asyncGreet('Robin Hood');
promise.then(function(greeting) {
  alert('Success: ' + greeting);
}, function(reason) {
  alert('Failed: ' + reason);
}, function(update) {
  alert('Got notification: ' + update);
});

At first it might not be obvious why this extra complexity is worth the trouble. The payoff
comes in the way of guarantees that promise and deferred APIs make, see
https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.

Additionally the promise api allows for composition that is very hard to do with the
traditional callback (CPS) approach.
For more on this please see the Q documentation especially the
section on serial or parallel joining of promises.

The Deferred API

A new instance of deferred is constructed by calling $q.defer().

The purpose of the deferred object is to expose the associated Promise instance as well as APIs
that can be used for signaling the successful or unsuccessful completion, as well as the status
of the task.

Methods

resolve(value) – resolves the derived promise with the value. If the value is a rejection
constructed via $q.reject, the promise will be rejected instead.

reject(reason) – rejects the derived promise with the reason. This is equivalent to
resolving it with a rejection constructed via $q.reject.

notify(value) - provides updates on the status of the promise's execution. This may be called
multiple times before the promise is either resolved or rejected.

Properties

promise – {Promise} – promise object associated with this deferred.

The Promise API

A new promise instance is created when a deferred instance is created and can be retrieved by
calling deferred.promise.

The purpose of the promise object is to allow for interested parties to get access to the result
of the deferred task when it completes.

Methods

then(successCallback, errorCallback, notifyCallback) – regardless of when the promise was or
will be resolved or rejected, then calls one of the success or error callbacks asynchronously
as soon as the result is available. The callbacks are called with a single argument: the result
or rejection reason. Additionally, the notify callback may be called zero or more times to
provide a progress indication, before the promise is resolved or rejected.

This method returns a new promise which is resolved or rejected via the return value of the
successCallback, errorCallback. It also notifies via the return value of the
notifyCallback method. The promise cannot be resolved or rejected from the notifyCallback
method.

catch(errorCallback) – shorthand for promise.then(null, errorCallback)

finally(callback) – allows you to observe either the fulfillment or rejection of a promise,
but to do so without modifying the final value. This is useful to release resources or do some
clean-up that needs to be done whether the promise was rejected or resolved. See the full
specification for
more information.

Because finally is a reserved word in JavaScript and reserved keywords are not supported as
property names by ES3, you'll need to invoke the method like promise['finally'](callback) to
make your code IE8 and Android 2.x compatible.

Chaining promises

Because calling the then method of a promise returns a new derived promise, it is easily
possible to create a chain of promises:

promiseB = promiseA.then(function(result) {
  return result + 1;
});

// promiseB will be resolved immediately after promiseA is resolved and its value
// will be the result of promiseA incremented by 1

It is possible to create chains of any length and since a promise can be resolved with another
promise (which will defer its resolution further), it is possible to pause/defer resolution of
the promises at any point in the chain. This makes it possible to implement powerful APIs like
$http's response interceptors.

Differences between Kris Kowal's Q and $q

 There are two main differences:

$q is integrated with the $rootScope.Scope Scope model observation
mechanism in angular, which means faster propagation of resolution or rejection into your
models and avoiding unnecessary browser repaints, which would result in flickering UI.

Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
all the important functionality needed for common async tasks.

Testing

it('should simulate promise', inject(function($q, $rootScope) {
  var deferred = $q.defer();
  var promise = deferred.promise;
  var resolvedValue;

  promise.then(function(value) { resolvedValue = value; });
  expect(resolvedValue).toBeUndefined();

  // Simulate resolving of promise
  deferred.resolve(123);
  // Note that the 'then' function does not get called synchronously.
  // This is because we want the promise API to always be async, whether or not
  // it got called synchronously or asynchronously.
  expect(resolvedValue).toBeUndefined();

  // Propagate promise resolution to 'then' functions using $apply().
  $rootScope.$apply();
  expect(resolvedValue).toEqual(123);
}));

Dependencies

$rootScope

Usage

$q(resolver);

Arguments

      Param
      Type
      Details

        resolver

        function(function, function)

Function which is responsible for resolving or
  rejecting the newly created promise. The first parameter is a function which resolves the
  promise, the second parameter is a function which rejects the promise.

Returns

    Promise

The newly created promise.

Methods

defer();

Creates a Deferred object which represents a task which will finish in the future.

Returns

    Deferred

Returns a new instance of deferred.

reject(reason);

Creates a promise that is resolved as rejected with the specified reason. This api should be
used to forward rejection in a chain of promises. If you are dealing with the last promise in
a promise chain, you don't need to worry about it.

When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
reject as the throw keyword in JavaScript. This also means that if you "catch" an error via
a promise error callback and you want to forward the error to the promise derived from the
current promise, you have to "rethrow" the error by returning a rejection constructed via
reject.

promiseB = promiseA.then(function(result) {
  // success: do something and resolve promiseB
  //          with the old or a new result
  return result;
}, function(reason) {
  // error: handle the error if possible and
  //        resolve promiseB with newPromiseOrValue,
  //        otherwise forward the rejection to promiseB
  if (canHandle(reason)) {
   // handle the error and recover
   return newPromiseOrValue;
  }
  return $q.reject(reason);
});

Parameters

      Param
      Type
      Details

        reason

        *

Constant, message, exception or an object representing the rejection reason.

Returns

    Promise

Returns a promise that was already resolved as rejected with the reason.

when(value);

Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
This is useful when you are dealing with an object that might or might not be a promise, or if
the promise comes from a source that can't be trusted.

Parameters

      Param
      Type
      Details

        value

        *

Value or a promise

Returns

    Promise

Returns a promise of the passed value or promise

all(promises);

Combines multiple promises into a single promise that is resolved when all of the input
promises are resolved.

Parameters

      Param
      Type
      Details

        promises

        Array.<Promise>Object.<Promise>

An array or hash of promises.

Returns

    Promise

Returns a single promise that will be resolved with an array/hash of values,
  each value corresponding to the promise at the same index/key in the promises array/hash.
  If any of the promises is resolved with a rejection, this resulting promise will be rejected
  with the same rejection value.


/*
    This file is part of Corrade.

    Copyright © 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016,
                2017, 2018, 2019, 2020 Vladimír Vondruš <mosra@centrum.cz>

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included
    in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    DEALINGS IN THE SOFTWARE.
*/

#include "Corrade/TestSuite/Tester.h"
#include "Corrade/TestSuite/Compare/Numeric.h"

namespace Corrade { namespace Test { namespace {

struct CppStandardTest: TestSuite::Tester {
    explicit CppStandardTest();

    void test();
};

CppStandardTest::CppStandardTest() {
    #ifdef COMPILING_AS_CPP11
    setTestName("Cpp11StandardTest");
    #elif defined(COMPILING_AS_CPP14)
    setTestName(TEST_NAME);
    #elif defined(COMPILING_AS_CPP17)
    setTestName("Cpp17StandardTest");
    #elif defined(COMPILING_AS_CPP2A)
    setTestName("Cpp2aStandardTest");
    #else
    #error no standard version macro passed from buildsystem
    #endif

    addTests({&CppStandardTest::test});
}

void CppStandardTest::test() {
    Debug{} << "Standard version using __cplusplus:" << __cplusplus;
    Debug{} << "Standard version using CORRADE_CXX_STANDARD:" << CORRADE_CXX_STANDARD;

    #ifdef COMPILING_AS_CPP11
    {
        #ifdef _MSC_VER
        CORRADE_EXPECT_FAIL("MSVC always compiles at least as C++14.");
        #endif
        CORRADE_COMPARE(CORRADE_CXX_STANDARD, 201103L);
    }
    #ifdef _MSC_VER
    CORRADE_COMPARE(CORRADE_CXX_STANDARD, 201402L);
    #endif
    #elif defined(COMPILING_AS_CPP14)
    CORRADE_COMPARE(CORRADE_CXX_STANDARD, 201402L);
    #elif defined(COMPILING_AS_CPP17)
    CORRADE_COMPARE(CORRADE_CXX_STANDARD, 201703L);
    #elif defined(COMPILING_AS_CPP2A)
    CORRADE_COMPARE_AS(CORRADE_CXX_STANDARD, 201703L,
        TestSuite::Compare::Greater);
    #else
    #error no standard version macro passed from the buildsystem
    #endif
}

}}}

CORRADE_TEST_MAIN(Corrade::Test::CppStandardTest)


/*
 * This file is part of the CitizenFX project - http://citizen.re/
 *
 * See LICENSE and MENTIONS in the root of the source tree for information
 * regarding licensing.
 */

#include "StdInc.h"
#include "CefOverlay.h"
#include "NUISchemeHandlerFactory.h"
#include <NUIClient.h>

#include <VFSManager.h>
#include <include/cef_parser.h>

#include "memdbgon.h"

static std::atomic<int> g_fileHandleCount;
static std::queue<std::function<void()>> g_deleteQueue;

static nui::TResourceLookupFn g_resourceLookupFunc;

extern const std::map<std::string, std::string, std::less<>> g_mimeTypeMap;

namespace nui
{
	void SetResourceLookupFunction(const nui::TResourceLookupFn& fn)
	{
		g_resourceLookupFunc = fn;
	}
}

class NUIResourceHandler : public CefResourceHandler
{
private:
	std::string mimeType_;

	bool dataManaged_;

	int read_;

	fwRefContainer<vfs::Device> device_;

	std::string filename_;

	uintptr_t file_;

	bool closed_;
public:
	NUIResourceHandler()
	{
		closed_ = false;
		file_ = -1;
	}

	virtual ~NUIResourceHandler()
	{
		if (file_ && file_ != -1 && !closed_)
		{
			device_->Close(file_);
		}

		g_fileHandleCount.fetch_sub(1);

		if (!g_deleteQueue.empty())
		{
			g_deleteQueue.front()();
			g_deleteQueue.pop();
		}
	}

	virtual bool ProcessRequest(CefRefPtr<CefRequest> request, CefRefPtr<CefCallback> callback)
	{
		std::string url = request->GetURL();
		std::wstring hostname;
		std::wstring path;

		CefURLParts parts;
		CefParseURL(url, parts);

		hostname = CefString(&parts.host);
		path = CefString(&parts.path);

		std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> converter;

		if (hostname == L"game" || hostname == L"nui-game-internal")
		{
			filename_ = "citizen:/";

			filename_ += converter.to_bytes(path).substr(1);
		}
		else
		{
			if (hostname.find(L"cfx-nui-") == 0)
			{
				hostname = hostname.substr(8);
			}

			if (g_resourceLookupFunc)
			{
				filename_ = g_resourceLookupFunc(ToNarrow(hostname));
			}
			else
			{
				filename_ = "resources:/";
				filename_ += converter.to_bytes(hostname) + "/";
			}

			filename_ += converter.to_bytes(path);
		}

		// remove # parts
		auto hash = filename_.find_first_of(L'#');

		if (hash != std::string::npos)
		{
			//filename_.resize(hash);
			filename_.erase(hash);
		}

		hash = filename_.find_first_of(L'?');

		if (hash != std::string::npos)
		{
			//filename_.resize(hash);
			filename_.erase(hash);
		}

		if (filename_.length() >= 256)
		{
			filename_ = filename_.substr(0, 255);
		}

		device_ = vfs::GetDevice(filename_);

		int count = g_fileHandleCount.fetch_add(1);

		auto handleOpen = [=] ()
		{
			if (device_.GetRef() && filename_.find("..") == std::string::npos)
			{
				file_ = device_->Open(filename_.c_str(), true);
			}

			// set mime type
			std::string ext = url.substr(url.rfind('.') + 1);

			mimeType_ = "text/html";

			auto it = g_mimeTypeMap.find(ext);

			if (it != g_mimeTypeMap.end())
			{
				mimeType_ = it->second;
			}

			callback->Continue();
		};

		if (count < 2)
		{
			handleOpen();
		}
		else
		{
			g_deleteQueue.push(handleOpen);
		}

		return true;
	}

	virtual void GetResponseHeaders(CefRefPtr<CefResponse> response, int64& response_length, CefString& redirectUrl)
	{
		response->SetMimeType(mimeType_);

		if (file_ == -1)
		{
			response->SetStatus(404);
		}
		else
		{
			response->SetStatus(200);
		}

		CefResponse::HeaderMap map;
		response->GetHeaderMap(map);

		if (mimeType_ == "text/html" || mimeType_ == "text/css" || mimeType_ == "application/javascript")
		{
			map.insert({ "content-type", mimeType_ + "; charset=utf-8" });
		}

		map.insert({ "cache-control", "no-cache, must-revalidate" });
		response->SetHeaderMap(map);

		if (file_ != -1)
		{
			response_length = device_->GetLength(file_);
		}
		else
		{
			response_length = 0;
		}
	}

	virtual void Cancel()
	{
		closed_ = true;

		if (file_ != -1)
		{
			device_->Close(file_);
		}
	}

	virtual bool ReadResponse(void* data_out, int bytes_to_read, int& bytes_read, CefRefPtr<CefCallback> callback)
	{
		if (file_ != -1)
		{
			bytes_read = device_->Read(file_, data_out, bytes_to_read);

			return (bytes_read > 0);
		}

		return false;
	}

	IMPLEMENT_REFCOUNTING(NUIResourceHandler);
};

class ForbiddenResourceHandler : public CefResourceHandler
{
public:
	IMPLEMENT_REFCOUNTING(ForbiddenResourceHandler);

	virtual bool ProcessRequest(CefRefPtr<CefRequest> request, CefRefPtr<CefCallback> callback) override
	{
		callback->Continue();
		return true;
	}

	virtual void GetResponseHeaders(CefRefPtr<CefResponse> response, int64& response_length, CefString& redirectUrl) override
	{
		response->SetStatus(403);
		response_length = 0;
	}

	virtual bool ReadResponse(void* data_out, int bytes_to_read, int& bytes_read, CefRefPtr<CefCallback> callback) override
	{
		bytes_read = 0;

		return true;
	}

	virtual void Cancel() override
	{
	}
};

void NUISchemeHandlerFactory::SetRequestBlacklist(const std::vector<std::regex>& requestBlacklist)
{
	m_requestBlacklist = requestBlacklist;
}

CefRefPtr<CefResourceHandler> NUISchemeHandlerFactory::Create(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, const CefString& scheme_name, CefRefPtr<CefRequest> request)
{
	if (scheme_name == "nui")
	{
		return new NUIResourceHandler();
	}
	else if (scheme_name == "https")
	{
		// parse the URL to get the hostname
		CefString url = request->GetURL();
		CefURLParts urlParts;

		if (CefParseURL(url, urlParts))
		{
			CefString hostString = &urlParts.host;

			if (hostString == "nui-game-internal")
			{
				return new NUIResourceHandler();
			}
			else if (hostString.ToString().find("cfx-nui-") == 0)
			{
				return new NUIResourceHandler();
			}
		}
	}
	else if (scheme_name == "ws" || scheme_name == "wss")
	{
		for (auto& reg : m_requestBlacklist)
		{
			std::string url = request->GetURL().ToString();

			if (std::regex_search(url, reg))
			{
				trace("Blocked a request for blacklisted URI %s\n", url);
				return new ForbiddenResourceHandler();
			}
		}

		return nullptr;
	}

	CefRefPtr<CefResourceHandler> outHandler;

	OnSchemeCreateRequest(scheme_name.ToString().c_str(), request, outHandler);

	return outHandler;
}

OVERLAY_DECL fwEvent<const char*, CefRefPtr<CefRequest>, CefRefPtr<CefResourceHandler>&> OnSchemeCreateRequest;

const std::map<std::string, std::string, std::less<>> g_mimeTypeMap = {
	{ "*3gpp", "audio/3gpp" },
	{ "*jpm", "video/jpm" },
	{ "*mp3", "audio/mp3" },
	{ "*rtf", "text/rtf" },
	{ "*wav", "audio/wave" },
	{ "*xml", "text/xml" },
	{ "3g2", "video/3gpp2" },
	{ "3gp", "video/3gpp" },
	{ "3gpp", "video/3gpp" },
	{ "ac", "application/pkix-attr-cert" },
	{ "adp", "audio/adpcm" },
	{ "ai", "application/postscript" },
	{ "apng", "image/apng" },
	{ "appcache", "text/cache-manifest" },
	{ "asc", "application/pgp-signature" },
	{ "atom", "application/atom+xml" },
	{ "atomcat", "application/atomcat+xml" },
	{ "atomsvc", "application/atomsvc+xml" },
	{ "au", "audio/basic" },
	{ "aw", "application/applixware" },
	{ "bdoc", "application/bdoc" },
	{ "bin", "application/octet-stream" },
	{ "bmp", "image/bmp" },
	{ "bpk", "application/octet-stream" },
	{ "buffer", "application/octet-stream" },
	{ "ccxml", "application/ccxml+xml" },
	{ "cdmia", "application/cdmi-capability" },
	{ "cdmic", "application/cdmi-container" },
	{ "cdmid", "application/cdmi-domain" },
	{ "cdmio", "application/cdmi-object" },
	{ "cdmiq", "application/cdmi-queue" },
	{ "cer", "application/pkix-cert" },
	{ "cgm", "image/cgm" },
	{ "class", "application/java-vm" },
	{ "coffee", "text/coffeescript" },
	{ "conf", "text/plain" },
	{ "cpt", "application/mac-compactpro" },
	{ "crl", "application/pkix-crl" },
	{ "css", "text/css" },
	{ "csv", "text/csv" },
	{ "cu", "application/cu-seeme" },
	{ "davmount", "application/davmount+xml" },
	{ "dbk", "application/docbook+xml" },
	{ "deb", "application/octet-stream" },
	{ "def", "text/plain" },
	{ "deploy", "application/octet-stream" },
	{ "disposition-notification", "message/disposition-notification" },
	{ "dist", "application/octet-stream" },
	{ "distz", "application/octet-stream" },
	{ "dll", "application/octet-stream" },
	{ "dmg", "application/octet-stream" },
	{ "dms", "application/octet-stream" },
	{ "doc", "application/msword" },
	{ "dot", "application/msword" },
	{ "drle", "image/dicom-rle" },
	{ "dssc", "application/dssc+der" },
	{ "dtd", "application/xml-dtd" },
	{ "dump", "application/octet-stream" },
	{ "ear", "application/java-archive" },
	{ "ecma", "application/ecmascript" },
	{ "elc", "application/octet-stream" },
	{ "emf", "image/emf" },
	{ "eml", "message/rfc822" },
	{ "emma", "application/emma+xml" },
	{ "eps", "application/postscript" },
	{ "epub", "application/epub+zip" },
	{ "es", "application/ecmascript" },
	{ "exe", "application/octet-stream" },
	{ "exi", "application/exi" },
	{ "exr", "image/aces" },
	{ "ez", "application/andrew-inset" },
	{ "fits", "image/fits" },
	{ "g3", "image/g3fax" },
	{ "gbr", "application/rpki-ghostbusters" },
	{ "geojson", "application/geo+json" },
	{ "gif", "image/gif" },
	{ "glb", "model/gltf-binary" },
	{ "gltf", "model/gltf+json" },
	{ "gml", "application/gml+xml" },
	{ "gpx", "application/gpx+xml" },
	{ "gram", "application/srgs" },
	{ "grxml", "application/srgs+xml" },
	{ "gxf", "application/gxf" },
	{ "gz", "application/gzip" },
	{ "h261", "video/h261" },
	{ "h263", "video/h263" },
	{ "h264", "video/h264" },
	{ "heic", "image/heic" },
	{ "heics", "image/heic-sequence" },
	{ "heif", "image/heif" },
	{ "heifs", "image/heif-sequence" },
	{ "hjson", "application/hjson" },
	{ "hlp", "application/winhlp" },
	{ "hqx", "application/mac-binhex40" },
	{ "htm", "text/html" },
	{ "html", "text/html" },
	{ "ics", "text/calendar" },
	{ "ief", "image/ief" },
	{ "ifb", "text/calendar" },
	{ "iges", "model/iges" },
	{ "igs", "model/iges" },
	{ "img", "application/octet-stream" },
	{ "in", "text/plain" },
	{ "ini", "text/plain" },
	{ "ink", "application/inkml+xml" },
	{ "inkml", "application/inkml+xml" },
	{ "ipfix", "application/ipfix" },
	{ "iso", "application/octet-stream" },
	{ "jade", "text/jade" },
	{ "jar", "application/java-archive" },
	{ "jls", "image/jls" },
	{ "jp2", "image/jp2" },
	{ "jpe", "image/jpeg" },
	{ "jpeg", "image/jpeg" },
	{ "jpf", "image/jpx" },
	{ "jpg", "image/jpeg" },
	{ "jpg2", "image/jp2" },
	{ "jpgm", "video/jpm" },
	{ "jpgv", "video/jpeg" },
	{ "jpm", "image/jpm" },
	{ "jpx", "image/jpx" },
	{ "js", "application/javascript" },
	//{ "json", "application/json" },
	{ "json5", "application/json5" },
	{ "jsonld", "application/ld+json" },
	{ "jsonml", "application/jsonml+json" },
	{ "jsx", "text/jsx" },
	{ "kar", "audio/midi" },
	{ "ktx", "image/ktx" },
	{ "less", "text/less" },
	{ "list", "text/plain" },
	{ "litcoffee", "text/coffeescript" },
	{ "log", "text/plain" },
	{ "lostxml", "application/lost+xml" },
	{ "lrf", "application/octet-stream" },
	{ "m1v", "video/mpeg" },
	{ "m21", "application/mp21" },
	{ "m2a", "audio/mpeg" },
	{ "m2v", "video/mpeg" },
	{ "m3a", "audio/mpeg" },
	{ "m4a", "audio/mp4" },
	{ "m4p", "application/mp4" },
	{ "ma", "application/mathematica" },
	{ "mads", "application/mads+xml" },
	{ "man", "text/troff" },
	{ "manifest", "text/cache-manifest" },
	{ "map", "application/json" },
	{ "mar", "application/octet-stream" },
	{ "markdown", "text/markdown" },
	{ "mathml", "application/mathml+xml" },
	{ "mb", "application/mathematica" },
	{ "mbox", "application/mbox" },
	{ "md", "text/markdown" },
	{ "me", "text/troff" },
	{ "mesh", "model/mesh" },
	{ "meta4", "application/metalink4+xml" },
	{ "metalink", "application/metalink+xml" },
	{ "mets", "application/mets+xml" },
	{ "mft", "application/rpki-manifest" },
	{ "mid", "audio/midi" },
	{ "midi", "audio/midi" },
	{ "mime", "message/rfc822" },
	{ "mj2", "video/mj2" },
	{ "mjp2", "video/mj2" },
	{ "mjs", "application/javascript" },
	{ "mml", "text/mathml" },
	{ "mods", "application/mods+xml" },
	{ "mov", "video/quicktime" },
	{ "mp2", "audio/mpeg" },
	{ "mp21", "application/mp21" },
	{ "mp2a", "audio/mpeg" },
	{ "mp3", "audio/mpeg" },
	{ "mp4", "video/mp4" },
	{ "mp4a", "audio/mp4" },
	{ "mp4s", "application/mp4" },
	{ "mp4v", "video/mp4" },
	{ "mpd", "application/dash+xml" },
	{ "mpe", "video/mpeg" },
	{ "mpeg", "video/mpeg" },
	{ "mpg", "video/mpeg" },
	{ "mpg4", "video/mp4" },
	{ "mpga", "audio/mpeg" },
	{ "mrc", "application/marc" },
	{ "mrcx", "application/marcxml+xml" },
	{ "ms", "text/troff" },
	{ "mscml", "application/mediaservercontrol+xml" },
	{ "msh", "model/mesh" },
	{ "msi", "application/octet-stream" },
	{ "msm", "application/octet-stream" },
	{ "msp", "application/octet-stream" },
	{ "mxf", "application/mxf" },
	{ "mxml", "application/xv+xml" },
	{ "n3", "text/n3" },
	{ "nb", "application/mathematica" },
	{ "oda", "application/oda" },
	{ "oga", "audio/ogg" },
	{ "ogg", "audio/ogg" },
	{ "ogv", "video/ogg" },
	{ "ogx", "application/ogg" },
	{ "omdoc", "application/omdoc+xml" },
	{ "onepkg", "application/onenote" },
	{ "onetmp", "application/onenote" },
	{ "onetoc", "application/onenote" },
	{ "onetoc2", "application/onenote" },
	{ "opf", "application/oebps-package+xml" },
	{ "otf", "font/otf" },
	{ "owl", "application/rdf+xml" },
	{ "oxps", "application/oxps" },
	{ "p10", "application/pkcs10" },
	{ "p7c", "application/pkcs7-mime" },
	{ "p7m", "application/pkcs7-mime" },
	{ "p7s", "application/pkcs7-signature" },
	{ "p8", "application/pkcs8" },
	{ "pdf", "application/pdf" },
	{ "pfr", "application/font-tdpfr" },
	{ "pgp", "application/pgp-encrypted" },
	{ "pkg", "application/octet-stream" },
	{ "pki", "application/pkixcmp" },
	{ "pkipath", "application/pkix-pkipath" },
	{ "pls", "application/pls+xml" },
	{ "png", "image/png" },
	{ "prf", "application/pics-rules" },
	{ "ps", "application/postscript" },
	{ "pskcxml", "application/pskc+xml" },
	{ "qt", "video/quicktime" },
	{ "raml", "application/raml+yaml" },
	{ "rdf", "application/rdf+xml" },
	{ "rif", "application/reginfo+xml" },
	{ "rl", "application/resource-lists+xml" },
	{ "rld", "application/resource-lists-diff+xml" },
	{ "rmi", "audio/midi" },
	{ "rnc", "application/relax-ng-compact-syntax" },
	{ "rng", "application/xml" },
	{ "roa", "application/rpki-roa" },
	{ "roff", "text/troff" },
	{ "rq", "application/sparql-query" },
	{ "rs", "application/rls-services+xml" },
	{ "rsd", "application/rsd+xml" },
	{ "rss", "application/rss+xml" },
	{ "rtf", "application/rtf" },
	{ "rtx", "text/richtext" },
	{ "s3m", "audio/s3m" },
	{ "sbml", "application/sbml+xml" },
	{ "scq", "application/scvp-cv-request" },
	{ "scs", "application/scvp-cv-response" },
	{ "sdp", "application/sdp" },
	{ "ser", "application/java-serialized-object" },
	{ "setpay", "application/set-payment-initiation" },
	{ "setreg", "application/set-registration-initiation" },
	{ "sgi", "image/sgi" },
	{ "sgm", "text/sgml" },
	{ "sgml", "text/sgml" },
	{ "shex", "text/shex" },
	{ "shf", "application/shf+xml" },
	{ "shtml", "text/html" },
	{ "sig", "application/pgp-signature" },
	{ "sil", "audio/silk" },
	{ "silo", "model/mesh" },
	{ "slim", "text/slim" },
	{ "slm", "text/slim" },
	{ "smi", "application/smil+xml" },
	{ "smil", "application/smil+xml" },
	{ "snd", "audio/basic" },
	{ "so", "application/octet-stream" },
	{ "spp", "application/scvp-vp-response" },
	{ "spq", "application/scvp-vp-request" },
	{ "spx", "audio/ogg" },
	{ "sru", "application/sru+xml" },
	{ "srx", "application/sparql-results+xml" },
	{ "ssdl", "application/ssdl+xml" },
	{ "ssml", "application/ssml+xml" },
	{ "stk", "application/hyperstudio" },
	{ "styl", "text/stylus" },
	{ "stylus", "text/stylus" },
	{ "svg", "image/svg+xml" },
	{ "svgz", "image/svg+xml" },
	{ "t", "text/troff" },
	{ "t38", "image/t38" },
	{ "tei", "application/tei+xml" },
	{ "teicorpus", "application/tei+xml" },
	{ "text", "text/plain" },
	{ "tfi", "application/thraud+xml" },
	{ "tfx", "image/tiff-fx" },
	{ "tif", "image/tiff" },
	{ "tiff", "image/tiff" },
	{ "tr", "text/troff" },
	{ "ts", "video/mp2t" },
	{ "tsd", "application/timestamped-data" },
	{ "tsv", "text/tab-separated-values" },
	{ "ttc", "font/collection" },
	{ "ttf", "font/ttf" },
	{ "ttl", "text/turtle" },
	{ "txt", "text/plain" },
	{ "u8dsn", "message/global-delivery-status" },
	{ "u8hdr", "message/global-headers" },
	{ "u8mdn", "message/global-disposition-notification" },
	{ "u8msg", "message/global" },
	{ "uri", "text/uri-list" },
	{ "uris", "text/uri-list" },
	{ "urls", "text/uri-list" },
	{ "vcard", "text/vcard" },
	{ "vrml", "model/vrml" },
	{ "vtt", "text/vtt" },
	{ "vxml", "application/voicexml+xml" },
	{ "war", "application/java-archive" },
	{ "wasm", "application/wasm" },
	{ "wav", "audio/wav" },
	{ "weba", "audio/webm" },
	{ "webm", "video/webm" },
	{ "webmanifest", "application/manifest+json" },
	{ "webp", "image/webp" },
	{ "wgt", "application/widget" },
	{ "wmf", "image/wmf" },
	{ "woff", "font/woff" },
	{ "woff2", "font/woff2" },
	{ "wrl", "model/vrml" },
	{ "wsdl", "application/wsdl+xml" },
	{ "wspolicy", "application/wspolicy+xml" },
	{ "x3d", "model/x3d+xml" },
	{ "x3db", "model/x3d+binary" },
	{ "x3dbz", "model/x3d+binary" },
	{ "x3dv", "model/x3d+vrml" },
	{ "x3dvz", "model/x3d+vrml" },
	{ "x3dz", "model/x3d+xml" },
	{ "xaml", "application/xaml+xml" },
	{ "xdf", "application/xcap-diff+xml" },
	{ "xdssc", "application/dssc+xml" },
	{ "xenc", "application/xenc+xml" },
	{ "xer", "application/patch-ops-error+xml" },
	{ "xht", "application/xhtml+xml" },
	{ "xhtml", "application/xhtml+xml" },
	{ "xhvml", "application/xv+xml" },
	{ "xm", "audio/xm" },
	{ "xml", "application/xml" },
	{ "xop", "application/xop+xml" },
	{ "xpl", "application/xproc+xml" },
	{ "xsd", "application/xml" },
	{ "xsl", "application/xml" },
	{ "xslt", "application/xslt+xml" },
	{ "xspf", "application/xspf+xml" },
	{ "xvm", "application/xv+xml" },
	{ "xvml", "application/xv+xml" },
	{ "yaml", "text/yaml" },
	{ "yang", "application/yang" },
	{ "yin", "application/yin+xml" },
	{ "yml", "text/yaml" },
	{ "zip", "application/zip" },
};


# Copyright 2008, 2009, 2016 Free Software Foundation, Inc.
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-2.0-or-later
#

import sys
import textwrap
from distutils.spawn import find_executable

from gi.repository import Gtk, GLib

from . import Utils, Actions, Constants
from ..core import Messages

class SimpleTextDisplay(Gtk.TextView):
    """
    A non user-editable gtk text view.
    """

    def __init__(self, text=''):
        """
        TextDisplay constructor.

        Args:
            text: the text to display (string)
        """
        Gtk.TextView.__init__(self)
        self.set_text = self.get_buffer().set_text
        self.set_text(text)
        self.set_editable(False)
        self.set_cursor_visible(False)
        self.set_wrap_mode(Gtk.WrapMode.WORD_CHAR)

class TextDisplay(SimpleTextDisplay):
    """
    A non user-editable scrollable text view with popup menu.
    """

    def __init__(self, text=''):
        """
        TextDisplay constructor.

        Args:
            text: the text to display (string)
        """
        SimpleTextDisplay.__init__(self, text)
        self.scroll_lock = True
        self.connect("populate-popup", self.populate_popup)

    def insert(self, line):
        """
        Append text after handling backspaces and auto-scroll.

        Args:
            line: the text to append (string)
        """
        line = self._consume_backspaces(line)
        self.get_buffer().insert(self.get_buffer().get_end_iter(), line)
        self.scroll_to_end()

    def _consume_backspaces(self, line):
        """
        Removes text from the buffer if line starts with '\b'

        Args:
            line: a string which may contain backspaces

        Returns:
            The string that remains from 'line' with leading '\b's removed.
        """
        if not line:
            return

        # for each \b delete one char from the buffer
        back_count = 0
        start_iter = self.get_buffer().get_end_iter()
        while len(line) > back_count and line[back_count] == '\b':
            # stop at the beginning of a line
            if not start_iter.starts_line():
                start_iter.backward_char()
            back_count += 1
        # remove chars from buffer
        self.get_buffer().delete(start_iter, self.get_buffer().get_end_iter())
        return line[back_count:]

    def scroll_to_end(self):
        """ Update view's scroll position. """
        if self.scroll_lock:
            buf = self.get_buffer()
            mark = buf.get_insert()
            buf.move_mark(mark, buf.get_end_iter())
            self.scroll_mark_onscreen(mark)

    def clear(self):
        """ Clear all text from buffer. """
        buf = self.get_buffer()
        buf.delete(buf.get_start_iter(), buf.get_end_iter())

    def save(self, file_path):
        """
        Save context of buffer to the given file.

        Args:
            file_path: location to save buffer contents
        """
        with open(file_path, 'w') as logfile:
            buf = self.get_buffer()
            logfile.write(buf.get_text(buf.get_start_iter(),
                                       buf.get_end_iter(), True))

    # Action functions are set by the Application's init function
    def clear_cb(self, menu_item, web_view):
        """ Callback function to clear the text buffer """
        Actions.CLEAR_CONSOLE()

    def scroll_back_cb(self, menu_item, web_view):
        """ Callback function to toggle scroll lock """
        Actions.TOGGLE_SCROLL_LOCK()

    def save_cb(self, menu_item, web_view):
        """ Callback function to save the buffer """
        Actions.SAVE_CONSOLE()

    def populate_popup(self, view, menu):
        """Create a popup menu for the scroll lock and clear functions"""
        menu.append(Gtk.SeparatorMenuItem())

        lock = Gtk.CheckMenuItem(label = "Scroll Lock")
        menu.append(lock)
        lock.set_active(self.scroll_lock)
        lock.connect('activate', self.scroll_back_cb, view)

        save = Gtk.ImageMenuItem(label = "Save Console")
        menu.append(save)
        save.connect('activate', self.save_cb, view)

        clear = Gtk.ImageMenuItem(label = "Clear Console")
        menu.append(clear)
        clear.connect('activate', self.clear_cb, view)
        menu.show_all()
        return False

class MessageDialogWrapper(Gtk.MessageDialog):
    """ Run a message dialog. """

    def __init__(self, parent, message_type, buttons, title=None, markup=None,
                 default_response=None, extra_buttons=None):
        """
        Create a modal message dialog.

        Args:
            message_type: the type of message may be one of:
                            Gtk.MessageType.INFO
                            Gtk.MessageType.WARNING
                            Gtk.MessageType.QUESTION or Gtk.MessageType.ERROR
            buttons: the predefined set of buttons to use:
                            Gtk.ButtonsType.NONE
                            Gtk.ButtonsType.OK
                            Gtk.ButtonsType.CLOSE
                            Gtk.ButtonsType.CANCEL
                            Gtk.ButtonsType.YES_NO
                            Gtk.ButtonsType.OK_CANCEL
            title: the title of the window (string)
            markup: the message text with pango markup
            default_response: if set, determines which button is highlighted by default
            extra_buttons: a tuple containing pairs of values:
                            each value is the button's text and the button's return value

        """
        Gtk.MessageDialog.__init__(
            self, transient_for=parent, modal=True, destroy_with_parent=True,
            message_type=message_type, buttons=buttons
        )
        if title:
            self.set_title(title)
        if markup:
            self.set_markup(markup)
        if extra_buttons:
            self.add_buttons(*extra_buttons)
        if default_response:
            self.set_default_response(default_response)

    def run_and_destroy(self):
        response = self.run()
        self.hide()
        return response

class ErrorsDialog(Gtk.Dialog):
    """ Display flowgraph errors. """

    def __init__(self, parent, flowgraph):
        """Create a listview of errors"""
        Gtk.Dialog.__init__(
            self,
            title='Errors and Warnings',
            transient_for=parent,
            modal=True,
            destroy_with_parent=True,
        )
        self.add_buttons(Gtk.STOCK_OK, Gtk.ResponseType.ACCEPT)
        self.set_size_request(750, Constants.MIN_DIALOG_HEIGHT)
        self.set_border_width(10)

        self.store = Gtk.ListStore(str, str, str)
        self.update(flowgraph)

        self.treeview = Gtk.TreeView(model=self.store)
        for i, column_title in enumerate(["Block", "Aspect", "Message"]):
            renderer = Gtk.CellRendererText()
            column = Gtk.TreeViewColumn(column_title, renderer, text=i)
            column.set_sort_column_id(i)  # liststore id matches treeview id
            column.set_resizable(True)
            self.treeview.append_column(column)

        self.scrollable = Gtk.ScrolledWindow()
        self.scrollable.set_vexpand(True)
        self.scrollable.add(self.treeview)

        self.vbox.pack_start(self.scrollable, True, True, 0)
        self.show_all()

    def update(self, flowgraph):
        self.store.clear()
        for element, message in flowgraph.iter_error_messages():
            if element.is_block:
                src, aspect = element.name, ''
            elif element.is_connection:
                src = element.source_block.name
                aspect = "Connection to '{}'".format(element.sink_block.name)
            elif element.is_port:
                src = element.parent_block.name
                aspect = "{} '{}'".format('Sink' if element.is_sink else 'Source', element.name)
            elif element.is_param:
                src = element.parent_block.name
                aspect = "Param '{}'".format(element.name)
            else:
                src = aspect = ''
            self.store.append([src, aspect, message])

    def run_and_destroy(self):
        response = self.run()
        self.hide()
        return response

def show_about(parent, config):
    ad = Gtk.AboutDialog(transient_for=parent)
    ad.set_program_name(config.name)
    ad.set_name('')
    ad.set_license(config.license)

    py_version = sys.version.split()[0]
    ad.set_version("{} (Python {})".format(config.version, py_version))

    try:
        ad.set_logo(Gtk.IconTheme().load_icon('gnuradio-grc', 64, 0))
    except GLib.Error:
        Messages.send("Failed to set window logo\n")

    #ad.set_comments("")
    ad.set_copyright(config.license.splitlines()[0])
    ad.set_website(config.website)

    ad.connect("response", lambda action, param: action.hide())
    ad.show()

def show_help(parent):
    """ Display basic usage tips. """
    markup = textwrap.dedent("""\
        Usage Tips
        \n\
        Add block: drag and drop or double click a block in the block
       selection window.
        Rotate block: Select a block, press left/right on the keyboard.
        Change type: Select a block, press up/down on the keyboard.
        Edit parameters: double click on a block in the flow graph.
        Make connection: click on the source port of one block, then
       click on the sink port of another block.
        Remove connection: select the connection and press delete, or
       drag the connection.
        \n\
        *Press Ctrl+K or see menu for Keyboard - Shortcuts
        \
    """)
    markup = markup.replace("Ctrl", Utils.get_modifier_key())

    MessageDialogWrapper(
        parent, Gtk.MessageType.INFO, Gtk.ButtonsType.CLOSE, title='Help', markup=markup
    ).run_and_destroy()

def show_keyboard_shortcuts(parent):
    """ Display keyboard shortcut-keys. """
    markup = textwrap.dedent("""\
    Keyboard Shortcuts
    \n\
    Ctrl+N: Create a new flowgraph.
    Ctrl+O: Open an existing flowgraph.
    Ctrl+S: Save the current flowgraph or save as for new.
    Ctrl+W: Close the current flowgraph.
    Ctrl+Z: Undo a change to the flowgraph.
    Ctrl+Y: Redo a change to the flowgraph.
    Ctrl+A: Selects all blocks and connections.
    Ctrl+P: Screen Capture of the Flowgraph.
    Ctrl+Shift+P: Save the console output to file.
    Ctrl+L: Clear the console.
    Ctrl+E: Show variable editor.
    Ctrl+F: Search for a block by name.
    Ctrl+Q: Quit.
    F1    : Help menu.
    F5    : Generate the Flowgraph.
    F6    : Execute the Flowgraph.
    F7    : Kill the Flowgraph.
    Ctrl+Shift+S: Save as the current flowgraph.
    Ctrl+Shift+D: Create a duplicate of current flow graph.

    Ctrl+X/C/V: Edit-cut/copy/paste.
    Ctrl+D/B/R: Toggle visibility of disabled blocks or
            connections/block tree widget/console.
    Shift+T/M/B/L/C/R: Vertical Align Top/Middle/Bottom and
            Horizontal Align Left/Center/Right respectively of the
            selected block.
    \
    """)
    markup = markup.replace("Ctrl", Utils.get_modifier_key())

    MessageDialogWrapper(
        parent, Gtk.MessageType.INFO, Gtk.ButtonsType.CLOSE, title='Keyboard - Shortcuts', markup=markup
    ).run_and_destroy()

def show_get_involved(parent):
    """Get Involved Instructions"""
    markup = textwrap.dedent("""\
    <tt>Welcome to GNU Radio Community!</tt>
    \n\
    <tt>For more details on contributing to GNU Radio and getting engaged with our great community visit </tt>here.
    \n\
    <tt>You can also join our Slack Channel, IRC Channel (#gnuradio) or contact through our mailing list(discuss-gnuradio)</tt>.
    \
    """)

    MessageDialogWrapper(
        parent, Gtk.MessageType.QUESTION, Gtk.ButtonsType.CLOSE, title='Get - Involved', markup=markup
    ).run_and_destroy()

def show_types(parent):
    """ Display information about standard data types. """
    colors = [(name, color) for name, key, sizeof, color in Constants.CORE_TYPES]
    max_len = 10 + max(len(name) for name, code in colors)

    message = '\n'.join(
        '<tt>{name}</tt>'
        ''.format(color=color, name=Utils.encode(name).center(max_len))
        for name, color in colors
    )

    MessageDialogWrapper(
        parent, Gtk.MessageType.INFO, Gtk.ButtonsType.CLOSE, title='Types - Color Mapping', markup=message
    ).run_and_destroy()

def show_missing_xterm(parent, xterm):
    markup = textwrap.dedent("""\
        The xterm executable {0!r} is missing.
        You can change this setting in your gnuradio.conf, in section [grc], 'xterm_executable'.
        \n\
        (This message is shown only once)\
    """).format(xterm)

    MessageDialogWrapper(
        parent, message_type=Gtk.MessageType.WARNING, buttons=Gtk.ButtonsType.OK,
        title='Warning: missing xterm executable', markup=markup
    ).run_and_destroy()

def choose_editor(parent, config):
    """
    Give the option to either choose an editor or use the default.
    """
    if config.editor and find_executable(config.editor):
        return config.editor

    buttons = (
        'Choose Editor', Gtk.ResponseType.YES,
        'Use Default', Gtk.ResponseType.NO,
        Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL
    )
    response = MessageDialogWrapper(
        parent, message_type=Gtk.MessageType.QUESTION, buttons=Gtk.ButtonsType.NONE,
        title='Choose Editor', markup='Would you like to choose the editor to use?',
        default_response=Gtk.ResponseType.YES, extra_buttons=buttons
    ).run_and_destroy()

    # Handle the initial default/choose/cancel response
    # User wants to choose the editor to use
    editor = ''
    if response == Gtk.ResponseType.YES:
        file_dialog = Gtk.FileChooserDialog(
            'Select an Editor...', None,
            Gtk.FileChooserAction.OPEN,
            ('gtk-cancel', Gtk.ResponseType.CANCEL, 'gtk-open', Gtk.ResponseType.OK),
            transient_for=parent
        )
        file_dialog.set_select_multiple(False)
        file_dialog.set_local_only(True)
        file_dialog.set_current_folder('/usr/bin')
        try:
            if file_dialog.run() == Gtk.ResponseType.OK:
                editor = file_dialog.get_filename()
        finally:
            file_dialog.hide()

    # Go with the default editor
    elif response == Gtk.ResponseType.NO:
        try:
            process = None
            if sys.platform.startswith('linux'):
                process = find_executable('xdg-open')
            elif sys.platform.startswith('darwin'):
                process = find_executable('open')
            if process is None:
                raise ValueError("Can't find default editor executable")
            # Save
            editor = config.editor = process
        except Exception:
            Messages.send('>>> Unable to load the default editor. Please choose an editor.\n')

    if editor == '':
        Messages.send('>>> No editor selected.\n')
    return editor


#
# Check can login if existing corrupt authority present
#

[Seat:*]
autologin-user=corrupt-xauth
user-session=default

#?*START-DAEMON
#?RUNNER DAEMON-START

# X server starts
#?XSERVER-0 START VT=7 SEAT=seat0

# Daemon connects when X server is ready
#?*XSERVER-0 INDICATE-READY
#?XSERVER-0 INDICATE-READY
#?XSERVER-0 ACCEPT-CONNECT

# Session starts
#?SESSION-X-0 START XDG_SEAT=seat0 XDG_VTNR=7 XDG_GREETER_DATA_DIR=.*/corrupt-xauth XDG_SESSION_TYPE=x11 XDG_SESSION_DESKTOP=default USER=corrupt-xauth
#?LOGIN1 ACTIVATE-SESSION SESSION=c0
#?XSERVER-0 ACCEPT-CONNECT
#?SESSION-X-0 CONNECT-XSERVER

# Check where the X authority is
#?*SESSION-X-0 READ-ENV NAME=XAUTHORITY
#?SESSION-X-0 READ-ENV NAME=XAUTHORITY VALUE=.*/home/corrupt-xauth/.Xauthority

# Check has correct permissions
#?*SESSION-X-0 CHECK-X-AUTHORITY
#?SESSION-X-0 CHECK-X-AUTHORITY MODE=rw-------

# Cleanup
#?*STOP-DAEMON
#?SESSION-X-0 TERMINATE SIGNAL=15
#?XSERVER-0 TERMINATE SIGNAL=15
#?RUNNER DAEMON-EXIT STATUS=0


package org.web3j.abi.datatypes.generated;

import java.math.BigInteger;
import org.web3j.abi.datatypes.Int;

/**
 * Auto generated code.
 *
Do not modifiy!
 *
Please use org.web3j.codegen.AbiTypesGenerator in the
 * codegen module to update.
 */
public class Int104 extends Int {
    public static final Int104 DEFAULT = new Int104(BigInteger.ZERO);

    public Int104(BigInteger value) {
        super(104, value);
    }

    public Int104(long value) {
        this(BigInteger.valueOf(value));
    }
}


// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef PPAPI_CPP_PRIVATE_FLASH_DEVICE_ID_H_
#define PPAPI_CPP_PRIVATE_FLASH_DEVICE_ID_H_

#include "ppapi/cpp/completion_callback.h"
#include "ppapi/cpp/resource.h"

namespace pp {
namespace flash {

class DeviceID : public Resource {
 public:
  DeviceID();
  DeviceID(const InstanceHandle& instance);

  // On success, returns a string var.
  int32_t GetDeviceID(const CompletionCallbackWithOutput<Var>& callback);
};

}  // namespace flash
}  // namespace pp

#endif  // PPAPI_CPP_PRIVATE_FLASH_DEVICE_ID_H_


/*
Copyright The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Code generated by client-gen. DO NOT EDIT.

package fake

import (
	v1alpha1 "k8s.io/client-go/kubernetes/typed/discovery/v1alpha1"
	rest "k8s.io/client-go/rest"
	testing "k8s.io/client-go/testing"
)

type FakeDiscoveryV1alpha1 struct {
	*testing.Fake
}

func (c *FakeDiscoveryV1alpha1) EndpointSlices(namespace string) v1alpha1.EndpointSliceInterface {
	return &FakeEndpointSlices{c, namespace}
}

// RESTClient returns a RESTClient that is used to communicate
// with API server by this client implementation.
func (c *FakeDiscoveryV1alpha1) RESTClient() rest.Interface {
	var ret *rest.RESTClient
	return ret
}


<!DOCTYPE html>

  {% include head.html %}

    {% include header.html %}

        {{ content }}

    {% include footer.html %}


## 7amebox1 - Pwnable Challenge

The 7amebox challenge is built on a custom VM written in Python (with
meaningless function names). The VM uses 7 bit bytes and three byte words with
"middle endian" byte order, presumably a reference to cLEMENCy from DEFCON 24.

To start, we annotated the VM implementation to use decent names and to
add basic disassembly and debugging functionality. See the files in this
directory for our modifications.

Disassembling the program, we see a trivial stack buffer overflow with a
hardcoded canary of 0x12345:

```asm
main:
   9:  push bp
   b:  mov bp, sp
   d:  sub.t sp, #3c
  12:  mov r5, bp
  14:  sub.t r5, #3
  19:  mov r6, #12345
  1e:  st.t r6, [r5]
  20:  mov r0, #cd # "name>"
  25:  call writestr
  2a:  mov r1, #42
  2f:  mov r5, bp
  31:  sub.t r5, #3c
  36:  mov r0, r5
  38:  call read
  3d:  mov r0, #d3 "bye\n"
  42:  call writestr
  47:  mov r5, bp
  49:  sub.t r5, #3
  4e:  ld.t r6, [r5]
  50:  cmp.t r6, #12345
  55:  jne #5
  5a:  mov sp, bp
  5c:  pop bp
  5e:  ret
```

The VM has no memory protections. Even though it appears to have a
configuration option to NX (which was disabled on this challenge), the
permission check is wrong:

```python
def check_permission(self, addr, perm):
    if self.get_perm(addr) & (PERM_MAPPED | perm):
        return True
    else:
        return False
```

The exploit overwrites the return address to point into the stack buffer. Our
flag reading shellcode didn't quite fit, so we used a stager to read larger
shellcode to the bottom of the stack.

Unfortunately, the time we spent adding debugging functionality was a waste as
we did not have enough time to exploit the rather convoluted bug in the second
challenge using this VM.


/*
 * Copyright (C) 2006 Apple Inc. All rights reserved.
 * Copyright (C) 2006, 2008 Nikolas Zimmermann <zimmermann@kde.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_DOCUMENT_EXTENSIONS_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_DOCUMENT_EXTENSIONS_H_

#include "base/macros.h"
#include "third_party/blink/renderer/core/layout/svg/svg_resources_cache.h"
#include "third_party/blink/renderer/platform/geometry/float_point.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"

namespace blink {

class Document;
class SVGElement;
class SVGSVGElement;
class SubtreeLayoutScope;

class SVGDocumentExtensions final
    : public GarbageCollected<SVGDocumentExtensions> {
 public:
  explicit SVGDocumentExtensions(Document*);
  ~SVGDocumentExtensions();

  void AddTimeContainer(SVGSVGElement*);
  void RemoveTimeContainer(SVGSVGElement*);

  // Records the SVG element as having a Web Animation on an SVG attribute that
  // needs applying.
  void AddWebAnimationsPendingSVGElement(SVGElement&);

  static void ServiceOnAnimationFrame(Document&);

  void StartAnimations();
  void PauseAnimations();
  void ServiceAnimations();

  void DispatchSVGLoadEventToOutermostSVGElements();

  SVGResourcesCache& ResourcesCache() { return resources_cache_; }

  void AddSVGRootWithRelativeLengthDescendents(SVGSVGElement*);
  void RemoveSVGRootWithRelativeLengthDescendents(SVGSVGElement*);
  void InvalidateSVGRootsWithRelativeLengthDescendents(SubtreeLayoutScope*);

  bool ZoomAndPanEnabled() const;

  void StartPan(const FloatPoint& start);
  void UpdatePan(const FloatPoint& pos) const;

  static SVGSVGElement* rootElement(const Document&);
  SVGSVGElement* rootElement() const;

  void Trace(blink::Visitor*);

 private:
  Member<Document> document_;
  HeapHashSet<Member<SVGSVGElement>> time_containers_;
  using SVGElementSet = HeapHashSet<Member<SVGElement>>;
  SVGElementSet web_animations_pending_svg_elements_;
  SVGResourcesCache resources_cache_;
  // Root SVG elements with relative length descendants.
  HeapHashSet<Member<SVGSVGElement>> relative_length_svg_roots_;
  FloatPoint translate_;
#if DCHECK_IS_ON()
  bool in_relative_length_svg_roots_invalidation_ = false;
#endif
  DISALLOW_COPY_AND_ASSIGN(SVGDocumentExtensions);
};

}  // namespace blink

#endif


//
// @license
// Copyright (c) 2013-2019 Pynk Lynn, LLC
// This code may only be used under the MIT style license found at
// https://github.com/pynklynn/notific8/blob/master/LICENSE
//

@mixin notific8_atomic_theme($name, $color, $text-color: #454545) {
  notific8-notification.atomic.#{$name} {
    --action-button-hover-background-color: #{darken($color, 1%)};
    --background-color: #{lighten($color, 30%)};
    --header-background-color: #{lighten($color, 20%)};
    --header-border-bottom-color: #{lighten($color, 10%)};
    --border-color: #{$color};
    --text-color: #{$text-color};
  }
}

notific8-notification.atomic {
  --action-button-hover-background-color: darken(#999, 1%);
  --background-color: lighten(#999, 30%);
  --header-background-color: lighten(#999, 20%);
  --header-border-bottom-color: lighten(#999, 10%);
  --border-color: #999;
  --text-color: #fff;

  background-color: var(--background-color);
  border: solid 1px var(--border-color);
  border-radius: em(3px, 14px);
  color: var(--text-color);
  font-size: em(14px);
  min-height: em(70px, 14px);
  padding: 0;
  transition: all .15s ease-in-out;
  width: em(500px);

  .notific8-header {
    background-color: var(--header-background-color);
    border-bottom: solid 1px var(--header-border-bottom-color);
    padding: .75em;
  }

  &[image] {
    .notific8-image {
      left: em(5px, 14px);
      max-height: em(18px, 14px);
      max-width: em(18px, 14px);
      position: absolute;
      top: em(48px, 14px);
    }

    .notific8-message {
      margin-left: em(20px, 12px);
    }
  }

  .notific8-content {
    width: 100%;
  }

  .notific8-message {
    display: block;
    font-size: em(12px, 14px);
    padding: em(10.5px, 14px);
  }

  .notific8-close-button {
    background-color: transparent;
    border: none;
    font-size: em(20px, 14px);
    right: .5em;
    top: .325em;
  }

  notific8-action-buttons {
    justify-content: space-around;
    padding: em(8px);
  }

  .notific8-action-button {
    background-color: var(--background-color);
    border: none;
    border-radius: em(3px, 12px);
    flex-grow: 1;
    margin-left: em(5px, 12px);
    margin-right: em(5px, 12px);
    padding: em(5px, 12px);
    transition: background-color .15s ease-in-out;

    &:hover {
      background-color: var(--action-button-hover-background-color);
    }

    &:first-child {
      margin-left: 0;
    }

    &:last-child {
      margin-right: 0;
    }
  }
}

notific8-container[right] notific8-notification.atomic {
  margin-right: em(-516px);

  .notific8-header {
    border-top-right-radius: 3px;
  }

  &[open] {
    margin-right: .625em;
  }
}

notific8-container[left] notific8-notification.atomic {
  margin-left: em(-516px);

  &[open] {
    margin-left: .625em;
  }
}


// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Synced 2019-08-02T12:50:58.002998.

import 'package:flutter_web_test/flutter_web_test.dart';
import 'package:flutter_web/rendering.dart';
import 'package:flutter_web/widgets.dart';

class TestCustomPainter extends CustomPainter {
  TestCustomPainter({ this.log, this.name });

  final List<String> log;
  final String name;

  @override
  void paint(Canvas canvas, Size size) {
    log.add(name);
  }

  @override
  bool shouldRepaint(TestCustomPainter oldPainter) => true;
}

void main() {
  testWidgets('Control test for custom painting', (WidgetTester tester) async {
    final List<String> log = <String>[];
    await tester.pumpWidget(CustomPaint(
      painter: TestCustomPainter(
        log: log,
        name: 'background',
      ),
      foregroundPainter: TestCustomPainter(
        log: log,
        name: 'foreground',
      ),
      child: CustomPaint(
        painter: TestCustomPainter(
          log: log,
          name: 'child',
        ),
      ),
    ));

    expect(log, equals(<String>['background', 'child', 'foreground']));
  });

  testWidgets('CustomPaint sizing', (WidgetTester tester) async {
    final GlobalKey target = GlobalKey();

    await tester.pumpWidget(Center(
      child: CustomPaint(key: target),
    ));
    expect(target.currentContext.size, Size.zero);

    await tester.pumpWidget(Center(
      child: CustomPaint(key: target, child: Container()),
    ));
    expect(target.currentContext.size, const Size(800.0, 600.0));

    await tester.pumpWidget(Center(
      child: CustomPaint(key: target, size: const Size(20.0, 20.0)),
    ));
    expect(target.currentContext.size, const Size(20.0, 20.0));

    await tester.pumpWidget(Center(
      child: CustomPaint(key: target, size: const Size(2000.0, 100.0)),
    ));
    expect(target.currentContext.size, const Size(800.0, 100.0));

    await tester.pumpWidget(Center(
      child: CustomPaint(key: target, size: Size.zero, child: Container()),
    ));
    expect(target.currentContext.size, const Size(800.0, 600.0));

    await tester.pumpWidget(Center(
      child: CustomPaint(key: target, child: Container(height: 0.0, width: 0.0)),
    ));
    expect(target.currentContext.size, Size.zero);

  });

  testWidgets('Raster cache hints', (WidgetTester tester) async {
    final GlobalKey target = GlobalKey();

    final List<String> log = <String>[];
    await tester.pumpWidget(CustomPaint(
      key: target,
      isComplex: true,
      painter: TestCustomPainter(log: log),
    ));
    RenderCustomPaint renderCustom = target.currentContext.findRenderObject();
    expect(renderCustom.isComplex, true);
    expect(renderCustom.willChange, false);

    await tester.pumpWidget(CustomPaint(
      key: target,
      willChange: true,
      foregroundPainter: TestCustomPainter(log: log),
    ));
    renderCustom = target.currentContext.findRenderObject();
    expect(renderCustom.isComplex, false);
    expect(renderCustom.willChange, true);
  });
}


/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_patch_h__
#define INCLUDE_patch_h__

#include "git2/patch.h"
#include "array.h"

/* cached information about a hunk in a patch */
typedef struct git_patch_hunk {
	git_diff_hunk hunk;
	size_t line_start;
	size_t line_count;
} git_patch_hunk;

struct git_patch {
	git_refcount rc;

	git_repository *repo; /* may be null */

	git_diff_options diff_opts;

	git_diff_delta *delta;
	git_diff_binary binary;
	git_array_t(git_patch_hunk) hunks;
	git_array_t(git_diff_line) lines;

	size_t header_size;
	size_t content_size;
	size_t context_size;

	void (*free_fn)(git_patch *patch);
};

extern int git_patch__invoke_callbacks(
	git_patch *patch,
	git_diff_file_cb file_cb,
	git_diff_binary_cb binary_cb,
	git_diff_hunk_cb hunk_cb,
	git_diff_line_cb line_cb,
	void *payload);

extern int git_patch_line_stats(
	size_t *total_ctxt,
	size_t *total_adds,
	size_t *total_dels,
	const git_patch *patch);

/** Options for parsing patch files. */
typedef struct {
	/**
	 * The length of the prefix (in path segments) for the filenames.
	 * This prefix will be removed when looking for files.  The default is 1.
	 */
	uint32_t prefix_len;
} git_patch_options;

#define GIT_PATCH_OPTIONS_INIT { 1 }

extern void git_patch_free(git_patch *patch);

#endif


## important notice Thu Jul  5 13:20:44 PDT 2018
I do not use this desktop theme or i3 anymore and cannot provide support for newer users who want to try it.
If it works for you-- great. If you can't get it figured out, I'm sorry, but I will not be able to help you. Good luck!!!

![alt text](https://github.com/a-schaefers/i3-wm-gruvbox-theme/raw/master/screenshots/gruv-clean-grootify.png)
![alt text](https://github.com/a-schaefers/i3-wm-gruvbox-theme/blob/master/screenshots/gruv-dirty-opate.png) ![alt text](https://github.com/a-schaefers/i3-wm-gruvbox-theme/raw/master/screenshots/gruv-sadkitty-clean.png)
![alt text](https://github.com/a-schaefers/i3-wm-gruvbox-theme/blob/master/screenshots/gruv-prepper-clean.png)

I did it like this:

1. Install Vim gruvbox theme. I use the 'vim-plug' plugin manager and enable vim gruvbox theme along with 256 colors in vimrc. Source the gruvbox color sh script in
.bashrc or .zshrc since I use URxvt (see my "note-about-terminals"). I
installed lightline which will use the vim gruvbox theme if you set it in the
lightline vim settings. I also have font-awesome powerline-fonts installed along with Hack
and Fantasque Sans Mono fonts. I use Fantasque Sans Mono for the terminal and Hack
for almost everything else.

2. Apply gruvbox color scheme to .Xresources file.

3. Apply i3 config colors. The colors and are located at the end of my i3/config.

4. Install i3blocks. https://github.com/vivien/i3blocks These blocks will not all work the same out of the
   box for everyone. At the least you'll probably need to set your network
   interface because my ethernet and wifi interface will probably be different than yours. (my
   ethernet is 'eno1' and wifi is 'wlp2s0'.) If you don't know what yours is, try typing 'ip link' or 'ifconfig' in the terminal and check the output. If you have trouble with a particular block not displaying, try executing the script directly to see if you may be missing a package. (E.g. ./battery) Now if a 'command not found' error appears, then you need to find out what command was not found, and what package you may need to get that command. Google is your friend here. Lastly, a few of the i3blocks scripts use their own colors by default, overriding your personal preference. I disabled this and included my version of the scripts. The only thing was changed was that the scripts no longer override color settings.

5. I am using prezto's https://github.com/sorin-ionescu/prezto zsh config, it's more lightweight than others that are
   out there and by default looks great with gruvbox.

6. Rofi https://github.com/DaveDavenport/rofi comes with gruvbox theme included all that is necessary is to turn it
   on.

7. Conky. https://github.com/brndnmtthws/conky
It is the most ugly code I've seen since 1995. I do not guarantee it will look right for you,
   but it displays fine on my 1366x768 laptop screen. conkyrc is the
   clock/date. conkyrc2 is the process list / disk space and will need some tweaking
   if you do not use 3 partitions, one each for boot home and root.

8. Dunst notification theme is nothing fancy but I included it anyways.

9. Make a gruvbox gtk theme. I created a GTK theme to my preferences using oomox. https://github.com/actionless/oomox
I included pictures of my settings and there is also a config file in this
repo.

10. Apply the gtk theme and double check your fonts. I use lxappearance to set
the oomox gtk theme along with gtk font. I use 'Hack' font for GTK, i3, and conky.
For my terminal I use Fantasque Sans Mono because I feel like
it's pretty groovy.

Note: I provide links to a lot of the projects here, but it is generally best
to install them using a package manager from your distro.

And that is all.


/*=============================================================================
    Copyright (c) 2001-2011 Joel de Guzman

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#if !defined(FUSION_SEQUENCE_VIEW_ITERATOR_RANGE_10022005_0610)
#define FUSION_SEQUENCE_VIEW_ITERATOR_RANGE_10022005_0610

#include <boost/fusion/support/config.hpp>
#include <boost/fusion/view/iterator_range/iterator_range.hpp>

#endif


// +build linux,arm64

package remote

import "syscall"

// linux_arm64 doesn't have syscall.Dup2 which ginkgo uses, so
// use the nearly identical syscall.Dup3 instead
func syscallDup(oldfd int, newfd int) (err error) {
	return syscall.Dup3(oldfd, newfd, 0)
}


using System.Linq;
using NHibernate.Cfg.MappingSchema;
using NHibernate.Mapping.ByCode;
using NHibernate.Mapping.ByCode.Impl;
using NUnit.Framework;

namespace NHibernate.Test.MappingByCode.MappersTests
{
	[TestFixture]
	public class ElementMapperTest
	{
		[Test]
		public void WhenSetTypeByICompositeUserTypeThenSetTypeName()
		{
			var mapping = new HbmElement();
			var mapper = new ElementMapper(typeof(object), mapping);

			Assert.That(() => mapper.Type<MyCompoType>(), Throws.Nothing);
			Assert.That(mapping.Type.name, Does.Contain(nameof(MyCompoType)));
			Assert.That(mapping.type, Is.Null);
		}

		private class Element
		{
		}

		[Test]
		public void CanSetColumnsAndFormulas()
		{
			var mapping = new HbmElement();
			IElementMapper mapper = new ElementMapper(typeof(Element), mapping);
			mapper.ColumnsAndFormulas(x => x.Name("pizza"), x => x.Formula("risotto"), x => x.Name("pasta"));

			Assert.That(mapping.Items, Has.Length.EqualTo(3));
			Assert.That(mapping.Items[0], Is.TypeOf<HbmColumn>(), "first");
			Assert.That(mapping.Items[1], Is.TypeOf<HbmFormula>(), "second");
			Assert.That(mapping.Items[2], Is.TypeOf<HbmColumn>(), "third");
			Assert.That(((HbmColumn)mapping.Items[0]).name, Is.EqualTo("pizza"));
			Assert.That(((HbmFormula)mapping.Items[1]).Text, Has.Length.EqualTo(1).And.One.EqualTo("risotto"));
			Assert.That(((HbmColumn)mapping.Items[2]).name, Is.EqualTo("pasta"));
			Assert.That(mapping.column, Is.Null, "column");
			Assert.That(mapping.formula, Is.Null, "formula");
		}

		[Test]
		public void CanSetMultipleFormulas()
		{
			var mapping = new HbmElement();
			IElementMapper mapper = new ElementMapper(typeof(Element), mapping);
			mapper.Formulas("formula1", "formula2", "formula3");

			Assert.That(mapping.formula, Is.Null);
			Assert.That(mapping.Items, Has.Length.EqualTo(3));
			Assert.That(
				mapping.Items.Cast<HbmFormula>().Select(f => f.Text.Single()),
				Is.EquivalentTo(new[] { "formula1", "formula2", "formula3" }));
		}
	}
}


Ranz and Marshall "Evaporation from drops - Part II" Chemical Engineering Progress, 48(4):173-180 (1952)

&HEAD CHID='Ranz_Marshall_Table_3_3' /

&MESH IJK=4,4,4, XB=0,10,0,10,0,10/

&TIME T_END = 100.,DT=0.01/
&DUMP NFRAMES=500/

&MISC NOISE=F, TMPA = 85, P_INF = 98791.9, HUMIDITY= 0, STRATIFICATION=F, Y_CO2_INFTY=0. /

&RADI RADIATION=F /

&SPEC ID ='WATER VAPOR' /

&PART ID='water_drops', STATIC = .TRUE., SPEC_ID = 'WATER VAPOR', DIAMETER = 560., SAMPLING_FACTOR = 1, MONODISPERSE = .TRUE.,
      MINIMUM_DIAMETER = 5, MAXIMUM_DIAMETER = 2000, INITIAL_TEMPERATURE = 29.4 /

&INIT PART_ID = 'water_drops', XB = 5,5,5,5,5,5, N_PARTICLES= 1,UVW=0,0,-0.188, ID='droplet'/

&VENT MB='XMIN',SURF_ID='OPEN'/
&VENT MB='XMAX',SURF_ID='OPEN'/
&VENT MB='YMIN',SURF_ID='OPEN'/
&VENT MB='YMAX',SURF_ID='OPEN'/
&VENT MB='ZMIN',SURF_ID='OPEN'/
&VENT MB='ZMAX',SURF_ID='OPEN'/

&DEVC XYZ=5,5,5,QUANTITY='PARTICLE TEMPERATURE', INIT_ID='droplet', ID='T'/
&DEVC XYZ=5,5,5,QUANTITY='PARTICLE DIAMETER', INIT_ID='droplet', ID='Diameter',SETPOINT=350,TRIP_DIRECTION=-1/
&DEVC XYZ=5,5,5,QUANTITY='PARTICLE DIAMETER', INIT_ID='droplet', ID='Diameter_t',NO_UPDATE_DEVC_ID='Timer'/
&DEVC XYZ=5,5,5,QUANTITY='TIME',ID='Timer',SETPOINT=5/
&DEVC XYZ=5,5,5,QUANTITY='TIME',ID='Timer2',NO_UPDATE_DEVC_ID='Timer'/
&DEVC QUANTITY='CONTROL VALUE',CTRL_ID='dD2/dt CTRL',ID='dD2/dt',UNITS='m2/s',CONVERSION_FACTOR=1E-12/

&CTRL FUNCTION_TYPE='POWER',INPUT_ID='Diameter','CONSTANT',CONSTANT=2,ID='Dt2'/
&CTRL FUNCTION_TYPE='POWER',INPUT_ID='Diameter_t','CONSTANT',CONSTANT=2,ID='Dt_t2'/
&CTRL FUNCTION_TYPE='SUBTRACT',INPUT_ID='Dt_t2','Dt2',ID='numer'/
&CTRL FUNCTION_TYPE='SUBTRACT',INPUT_ID='Timer','Timer2',ID='denom_1'/
&CTRL FUNCTION_TYPE='SUM',INPUT_ID='denom_1','CONSTANT',CONSTANT=1E-6,ID='denom'/
&CTRL FUNCTION_TYPE='DIVIDE',INPUT_ID='numer','denom',ID='dD2/dt CTRL'/
&CTRL FUNCTION_TYPE='KILL',INPUT_ID='Diameter',ID='kill'/

&TAIL /


@using CoiniumServ.Persistance.Blocks
@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<CoiniumServ.Server.Web.Models.Pool.BlockModel>
@{ Layout = "layout/main.cshtml"; }

Block Details

                            Height
                            Status
                            Block Hash
                            Tx Hash
                            Amount
                            Paid
                            Date

                            @Model.Block.Height

                                @switch (@Model.Block.Status)
                                {
                                    case BlockStatus.Pending:

@Model.Block.Status

                                        break;
                                    case BlockStatus.Orphaned:

@Model.Block.Status

                                        break;
                                    case BlockStatus.Confirmed:

@Model.Block.Status

                                        break;
                                }

                            @Model.Block.BlockHash.Substring(0, 10)
                            @Model.Block.TransactionHash.Substring(0, 10)
                            @Model.Block.Amount

@(Model.Block.Accounted ? "Yes" : "No")

                            <time class="timeago" datetime="@Model.Block.CreatedAt.ToString("o")">@Model.Block.CreatedAt.ToString("o")</time>

Payment Details

                @if (Model.Payments.Count == 0)
                {

                        Waiting for block to get confirmed..

                }
                else
                {

                                Payment Id
                                Address
                                Amount
                                Fullfilled
                                Tx Id
                                Date

                            @foreach (var paymentDetails in @Model.Payments)
                            {

                                    @paymentDetails.PaymentId
                                    @paymentDetails.Address

                                        @if (paymentDetails.Completed)
                                        {
                                            @: @paymentDetails.Amount @paymentDetails.Currency
                                        }
                                        else
                                        {
                                            @: @paymentDetails.Amount @Model.Coin.Symbol
                                        }

@(paymentDetails.Completed ? "Yes" : "No")

                                        @if (paymentDetails.Completed)
                                        {
                                            @paymentDetails.TransactionId
                                        }
                                        else
                                        {
                                            @:-
                                        }

                                        <time class="timeago" datetime="@(paymentDetails.Completed ? paymentDetails.TransactionDate.ToString("yyyy-MM-ddTHH:mm:ssZ") : paymentDetails.PaymentDate.ToString("yyyy-MM-ddTHH:mm:ssZ"))">@(paymentDetails.Completed ? paymentDetails.TransactionDate.ToString("yyyy-MM-ddTHH:mm:ssZ") : paymentDetails.PaymentDate.ToString("yyyy-MM-ddTHH:mm:ssZ"))</time>

                            }

                }

         Prev
         Next