text:
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class EditarParamPosProc
    Inherits System.Windows.Forms.Form

    'Descartar substituições de formulário para limpar a lista de componentes.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Exigido pelo Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'OBSERVAÇÃO: o procedimento a seguir é exigido pelo Windows Form Designer
    'Pode ser modificado usando o Windows Form Designer.
    'Não o modifique usando o editor de códigos.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container()
        Me.Label2 = New System.Windows.Forms.Label()
        Me.Label4 = New System.Windows.Forms.Label()
        Me.Label5 = New System.Windows.Forms.Label()
        Me.cTipoExib = New System.Windows.Forms.ComboBox()
        Me.cEsqCores = New System.Windows.Forms.ComboBox()
        Me.lEsquema = New System.Windows.Forms.Label()
        Me.lPasso = New System.Windows.Forms.Label()
        Me.lUT = New System.Windows.Forms.Label()
        Me.bAceitar = New MeshExplorer.Controls.DarkButton()
        Me.tPasso = New Ignis.NumericUpDownEx()
        Me.Label1 = New System.Windows.Forms.Label()
        Me.cTamanho = New System.Windows.Forms.ComboBox()
        Me.ToolTip1 = New System.Windows.Forms.ToolTip(Me.components)
        CType(Me.tPasso, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.SuspendLayout()
        '
        'Label2
        '
        Me.Label2.Font = New System.Drawing.Font("Segoe UI", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label2.ForeColor = System.Drawing.Color.WhiteSmoke
        Me.Label2.Location = New System.Drawing.Point(12, 11)
        Me.Label2.Name = "Label2"
        Me.Label2.Size = New System.Drawing.Size(344, 17)
        Me.Label2.TabIndex = 35
        Me.Label2.Text = "Definição dos parâmetros de pós-processamento:"
        '
        'Label4
        '
        Me.Label4.Font = New System.Drawing.Font("Segoe UI", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label4.ForeColor = System.Drawing.Color.Silver
        Me.Label4.Location = New System.Drawing.Point(12, 28)
        Me.Label4.Name = "Label4"
        Me.Label4.Size = New System.Drawing.Size(344, 54)
        Me.Label4.TabIndex = 34
        Me.Label4.Text = "Nesta janela, definem-se as configurações de pós-processamento referentes à exibi" &
    "ção dos resultados da simulação em forma gráfica."
        '
        'Label5
        '
        Me.Label5.Font = New System.Drawing.Font("Segoe UI", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label5.ForeColor = System.Drawing.Color.WhiteSmoke
        Me.Label5.Location = New System.Drawing.Point(12, 93)
        Me.Label5.Name = "Label5"
        Me.Label5.Size = New System.Drawing.Size(178, 17)
        Me.Label5.TabIndex = 38
        Me.Label5.Text = "Tipo de visualização:"
        '
        'cTipoExib
        '
        Me.cTipoExib.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
        Me.cTipoExib.Font = New System.Drawing.Font("Segoe UI", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.cTipoExib.FormattingEnabled = True
        Me.cTipoExib.Items.AddRange(New Object() {"Gradiente de Temperaturas", "Linhas Isotérmicas"})
        Me.cTipoExib.Location = New System.Drawing.Point(15, 113)
        Me.cTipoExib.Name = "cTipoExib"
        Me.cTipoExib.Size = New System.Drawing.Size(175, 23)
        Me.cTipoExib.TabIndex = 39
        '
        'cEsqCores
        '
        Me.cEsqCores.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
        Me.cEsqCores.Font = New System.Drawing.Font("Segoe UI", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.cEsqCores.FormattingEnabled = True
        Me.cEsqCores.Items.AddRange(New Object() {"Colorido", "Escala de Cinza"})
        Me.cEsqCores.Location = New System.Drawing.Point(201, 113)
        Me.cEsqCores.Name = "cEsqCores"
        Me.cEsqCores.Size = New System.Drawing.Size(155, 23)
        Me.cEsqCores.TabIndex = 41
        '
        'lEsquema
        '
        Me.lEsquema.Font = New System.Drawing.Font("Segoe UI", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.lEsquema.ForeColor = System.Drawing.Color.WhiteSmoke
        Me.lEsquema.Location = New System.Drawing.Point(198, 93)
        Me.lEsquema.Name = "lEsquema"
        Me.lEsquema.Size = New System.Drawing.Size(158, 17)
        Me.lEsquema.TabIndex = 40
        Me.lEsquema.Text = "Esquema de cores:"
        '
        'lPasso
        '
        Me.lPasso.Font = New System.Drawing.Font("Segoe UI", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.lPasso.ForeColor = System.Drawing.Color.WhiteSmoke
        Me.lPasso.Location = New System.Drawing.Point(198, 93)
        Me.lPasso.Name = "lPasso"
        Me.lPasso.Size = New System.Drawing.Size(158, 17)
        Me.lPasso.TabIndex = 42
        Me.lPasso.Text = "Passo entre isotermas:"
        Me.lPasso.Visible = False
        '
        'lUT
        '
        Me.lUT.AutoSize = True
        Me.lUT.Font = New System.Drawing.Font("Segoe UI", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.lUT.ForeColor = System.Drawing.Color.Silver
        Me.lUT.Location = New System.Drawing.Point(303, 117)
        Me.lUT.Name = "lUT"
        Me.lUT.Size = New System.Drawing.Size(31, 15)
        Me.lUT.TabIndex = 44
        Me.lUT.Text = "U. T."
        Me.ToolTip1.SetToolTip(Me.lUT, "Unidades de Temperatura")
        Me.lUT.Visible = False
        '
        'bAceitar
        '
        Me.bAceitar.Font = New System.Drawing.Font("Segoe UI", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.bAceitar.Location = New System.Drawing.Point(15, 209)
        Me.bAceitar.Name = "bAceitar"
        Me.bAceitar.Size = New System.Drawing.Size(341, 27)
        Me.bAceitar.TabIndex = 45
        Me.bAceitar.Text = "Aceitar e Sair"
        Me.bAceitar.UseVisualStyleBackColor = True
        '
        'tPasso
        '
        Me.tPasso.Font = New System.Drawing.Font("Segoe UI", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.tPasso.InterceptMouseWheel = Ignis.NumericUpDownEx.InterceptMouseWheelMode.Never
        Me.tPasso.Location = New System.Drawing.Point(201, 113)
        Me.tPasso.Maximum = New Decimal(New Integer() {-1530494977, 232830, 0, 0})
        Me.tPasso.Minimum = New Decimal(New Integer() {1, 0, 0, 0})
        Me.tPasso.Name = "tPasso"
        Me.tPasso.ShowUpDownButtons = Ignis.NumericUpDownEx.ShowUpDownButtonsMode.Never
        Me.tPasso.Size = New System.Drawing.Size(97, 23)
        Me.tPasso.TabIndex = 43
        Me.tPasso.Value = New Decimal(New Integer() {1, 0, 0, 0})
        Me.tPasso.Visible = False
        '
        'Label1
        '
        Me.Label1.Font = New System.Drawing.Font("Segoe UI", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label1.ForeColor = System.Drawing.Color.WhiteSmoke
        Me.Label1.Location = New System.Drawing.Point(12, 148)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(344, 17)
        Me.Label1.TabIndex = 46
        Me.Label1.Text = "Tamanho da imagem, em pixels:"
        '
        'cTamanho
        '
        Me.cTamanho.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
        Me.cTamanho.Font = New System.Drawing.Font("Segoe UI", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.cTamanho.FormattingEnabled = True
        Me.cTamanho.Items.AddRange(New Object() {"500 x 500 (1x)", "1000 x 1000 (2x)", "1500 x 1500 (3x)", "2000 x 2000 (4x)"})
        Me.cTamanho.Location = New System.Drawing.Point(15, 168)
        Me.cTamanho.Name = "cTamanho"
        Me.cTamanho.Size = New System.Drawing.Size(175, 23)
        Me.cTamanho.TabIndex = 47
        '
        'EditarParamPosProc
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.BackColor = System.Drawing.Color.FromArgb(CType(CType(76, Byte), Integer), CType(CType(76, Byte), Integer), CType(CType(76, Byte), Integer))
        Me.ClientSize = New System.Drawing.Size(368, 248)
        Me.Controls.Add(Me.cTamanho)
        Me.Controls.Add(Me.Label1)
        Me.Controls.Add(Me.bAceitar)
        Me.Controls.Add(Me.lUT)
        Me.Controls.Add(Me.tPasso)
        Me.Controls.Add(Me.cEsqCores)
        Me.Controls.Add(Me.cTipoExib)
        Me.Controls.Add(Me.Label5)
        Me.Controls.Add(Me.Label2)
        Me.Controls.Add(Me.Label4)
        Me.Controls.Add(Me.lPasso)
        Me.Controls.Add(Me.lEsquema)
        Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog
        Me.MaximizeBox = False
        Me.MinimizeBox = False
        Me.Name = "EditarParamPosProc"
        Me.ShowInTaskbar = False
        Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent
        Me.Text = "Editar Parâmetros de Pós-Processamento"
        CType(Me.tPasso, System.ComponentModel.ISupportInitialize).EndInit()
        Me.ResumeLayout(False)
        Me.PerformLayout()

    End Sub

    Friend WithEvents Label2 As Label
    Friend WithEvents Label4 As Label
    Friend WithEvents Label5 As Label
    Friend WithEvents cTipoExib As ComboBox
    Friend WithEvents cEsqCores As ComboBox
    Friend WithEvents lEsquema As Label
    Friend WithEvents lPasso As Label
    Friend WithEvents tPasso As NumericUpDownEx
    Friend WithEvents lUT As Label
    Private WithEvents bAceitar As MeshExplorer.Controls.DarkButton
    Friend WithEvents Label1 As Label
    Friend WithEvents cTamanho As ComboBox
    Friend WithEvents ToolTip1 As ToolTip
End Class


text:
title:  Veivakadeitaki ni Veivakabulai
date:   25/04/2018
---

E so na Lotu Kavitu era se vakilakila tiko ga se ra sa vakabulai se sega. E dredre mera vakadeitaka na nodra i tutu ka ra diva tiko mera kila na vanua era na cava kina, e na vakasama ni bula tawamudu. Era cakacaka sara vakagumatua me rawa nira bau vinaka toka ia na kena dina na nodra kila vinaka tu nira lekata tiko ga na ka e gadrevi. Era rai ki loma vei ira ka lailai wale sara na ka me vakayaloqaqataki ira era kunea kina ena nodra i lakolako tiko ki lomalagi.

`Nida raica na maliwa vakaitamera e koto e na i tovo ne i Jisu kei na noda oi keda, se, ena noda wilika na i tukutuku me vaka na "ni sa qiqo na matamata ni koro, ka rabailailai na sala, sa basika ki na bula, a ra sa lewe lailai sa kunea" (Maciu 7:14), o cei beka vei keda e sega ni dau tiko na gauna me dau vakananuma kina se e na rawati lomalagi beka se sega?`

Meda vakarau tu ki na vakataotioti ni gauna, o ira na tamata e dodonu me sa vakadeitaki tu na nodra sa vakabulai ena gauna oqo me na rawarawa kina nira na sega ni rerevaka na gauna sa tiko mai liu. Ia, me vaka eda sa raica oti, ni oi na Lewetolu Vakalou e ratou qarava tolutolu tiko na cakacaka me rawa nida vakabulai. O koya e sa rawa gona kina, nida bula vata kei na kena vakadeitaki na noda sa vakabulai.

Wiliki ira na veitikina oqo. Na i nuinui kei na veivakadeitaki cava e rawa ni kunei mai vei ira me baleta na veivakabulai kei na veika e cakava na Kalou e na vukuda kei na veika e yalataka me na cakava?

`Same 91:15, 16`

`Joeli 2:31, 32`

`Joni 10:28`

`Roma 10:9–13`

`1 Joni 5:11–13`

Eda sa kacivi, ka vakaroti sara mada ga, meda bulataka na bula e vakatabui, ia na bula oqo me i vakaraitaki ni noda sa vakabulai e na vukui Karisito, ka sega ni mai ka meda na qai vakabulai kina.

redpajama_set_name: RedPajamaGithub


text:
Cloud Foundry
=============

.. todo:: Sprawdzić: https://brooklyn.apache.org/v/latest/ops/locations/

Cloud Foundry is an open platform as a service (PaaS) that provides a choice of clouds, developer frameworks, and application services. Cloud Foundry makes it faster and easier to build, test, deploy, and scale applications.

- https://www.infoq.com/presentations/pcf-cd
- https://www.infoq.com/presentations/devops-cloud-foundry
- https://www.infoq.com/presentations/trends-cloud-foundry

..  figure:: ../_img/cloud-foundry-architecture-01.png
    :scale: 50%
    :align: center

    Cloud Foundry Architecture

..  figure:: ../_img/cloud-foundry-architecture-02.png
    :scale: 50%
    :align: center

    Cloud Foundry Architecture

Technology
----------
=================  =================================================
Name               Description
=================  =================================================
cf                 Cloud Foundry is an open platform as a service (PaaS)
cflinuxfs2-rootfs  System plików
diego              Diego is the new container runtime system for Cloud Foundry, replacing the DEAs and Health Manager.
garden-runc        Guardian is a simple single-host OCI container manager. It implements the Garden API which is used in Cloud Foundry.
bosh-aws-cpi
bosh
=================  =================================================

Bosh
----
BOSH is an open source tool chain for release engineering, deployment and lifecycle management of large scale distributed services. It's the default deployment and management platform for Cloud Foundry operators.

BOSH installs and updates software packages on large numbers of VMs over many IaaS providers with the absolute minimum of configuration changes.

- https://bosh.io/docs/bosh-components.html

The Director is the core orchestrating component in BOSH. The Director controls VM creation and deployment, as well as other software and service lifecycle events.

Stemcell
^^^^^^^^
A stemcell is a versioned Operating System image wrapped with IaaS specific packaging.

- https://bosh.io/docs/stemcell.html

A typical stemcell contains a bare minimum OS skeleton with a few common utilities pre-installed, a BOSH Agent, and a few configuration files to securely configure the OS by default. For example: with vSphere, the official stemcell for Ubuntu Trusty is an approximately 500MB VMDK file. With AWS, official stemcells are published as AMIs that can be used in your AWS account.

By introducing the concept of a stemcell, the following problems have been solved:

- Capturing a base Operating System image
- Versioning changes to the Operating System image
- Reusing base Operating System images across VMs of different types
- Reusing base Operating System images across different IaaS

Release
^^^^^^^
A release is a versioned collection of configuration properties, configuration templates, start up scripts, source code, binary artifacts, and anything else required to build and deploy software in a reproducible way.

- https://bosh.io/docs/release.html

A release is the layer placed on top of a stemcell.

By introducing the concept of a release, the following concerns are addressed:

- Capturing all needed configuration options and scripts for deployment of the software
- Recording and keeping track of all dependencies for the software
- Versioning and keeping track of software releases
- Creating releases that can be IaaS agnostic
- Creating releases that are self-contained and do not require internet access for deployment

Deployment
^^^^^^^^^^
A deployment is a collection of VMs, built from a stemcell, that has been populated with specific releases and disks that keep persistent data. These resources are created based on a manifest file in the IaaS and managed by the BOSH Director, a centralized management server.

.. code-block:: yaml

    ---
    name: redis-us

    releases:
    - name: redis
      version: 15.9 # <--- bump version

    resource_pools:
    - name: all-machines
      stemcell:
        name: bosh-aws-xen-ubuntu-trusty-go_agent
        version: 2972
      network: default
      cloud_properties:
        instance_type: m1.small
        availability_zone: us-east-1a
    ...

Bosh Lite
---------
- https://github.com/cloudfoundry/bosh-lite

Create
^^^^^^
.. code-block:: sh

    git clone https://github.com/cloudfoundry/bosh-lite
    cd bosh-lite
    vagrant up

Upgrade
^^^^^^^
.. code-block:: sh

    git pull
    vagrant box update
    vagrant destroy
    vagrant up

CF Release
----------
CF-Release is the BOSH release repository for the Cloud Foundry platform. To deploy Cloud Foundry, start with cf-release, build a custom manifest for your deployment, and let BOSH take over from there.

Diego
-----
Diego is the new container runtime system for Cloud Foundry, replacing the DEA (Droplet Execution Agent) and Health Manager.

- https://github.com/cloudfoundry/diego-release

Cloud Foundry has used two architectures for managing application containers:

- Droplet Execution Agents (DEA)
- Diego.

With the DEA architecture, the Cloud Controller schedules and manages applications on the DEA nodes. In the newer Diego architecture, Diego components replace the DEAs and the Health Manager (HM9000), and assume application scheduling and management responsibility from the Cloud Controller.

- https://github.com/cloudfoundry/diego-release/tree/develop/examples/bosh-lite

From the standpoint of your application, here's what you need to know: In Diego, you now have the choice to push a one-use function (a Task) or a more traditional application that stays resident (a Long-Running Process, or LRP) -- a good example of an LRP might be a web server that you need always listening for traffic, while a Task may be something like a database migration as part of a release, or a task that examines recent data for something specific. Before, in DEA, you really only pushed processes that were expected to stay resident. Diego's brain and health monitor makes sure these tasks are balanced as well as possible - spreading out CPU-intensive tasks across virtual machines, or balancing memory, et cetera. While before some of this was done as part of the cloud controller, now the Diego environment handles it itself.

Getting a bit further into the trees, pushing an application to Cloud Foundry using Diego would:

- Contacts the Diego Brain which immediately sets up Auctioneer to announce to the diego cells that there is a new task or LRP that needs to be added, and how many cells it should use.

- Lets the Converger know what the application expects to have running at any time, so that if there is a change, it can immediately set up a replacement.

- The Diego Cells run the task at hand, constantly updating the bulletin board system with necessary information (such as CPU usage) that allow the auctioneer and the converger to ensure the app is running according to plan. Diego uses etcd to handle the BBS.

- What isn't handled by the BBS is handled by Consul - this is mostly locks to make sure only the right process is handling the right task (as an example in Diego, there can be only one Auctioneer at any time, but if that Auctioneer goes away, something else must pick up the lock) or load balancing.

- Various other Diego-specific processes (Nsync, TPS, stager, and so forth) all exist as brokers to provide information from the cells to the right ingestors to ensure things are pushed in a safe manner, and information gets back to the right channels when things are not so safe.

- http://www.starkandwayne.com/blog/demystifying-cloud-foundrys-diego/

Droplet Execution Agents (DEA) -> Diego
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- Warden -> Garden
- Health Manager (HM9000) -> nsync, BBS, and Cell Rep
- DEA Placement Algorithm -> Diego Auction
- Message Bus (NATS)

+-------------------------+---------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+
| DEA architecture        | Diego architecture                                                  | Function                                                                                | Δ notes                                                                                |
+=========================+=====================================================================+=====================================================================================================================================================+=============================================================================================================================+
| Ruby                    | Go                                                                  | Source code language                                                                                |                                                                                |
+-------------------------+---------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+
| DEA                     | Diego Brain                                                         | High-level coordinator that allocates processes to containers in application VMs and keeps them running                                             | DEA is part of the Cloud Controller. Diego is outside the Cloud Controller.                                                 |
+-------------------------+---------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+
| DEA Node                | Diego Cell                                                          | Mid-level manager on each VM that runs apps as directed and communicates "heartbeat", application status and container location, and other messages | Runs on each VM that hosts apps, as opposed to special-purpose component VMs.                                               |
+-------------------------+---------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+
| Warden                  | Garden                                                              | Low-level manager and API protocol on each VM for creating, configuring, destroying, monitoring, and addressing application containers              | Warden is Linux-only. Garden uses platform-specific Garden-backends to run on multiple OS.                                  |
+-------------------------+---------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+
| DEA Placement Algorithm | Diego Auction                                                       | Algorithm used to allocate processes to VMs                                                                                | Diego Auction distinguishes between Task and Long-Running Process (LRP) job types                                           |
+-------------------------+---------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+
| Health Manager (HM9000) | nSync, BBS, and Cell Reps                                           | System that monitors application instances and keeps instance counts in sync with the number that should be running                                 | nSync syncs between Cloud Controller and Diego, BBS syncs within Diego, and Cell Reps sync between cells and the Diego BBS. |
+-------------------------+---------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+
| NATS Message Bus        | Bulletin Board System (BBS) and Consulthrough HTTP, HTTPS, and NATS | Internal communication between components                                                                                | BBS stores most runtime data; Consul stores control data.                                                                   |
+-------------------------+---------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+
|                         |                                                                     |                                                                                |                                                                                |
+-------------------------+---------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+
|                         |                                                                     |                                                                                |                                                                                |
+-------------------------+---------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+

Consul
------
Consul is a tool for service discovery and configuration. Consul is distributed, highly available, and extremely scalable.

- https://github.com/hashicorp/consul

Consul provides several key features:

- Service Discovery - Consul makes it simple for services to register themselves and to discover other services via a DNS or HTTP interface. External services such as SaaS providers can be registered as well.

- Health Checking - Health Checking enables Consul to quickly alert operators about any issues in a cluster. The integration with service discovery prevents routing traffic to unhealthy hosts and enables service level circuit breakers.

- Key/Value Storage - A flexible key/value store enables storing dynamic configuration, feature flagging, coordination, leader election and more. The simple HTTP API makes it easy to use anywhere.

- Multi-Datacenter - Consul is built to be datacenter aware, and can support any number of regions without complex configuration.

Guardian
--------
A simple single-host OCI (`Open Container Initiative <https://www.opencontainers.org>`_) container manager.

- https://github.com/cloudfoundry/garden-runc-release

Components
^^^^^^^^^^
- Gardeners Question Time (GQT): A venerable British radio programme. And also a test suite.
- Gardener: Orchestrates the other components. Implements the Cloud Foundry Garden API.
- Garden Shed: RootFS and volume management. Where stuff is kept in the garden.
- RunDMC: A tiny wrappper around RunC to manage a collection of RunC containers.
- Kawasaki: It's an amazing networker.

CLI - Command Line Interface
----------------------------

.. code-block:: text

    Before getting started:
      config    login,l      target,t
      help,h    logout,lo

    Application lifecycle:
      apps,a        logs      set-env,se
      push,p        ssh       create-app-manifest
      start,st      app
      stop,sp       env,e
      restart,rs    scale
      restage,rg    events

    Services integration:
      marketplace,m        create-user-provided-service,cups
      services,s           update-user-provided-service,uups
      create-service,cs    create-service-key,csk
      update-service       delete-service-key,dsk
      delete-service,ds    service-keys,sk
      service              service-key
      bind-service,bs      bind-route-service,brs
      unbind-service,us    unbind-route-service,urs

    Route and domain management:
      routes,r        delete-route    create-domain
      domains         map-route
      create-route    unmap-route

    Space management:
      spaces         create-space    set-space-role
      space-users    delete-space    unset-space-role

    Org management:
      orgs,o       set-org-role
      org-users    unset-org-role

    CLI plugin management:
      plugins           add-plugin-repo      repo-plugins
      install-plugin    list-plugin-repos

    Commands offered by installed plugins:

    Global options:
      --help, -h                         Show help
      -v                                 Print API request diagnostics to stdout

Help
^^^^
.. code-block:: sh

    cf help

Deployment
^^^^^^^^^^
.. code-block:: sh

    cf push myapp -p <filename>.jar
    cf app myapp

Scaling
^^^^^^^
.. code-block:: sh

    cf scale myapp -i 2

Marketplace
^^^^^^^^^^^
.. code-block:: sh

    cf marketplace |grep mysql

    cf create-service p-mysql 100mb mydb
    cf bind-service myapp mydb
    cf restart myapp

Web Platform
------------
- https://console.run.pivotal.io

Login
^^^^^
.. code-block:: sh

    cf login -a api.run.pivotal.io
    cf push myapp

PCF Dev
-------
A lightweight Pivotal Cloud Foundry® (PCF) installation that runs on a single virtual machine (VM) on your workstation. PCF Dev is intended for application developers who want to develop and debug their applications locally on a PCF deployment.

- https://network.pivotal.io/products/pcfdev

Zadania
-------

`pcfdev`
^^^^^^^^
- Zainstaluj na czystym `Ubunutu` na `Vagrant` ``pcfdev``

.. code-block:: console
    :caption: Rozwiązanie dla CF Dev

    wget -q -O - https://packages.cloudfoundry.org/debian/cli.cloudfoundry.org.key | sudo apt-key add -
    echo "deb http://packages.cloudfoundry.org/debian stable main" | sudo tee /etc/apt/sources.list.d/cloudfoundry-cli.list
    sudo apt-get update
    sudo apt-get install openjdk-8-jdk
    sudo apt-get install cf-cli

Bosh Lite
^^^^^^^^^
- Uruchom `Bosh Lite` na `Vagrant`

.. code-block:: console
    :caption: Rozwiązanie deploymentu lokalnego - uruchomienie

    git clone https://github.com/cloudfoundry/bosh-lite
    cd bosh-lite
    vagrant up

    # uważaj na ilość RAMu i CPU dla maszyny

Deploy to local workstation
^^^^^^^^^^^^^^^^^^^^^^^^^^^
- Uruchom aplikację https://github.com/cloudfoundry-samples/spring-music CF lokalnie
- Podłącz aplikację do bazy danych `MySQL`

.. tip:: `cf dev <https://network.pivotal.io/products/pcfdev>`_

.. code-block:: console
    :caption: Rozwiązanie deploymentu lokalnego - uruchomienie

    git clone https://github.com/cloudfoundry-samples/spring-music
    cd ./spring-music
    cf login -a api.local.pcfdev.io --skip-ssl-validation
    ./gradlew assemble
    cf push --hostname spring-music
    cf logs spring-music --recent
    cf logs spring-music

.. code-block:: console
    :caption: Rozwiązanie deploymentu lokalnego - baza danych

    cf marketplace -s p-mysql
    cf create-service p-mysql 512mb my-spring-db
    cf bind-service spring-music my-spring-db
    cf restart spring-music
    cf services

Deploy to `Pivotal Web Services` (`PWS`)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- Uruchom aplikację https://github.com/cloudfoundry-samples/cf-sample-app-spring.git w `PWS`
- Podłącz aplikację do bazy danych `ElephantSQL`
- Przeskalują aplikację:

    - ilość instancji = 2
    - ilość ramu = 1 GB
    - ilość miejsca na dysku = 512 MB

.. code-block:: console
    :caption: Rozwiązanie deploymentu cloud - kod

    git clone https://github.com/cloudfoundry-samples/cf-sample-app-spring.git
    cd cf-sample-app-spring
    cf login -a https://api.run.pivotal.io
    cf push
    cf logs cf-spring --recent
    cf logs cf-spring

.. code-block:: console
    :caption: Rozwiązanie deploymentu cloud - baza danych

    cf marketplace -s elephantsql
    cf create-service elephantsql turtle cf-spring-db
    cf bind-service cf-spring cf-spring-db
    cf restart cf-spring
    cf services

.. code-block:: console
    :caption: Rozwiązanie deploymentu cloud - skalowanie

    cf scale cf-spring -i 2
    cf app cf-spring
    cf scale cf-spring -m 1G
    cf scale cf-spring -k 512M

Diego
^^^^^
- Uruchom `Diego` na `Bosh Lite` z poprzedniego zadania

.. code-block:: console
    :caption: Rozwiązanie

    https://github.com/cloudfoundry/diego-release/tree/develop/examples/bosh-lite


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>SIAA Research</title>
    <link rel="icon" type="image/x-icon" href="favicon.ico">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="css/normalize.min.css">
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.css">
    <link rel="stylesheet" href="css/site.min.css">

SIAA Research

Research to Reach the Stars

       contact [at] siaaresearch [dot] com

 Thinking On The Largest Scales

What could be larger then humanity exploring the galaxy?

We like to think about problems on such large physical and time scales, and how humanity can overcome them.

 Unlocking Humanity's Potential

We use computational methods to solve problems associated with human exploration of our cosmic neighbourhood.

We look at spacecraft trajectories for round-trip visits to one of the moons of Jupiter like Europa, to how humanity could escape the bounds of the Solar System and explore the Milky Way Galaxy.

We also study long-term and large-scale projects that would benefit all of humanity, such as the Astro-Engineering project of moving the position of the Earth to a safe distance from the Sun as it goes through its Red Giant Phase.

We also help researchers around the world modernize or optimize their scientific or legacy code to take advantage of new programming or computing paradigms.

 Who Are We?

We are a collection of Astronomy, Climate and Physics researchers with PhDs in our respective fields that love to solve problems.

Particularly those challenges that will see Humanity explore the Solar System and the Milky Way Galaxy.

These range from the dynamics and logistics of moving humans to the stars, to the needs of those humans so that they not only survive, but flourish.

 What Do We Do?

We primarily design computer models and numerical simulations to test our ideas.

They can be simple statistical models, precise spacecraft flight dynamics, or models of terraformation.

 What Does SIAA Mean?

SIAA is an acronym for the latin phrase

        Sic Itur Ad Astra

which translates into English as

        Thus One Goes To The Stars

 Why Should You Care?

We think that humanity's future will involve exploring the billions of worlds in our galaxy.

Though we may never participate in our lifetimes, we desire to be a part of that exploration and discovery in any way that we can.

By providing solutions to problems that humanity's descendants may encounter as they colonize space, we can take part vicariously through them.

 Projects

These are some of the active projects at SIAA Research

      <input class="toggle-box" id="longLiveEarth" type="checkbox">
      Long Live Earth

In this Astro-Engineering project, we consider how to move the position of the Earth to a safe distance from the Sun as it goes through its Red Giant Phase.

As the Sun starts to run out of fuel near the end of its life in the next 4 - 5 billion years, the Sun will start to increase in size engulfing the Earth in the process. For the long term survival of the planet Earth, the birthplace of humanity, we look at celestial mechanical solutions to this problem.

We look at the prospect of creating a celestial body close encounter delivery system which would gradually move the Earth to a safe distance from the Sun as it ages. The challenge of this approach is constructing such a delivery system that works on such large timescales, as well as accounting for potential gaps in human participation in this program.

      <input class="toggle-box" id="exploration" type="checkbox">
      Space Exploration

In this project we look at ways for humanity to escape the confines of the Solar System, and explore the galaxy.

Exploration mechanisms for humanity inside and outside of the Solar System.

Spacecraft trajectories for visits to all celestial bodies in the Solar System.

      <input class="toggle-box" id="biologicalSafety" type="checkbox">
      Biological Safety

Protecting human cargo and other biological matter through space.

      <input class="toggle-box" id="asteroidMining" type="checkbox">
      Asteroid Mining

Mining operations in the asteroid belt and comets in the Oort cloud.

      <input class="toggle-box" id="longTerm" type="checkbox">
      Long Term And Large Scale

Long-term and large-scale projects that would benefit all of humanity.

         2014-2016 SIAA Research. All Rights Reserved.


text:
describe('Function helper', function() {
  //
  // Handsontable.helper.proxy
  //
  describe('proxy', function() {
    it('should returns new function with corrected binded context', function() {
      var proxy = Handsontable.helper.proxy;
      var proxied = function(context) {
        return proxy(function() {
          return this;
        }, context)();
      }
      var object = {};
      var func = function(){};

      expect(proxied(1).valueOf()).toBe(1);
      expect(proxied('foo').valueOf()).toBe('foo');
      expect(proxied(func)).toBe(func);
    });
  });

  //
  // Handsontable.helper.throttle
  //
  describe('throttle', function() {
    it('should returns new function with applied throttling functionality', function() {
      var spy = jasmine.createSpy();
      var throttle = Handsontable.helper.throttle;
      var throttled = throttle(spy, 200);

      throttled();
      throttled();
      throttled();
      throttled();
      throttled();

      expect(spy.calls.length).toBe(1);

      waits(100);
      runs(function() {
        throttled();
        throttled();

        expect(spy.calls.length).toBe(1);
      });
      waits(300);
      runs(function() {
        throttled();
        throttled();
        throttled();
        throttled();

        expect(spy.calls.length).toBe(3);
      });
      waits(500);
      runs(function() {
        expect(spy.calls.length).toBe(4);
      });
    });
  });

  //
  // Handsontable.helper.throttleAfterHits
  //
  describe('throttleAfterHits', function() {
    it('should returns new function with applied throttling functionality', function() {
      var spy = jasmine.createSpy();
      var throttle = Handsontable.helper.throttleAfterHits;
      var throttled = throttle(spy, 200, 5);

      throttled();
      throttled();
      throttled();
      throttled();
      throttled();

      expect(spy.calls.length).toBe(5);

      waits(100);
      runs(function() {
        throttled();
        throttled();

        expect(spy.calls.length).toBe(6);
      });
      waits(300);
      runs(function() {
        throttled();
        throttled();
        throttled();
        throttled();

        expect(spy.calls.length).toBe(8);
      });
      waits(500);
      runs(function() {
        expect(spy.calls.length).toBe(9);
      });
    });
  });

  //
  // Handsontable.helper.debounce
  //
  describe('debounce', function() {
    it('should returns new function with applied debouncing functionality', function() {
      var spy = jasmine.createSpy();
      var debounce = Handsontable.helper.debounce;
      var debounced = debounce(spy, 200);

      debounced();
      debounced();
      debounced();
      debounced();
      debounced();

      expect(spy.calls.length).toBe(0);

      waits(100);
      runs(function() {
        debounced();
        debounced();

        expect(spy.calls.length).toBe(0);
      });
      waits(300);
      runs(function() {
        debounced();
        debounced();
        debounced();
        debounced();

        expect(spy.calls.length).toBe(1);
      });
      waits(500);
      runs(function() {
        expect(spy.calls.length).toBe(2);
      });
    });
  });
});


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace SpaceShooter.Tools
{
    // klasa odpowiadająca zapisywanie logów
    class Logger
    {
        /// <summary>
        /// Przekazuje informacje do zapisania w logach
        /// </summary>
        /// <param name="message">Treść wiadomości</param>
        static public void Info(string message)
        {
            WriteLog(message, "INFO");
        }

        /// <summary>
        /// Przekazuje treść błędu do zapisania w logach
        /// </summary>
        /// <param name="ex">Błąd</param>
        /// <param name="extraData">Dodatkowe informacje</param>
        static public void Error(Exception ex, string extraData = null)
        {
            WriteLog(ex.Message, "ERROR", extraData);
            WriteLog(ex.StackTrace, "STACKTRACE");
        }
        /// <summary>
        /// Zapisuje do logów wiadomość
        /// </summary>
        /// <param name="message">Treść wiadomości</param>
        /// <param name="type">Typ np. error, info</param>
        /// <param name="extraData">Dodatkowe informacje</param>
        static private void WriteLog(string message, string type, string extraData = null) {
            string new_message;
            new_message = "| " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " | [" + type + "] " + message + " | " + extraData;
            Trace.WriteLine(new_message);
        }
    }
}


text:
package com.sequenceiq.cloudbreak.cloud.model;

import com.sequenceiq.cloudbreak.cloud.model.VmTypeMeta.VmTypeMetaBuilder;

public enum VolumeParameterType {

    MAGNETIC() {
        @Override public VolumeParameterConfig getVolumeParameterByType(VmTypeMeta metaData) {
            return metaData.getMagneticConfig();
        }

        @Override
        public void buildForVmTypeMetaBuilder(VmTypeMetaBuilder builder, int maxDataDiskCount, int maxdiskSize) {
            builder.withMagneticConfig(VolumeParameterType.volumeParameterConfig(this, maxDataDiskCount, maxdiskSize));
        }

        @Override
        public void buildForVmTypeMetaBuilder(VmTypeMetaBuilder builder, int maxDataDiskCount) {
            builder.withMagneticConfig(VolumeParameterType.volumeParameterConfig(this, maxDataDiskCount));
        }

        @Override
        public boolean in(VolumeParameterType... types) {
            return VolumeParameterType.in(this, types);
        }
    },

    SSD() {
        @Override public VolumeParameterConfig getVolumeParameterByType(VmTypeMeta metaData) {
            return metaData.getSsdConfig();
        }

        @Override
        public void buildForVmTypeMetaBuilder(VmTypeMetaBuilder builder, int maxDataDiskCount, int maxdiskSize) {
            builder.withSsdConfig(VolumeParameterType.volumeParameterConfig(this, maxDataDiskCount, maxdiskSize));
        }

        @Override
        public void buildForVmTypeMetaBuilder(VmTypeMetaBuilder builder, int maxDataDiskCount) {
            builder.withSsdConfig(VolumeParameterType.volumeParameterConfig(this, maxDataDiskCount));
        }

        @Override
        public boolean in(VolumeParameterType... types) {
            return VolumeParameterType.in(this, types);
        }
    },

    EPHEMERAL() {
        @Override public VolumeParameterConfig getVolumeParameterByType(VmTypeMeta metaData) {
            return metaData.getEphemeralConfig();
        }

        @Override
        public void buildForVmTypeMetaBuilder(VmTypeMetaBuilder builder, int maxDataDiskCount) {
            builder.withEphemeralConfig(VolumeParameterType.volumeParameterConfig(this, maxDataDiskCount));
        }

        @Override
        public void buildForVmTypeMetaBuilder(VmTypeMetaBuilder builder, int maxDataDiskCount, int maxdiskSize) {
            builder.withEphemeralConfig(VolumeParameterType.volumeParameterConfig(this, maxDataDiskCount, maxdiskSize));
        }

        @Override
        public boolean in(VolumeParameterType... types) {
            return VolumeParameterType.in(this, types);
        }
    },

    ST1() {
        @Override public VolumeParameterConfig getVolumeParameterByType(VmTypeMeta metaData) {
            return metaData.getSt1Config();
        }

        @Override
        public void buildForVmTypeMetaBuilder(VmTypeMetaBuilder builder, int maxDataDiskCount, int maxdiskSize) {
            builder.withSt1Config(VolumeParameterType.volumeParameterConfig(this, maxDataDiskCount, maxdiskSize));
        }

        @Override
        public void buildForVmTypeMetaBuilder(VmTypeMetaBuilder builder, int maxDataDiskCount) {
            builder.withSt1Config(VolumeParameterType.volumeParameterConfig(this, maxDataDiskCount));
        }

        @Override
        public boolean in(VolumeParameterType... types) {
            return VolumeParameterType.in(this, types);
        }
    },

    AUTO_ATTACHED() {
        @Override public VolumeParameterConfig getVolumeParameterByType(VmTypeMeta metaData) {
            return metaData.getAutoAttachedConfig();
        }

        @Override
        public void buildForVmTypeMetaBuilder(VmTypeMetaBuilder builder, int maxDataDiskCount, int maxdiskSize) {
            builder.withAutoAttachedConfig(VolumeParameterType.volumeParameterConfig(this, maxDataDiskCount, maxdiskSize));
        }

        @Override
        public void buildForVmTypeMetaBuilder(VmTypeMetaBuilder builder, int maxDataDiskCount) {
            builder.withAutoAttachedConfig(VolumeParameterType.volumeParameterConfig(this, maxDataDiskCount));
        }

        @Override
        public boolean in(VolumeParameterType... types) {
            return VolumeParameterType.in(this, types);
        }
    };

    private static final int DEFAULT_MINIMUM_VOLUME_SIZE_IN_GIBIBYTES = 10;

    private static final int DEFAULT_MAXIMUM_VOLUME_SIZE_IN_GIBIBYTES = 4095;

    private static final int DEFAULT_MINIMUM_VOLUME_COUNT = 1;

    public abstract VolumeParameterConfig getVolumeParameterByType(VmTypeMeta metaData);

    public abstract void buildForVmTypeMetaBuilder(VmTypeMetaBuilder builder, int maxDataDiskCount);

    public abstract void buildForVmTypeMetaBuilder(VmTypeMetaBuilder builder, int maxDataDiskCount, int maxdiskSize);

    public abstract boolean in(VolumeParameterType... types);

    private static boolean in(VolumeParameterType type, VolumeParameterType... subset) {
        if (subset != null) {
            for (VolumeParameterType volumeParameterType : subset) {
                if (type == volumeParameterType) {
                    return true;
                }
            }
        }
        return false;
    }

    private static VolumeParameterConfig volumeParameterConfig(VolumeParameterType volumeParameterType, int maxDataDiskCount, int maxdiskSize) {
        return new VolumeParameterConfig(
                volumeParameterType,
                DEFAULT_MINIMUM_VOLUME_SIZE_IN_GIBIBYTES,
                maxdiskSize,
                DEFAULT_MINIMUM_VOLUME_COUNT,
                maxDataDiskCount);
    }

    private static VolumeParameterConfig volumeParameterConfig(VolumeParameterType volumeParameterType, int maxDataDiskCount) {
        return new VolumeParameterConfig(
                volumeParameterType,
                DEFAULT_MINIMUM_VOLUME_SIZE_IN_GIBIBYTES,
                DEFAULT_MAXIMUM_VOLUME_SIZE_IN_GIBIBYTES,
                DEFAULT_MINIMUM_VOLUME_COUNT,
                maxDataDiskCount);
    }

}


text:
package models

import "testing"

func TestGetLocalIntel(t *testing.T) {

	var names []interface{}
	names = append(names, "dude")
	names = append(names, "Test Character")

	_, err := GetLocalIntel(names)
	if err != nil {
		t.Error(err)
	}

}


text:
#ifndef _HMM_GAME_RISE_SKELETONS_DIALOG_H_
#define _HMM_GAME_RISE_SKELETONS_DIALOG_H_

class iDlg_RiseSkeletons : public iBaseGameDlg
{
public:
	iDlg_RiseSkeletons(iViewMgr* pViewMgr, PLAYER_ID pid, CREATURE_TYPE ct, sint32 quant );

private:
	void OnCreateDlg();
	void DoCompose(const iRect& rect);
	iSize ClientSize() const;
	void iCMDH_ControlCommand(iView* pView, CTRL_CMD_ID cmd, sint32 param);

private:
	CREATURE_TYPE	m_ct;
	sint32			m_quant;
};

#endif //_HMM_GAME_RISE_SKELETONS_DIALOG_H_


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TypeOperators #-}
module Network.Webmachine.DecisionCore where
import           Control.Exception
import           Control.Lens hiding (Context)
import           Control.Monad.Cont
import           Control.Monad.RWS.Strict
import           Crypto.Conduit (sinkHash)
import           Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Base16 as B16
import           Data.ByteString.Lazy (fromStrict)
import           Data.Conduit (($$), runResourceT)
import           Data.Digest.Pure.MD5 (MD5Digest)
import qualified Data.HashMap.Strict as H
import           Data.Text (Text)
import           Data.Time.Clock
import qualified Data.Serialize as S
import           Network.HTTP.Types.Header
import           Network.HTTP.Types.Method
import           Network.HTTP.Types.Status
import           Network.Wai.Lens

type NonEmptyList h a = (a, [a])

data Result e h a
  = Error SomeException
  | Halt Status h
  | Result a

class MonadIO m => DecisionGraph m r where
  ping :: Context r m Bool
  ping = return True

  serviceAvailable :: Context r m Bool
  serviceAvailable = return True

  knownMethods :: Context r m [Method]
  knownMethods = return [ methodGet, methodHead, methodPost, methodPut, methodDelete, methodPatch, methodTrace, methodConnect, methodOptions ]

  uriTooLong :: Context r m Bool
  uriTooLong = return False

  allowedMethods :: Context r m [Method]
  allowedMethods = return [ methodGet, methodHead ]

  validateContentChecksum :: Context r m (Maybe Bool)
  validateContentChecksum = return Nothing

  malformedRequest :: Context r m Bool
  malformedRequest = return False

  isAuthorized :: Context r m (Result e h (Either ByteString ()))
  isAuthorized = return True

  forbidden :: Context r m Bool
  forbidden = return False

  validContentHeaders :: Context r m Bool
  validContentHeaders = return True

  knownContentType :: Context r m Bool
  knownContentType = return True

  validEntityLength :: Context r m Bool
  validEntityLength = return True

  options :: Context r m [Method]
  options = return []

  languageAvailable :: Context r m Bool
  languageAvailable = return True

  resourceExists :: Context r m Bool
  resourceExists = return True

  generateETag :: Context r m (Maybe ByteString)
  generateETag = return Nothing

  lastModified :: Context r m (Maybe UTCTime)
  lastModified = return Nothing

  movedPermanently :: Context r m Bool
  movedPermanently = return False

  previouslyExisted :: Context r m Bool
  previouslyExisted = return False

  movedTemporarily :: Context r m Bool
  movedTemporarily = return False

  allowMissingPost :: Context r m Bool
  allowMissingPost = return False

  deleteResource :: Context r m Bool
  deleteResource = return False

  deleteCompleted :: Context r m Bool
  deleteCompleted = return True

  postIsCreate :: Context r m Bool
  postIsCreate = return False

  createPath :: Context r m (Maybe [Text])
  createPath = return Nothing

  baseUri :: Context r m (Maybe [Text])
  baseUri = return Nothing

  processPost :: Context r m Bool
  processPost = return False

  isConflict :: Context r m Bool
  isConflict = return False

  expires :: Context r m (Maybe UTCTime)
  expires = return Nothing

  multipleChoices :: Context r m Bool
  multipleChoices = return False

  contentTypesAccepted :: Context r m [ByteString]
  contentTypesAccepted = return []

  charsetsProvided :: Context r m (H.HashMap ByteString (ByteString -> ByteString))
  charsetsProvided = return []

  encodingsProvided :: Context r m (H.HashMap ByteString (ByteString -> ByteString))
  encodingsProvided = return [("identity", id)]

  contentTypesProvided :: Context r m (H.HashMap ByteString (Result e h a -> ByteString))
  contentTypesProvided = return []

  variances :: Context r m [()]
  variances = return []

type ContextState = (Request, H.HashMap HeaderName ByteString)

request :: Lens' ContextState Request
request = _1

resultHeaders :: Lens' ContextState (H.HashMap HeaderName ByteString)
resultHeaders = _2

newtype Context r m a = Context
  { fromContext :: ContT Response (RWST r () ContextState m) a
  }
  deriving (Monad)

instance (Monad m) => MonadState ContextState (Context r m) where
  get = Context $ lift get
  put = Context . lift . put

instance MonadIO m => MonadIO (Context r m) where
  liftIO = Context . liftIO

instance DecisionGraph IO ()

{-
runDecisionGraph :: DecisionGraph m r => r -> m Response
runDecisionGraph = runReaderT (runContT (decisionGraph True) return)

decisionGraph :: DecisionGraph m r => Context r m Response
decisionGraph = callCC $ \exit -> do
  b13 exit
  return $
-}

class Decision m a | a -> m where
  decision :: a -> m Response

instance Monad m => Decision (Context r m) Status where
  decision s = return $ responseLBS s [] $ fromStrict $ statusMessage s

instance Monad m => Decision (Context r m) (Context r m Response) where
  decision s = s

findHeader :: HeaderName -> [Header] -> Maybe BS.ByteString
findHeader h hs = headerPair ^? _Just . _2
  where headerPair = findOf each (\(k, v) -> k == h) hs

decisionTest :: (Monad m, Decision m a, Decision m b) => m Bool -> a -> b -> m Response
decisionTest t = decisionTest' t id

decisionTest' :: (Monad m, Decision m a, Decision m b) => m t -> (t -> Bool) -> a -> b -> m Response
decisionTest' t tf trueFlow falseFlow = do
  tr <- t
  if tf tr then decision trueFlow else decision falseFlow

getMethod :: Monad m => Context r m Method
getMethod = use $ request . method

getHeader :: Monad m => HeaderName -> Context r m (Maybe BS.ByteString)
getHeader h = use $ request . requestHeaders . to (findHeader h)

setHeader :: Monad m => HeaderName -> ByteString -> Context r m ()

chooseCharset
cooseEncoding ::
variances

-- | Service available
b13 :: (DecisionGraph m r) => Context r m Response
b13 = decisionTest ping b13b serviceUnavailable503

-- | Service available, part 2
b13b :: (DecisionGraph m r) => Context r m Response
b13b = decisionTest serviceAvailable b12 serviceUnavailable503

-- | Known method?
b12 :: (DecisionGraph m r) => Context r m Response
b12 = do
  m <- getMethod
  decisionTest (fmap (elem m) knownMethods) b11 notImplemented501
  where
    knownMethod = undefined

-- | URI too long?
b11 :: (DecisionGraph m r) => Context r m Response
b11 = decisionTest uriTooLong requestURITooLong414 b10

-- | Method allowed?
b10 :: (DecisionGraph m r) => Context r m Response
b10 = do
  methods <- allowedMethods
  m <- use $ request . method
  if elem m methods
    then b9
    else do
      (resultHeaders . at "Allow") .= Just (BS.intercalate ", " methods)
      decision methodNotAllowed405

-- | Content-MD5 present?
b9 :: (DecisionGraph m r) => Context r m Response
b9 = do
  h <- uses (request . requestHeaders) $ findHeader hContentMD5
  maybe b9b b9a h

-- | Content-MD5 valid?
b9a :: (MonadIO m, DecisionGraph m r) => ByteString -> Context r m Response
b9a providedMD5 = do
  bodySource <- use $ request . requestBody
  digest <- liftIO $ bodySource $$ sinkHash
  if fst (B16.decode providedMD5) == S.encode (digest :: MD5Digest)
    then b9b
    else decision badRequest400

-- | Malformed?
b9b :: (DecisionGraph m r) => Context r m Response
b9b = decisionTest malformedRequest badRequest400 b8

-- | Authorized?
b8 :: (DecisionGraph m r) => Context r m Response
b8 = do
  authResult <- isAuthorized
  case authResult of
    Result r -> case r of
      Left authHead -> do
        setHeader "WWW-Authenticate" authHead
        decision unauthorized401
      Right u -> b7
    _ -> return authResult

-- | Forbidden?
b7 :: (DecisionGraph m r) => Context r m Response
b7 = decisionTest forbidden forbidden403 b6

-- | Okay Content-* headers?
b6 :: (DecisionGraph m r) => Context r m Response
b6 = decisionTest validContentHeaders b5 notImplemented501

-- | Known Content-Type?
b5 :: (DecisionGraph m r) => Context r m Response
b5 = decisionTest knownContentType b4 unsupportedMediaType415

-- | Request entity too large?
b4 :: (DecisionGraph m r) => Context r m Response
b4 = decisionTest validEntityLength b3 requestEntityTooLarge413

-- | OPTIONS?
b3 :: (DecisionGraph m r) => Context r m Response
b3 = do
  m <- use $ request . method
  if m == methodOptions
    then decision internalServerError500
    else c3

-- | Accept exists
c3 :: (DecisionGraph m r) => Context r m Response
c3 = do
  types <- contentTypesProvided
  mAccept <- uses (request . requestHeaders) $ findHeader "Accept"
  case mAccept of
    Just a -> c4 a
    Nothing -> case types ^? traverse of
      Nothing -> decision notAcceptable406
      Just (t, _) -> do
        (resultHeaders . at hContentType) .= Just t
        d4

c4 :: (DecisionGraph m r) => ByteString -> Context r m Response
c4 contentType = do
  types <- contentTypesProvided
  case _ of
    Nothing -> decision notAcceptable406
    Just m -> do
      setMetadata "Content-Type" m
      d4

d4 :: (DecisionGraph m r) => Context r m Response
d4 = decisionTest' (getHeader "Accept-Language") (== Nothing) e5 d5

d5 :: (DecisionGraph m r) => Context r m Response
d5 = decisionTest languageAvailable e5 notAcceptable406

e5 :: (DecisionGraph m r) => Context r m Response
e5 = do
  mh <- getHeader "Accept-Charset"
  case mh of
    Nothing -> decisionTest' (chooseCharset "*") (== Nothing) notAcceptable406 f6
    Just h -> e6

e6 :: (DecisionGraph m r) => Context r m Response
e6 = decisionTest' (getHeader "Accept-Charset" >>= chooseCharset) (== Nothing ) notAcceptable406 f6

-- TODO implement this correctly
f6 :: (DecisionGraph m r) => ByteString -> Context r m Response
f6 h = g7

f7 :: (DecisionGraph m r) => Context r m Response
f7 = decisionTest' (getHeader "Accept-Encoding" >>= chooseEncoding) (== Nothing) notAcceptable406 g7

g7 :: (DecisionGraph m r) => ByteString -> Context r m Response
g7 = do
  vs <- variances
  case vs of
    [] -> return ()
    _ -> setHeader "Vary" (BS.intercalate vs ", ")
  decisionTest resourceExists g8 h7

g8 :: (DecisionGraph m r) => ByteString -> Context r m Response
g8 = decisionTest' (getHeader "If-Match") (== Nothing) h10 g9

g9 :: (DecisionGraph m r) => ByteString -> Context r m Response
g9 = decisionTest' (getHeader "If-Match") (== (Just "*")) h10 (g11 h)

g11 :: (DecisionGraph m r) => ByteString -> Context r m Response
g11 h = do
  let etags = splitQuotedStrings h
  etag <- generateETag
  if elem etag etags
    then h10
    else decision preconditionFailed412

h7 :: (DecisionGraph m r) => ByteString -> Context r m Response
h7 = decisionTest' (getHeader "If-Match") (== Nothing) i7 preconditionFailed412

h10 :: (DecisionGraph m r) => ByteString -> Context r m Response
h10 = decisionTest' (getHeader "If-Unmodified-Since") (== Nothing) i12 (h11 h)

h11 :: (DecisionGraph m r) => ByteString -> Context r m Response
h11 h = case convertRequestDate h of
  Nothing -> i12
  Just t -> h12 t

h12 :: (DecisionGraph m r) => UTCTime -> Context r m Response
h12 t = do
  lm <- lastModified
  case lm of
    Nothing -> i12
    Just l -> if t > t
      then decision preconditionFailed412
      else i12

i4 :: (DecisionGraph m r) => Context r m Response
i4 = do
  res <- movedPermanently
  case res of
    Result r -> case r of
      Just uri -> do
        setHeader "Location" uri
        decision movedPermanently301
      Nothing -> p3
    _ -> return res

i7 :: (DecisionGraph m r) => Context r m Response
i7 = decisionTest' getMethod (== methodPut) i4 k7

i12 :: (DecisionGraph m r) => Context r m Response
i12 = decisionTest' (getHeader "If-None-Match") (== Nothing) l13 i13

i13 :: (DecisionGraph m r) => Context r m Response
i13 = decisionTest' (getHeader "If-None-Match") (== (Just "*")) j18 k13

j18 :: (DecisionGraph m r) => Context r m Response
j18 = decisionTest' getMethod (\m -> m == methodGet || m == methodHead) notModified304 preconditionFailed412

k5 :: (DecisionGraph m r) => Context r m Response
k5 = do
  res <- movedPermanently
  case res of
    Result r -> case r of
      Just uri -> do
        setHeader "Location" uri
        decision movedPermanently301
      Nothing -> l5
    _ -> return res

k7 :: (DecisionGraph m r) => Context r m Response
k7 = decisionTest previouslyExisted k5 l7

-- TODO
k13 :: (DecisionGraph m r) => Context r m Response
k13 = l13

l5 :: (DecisionGraph m r) => Context r m Response
l5 = do
  res <- movedTemporarily
  case res of
    Result r -> case r of
      Just uri -> do
        setHeader "Location" uri
        decision temporaryRedirect307
      Nothing -> m5
    _ -> return res

l7 :: (DecisionGraph m r) => Context r m Response
l7 = decisionTest' getMethod (== methodPost) m7 notFound404

l13 :: (DecisionGraph m r) => Context r m Response
l13 = decisionTest' (getHeader "If-Modified-Since") (== Nothing) m16 l14

l14 :: (DecisionGraph m r) => Context r m Response
l14 dateHeader = do
  case convertRequestDate dateHeader of
    Nothing -> m16
    Just d -> l15 d

l15 :: (DecisionGraph m r) => Context r m Response
l15 t = do
  now <- liftIO getCurrentTime
  if t > now
    then m16
    else l17 t

l17 :: (DecisionGraph m r) => Context r m Response
l17 t = do
  lm <- lastModified
  case lm of
    Nothing -> decision notModified304
    Just m -> if m > t then m16 else decision notModified304

m5 :: (DecisionGraph m r) => Context r m Response
m5 = decisionTest getMethod (== methodPost) n5 gone410

m7 :: (DecisionGraph m r) => Context r m Response
m7 = decisionTest allowMissingPost n11 notFound404

m16 :: (DecisionGraph m r) => Context r m Response
m16 = decisionTest getMethod (== methodDelete) m20 n16

m20 :: (DecisionGraph m r) => Context r m Response
m20 = decisionTest deleteResource m20b internalServerError500

m20b :: (DecisionGraph m r) => Context r m Response
m20b = decisionTest deleteCompleted o20 accepted202

n5 :: (DecisionGraph m r) => Context r m Response
n5 = decisionTest allowMissingPost n11 gone410

-- TODO
n11 :: (DecisionGraph m r) => Context r m (Result ByteString h a)
n11 = do
  {-
  shouldCreate <- postIsCreate
  if shouldCreate
    then do
      path <- createPath
      case path of
        Nothing -> return $ Error "post is create without create path"
        Just p -> do
          base <- baseUri
          let b = if BS.last base == '/' then BS.init base else base
  -}
  p11

n16 :: (DecisionGraph m r) => Context r m Response
n16 = decisionTest' getMethod (== methodPost) n11 o16

o14 :: (DecisionGraph m r) => Context r m Response
o14 = do
  conflict <- isConflict
  if conflict
    then decision conflict409
    else do
      res <- acceptHelper
      case res of
        Result a -> p11 a
        _ -> return res

o16 :: (DecisionGraph m r) => Context r m Response
o16 = decisionTest' getMethod (== methodPut) o14 o18

o18 :: (DecisionGraph m r) => Context r m Response
o18 = do
  o18b

o18b :: (DecisionGraph m r) => Context r m Response
o18b = decisionTest multipleChoices multipleChoices300 ok200

o20 :: (DecisionGraph m r) => Context r m Response
o20 = decisionTest hasResponseBody o18 noContent204

p3 :: (DecisionGraph m r) => Context r m Response
p3 = do
  conflict <- isConflict
  if conflict
    then decision conflict409
    else do
      res <- acceptHelper
      case res of
        Result a -> p11 a
        _ -> return res

p11 :: (DecisionGraph m r) => Context r m Response
p11 = decisionTest' (getRequestHeader "Location") (== Nothing) o20 created201


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycopath. Mycol. appl. 36: 12 (1968)

#### Original name
Penicillium meridianum D.B. Scott, 1968

### Remarks
null


text:
'use strict';
angular.module('otrsapp.ticketservices', []).factory('TicketService', function ($q, $window, CommonService, AuthService) {
  var getByid = function ($http, ticketId, sessionId, ifAll) {
    var deferred = $q.defer();
    var request = $http({
      method: "post",
      url: wsUrl,
      headers: {
        'Content-Type': 'text/xml;charset=UTF-8',
        'Access-Control-Allow-Headers': 'Content-Type'
      },
      data: '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" ' +
        'xmlns:tic="http://www.otrs.org/TicketConnector/"> ' +
        '<soapenv:Header/>' +
        '<soapenv:Body>' +
        '<TicketGet>' +
        '  <tic:SessionID>' + sessionId + '</tic:SessionID>' +
        '  <tic:TicketID>' + ticketId + '</tic:TicketID>' +
        '  <tic:AllArticles>' + ifAll + '</tic:AllArticles>' +
        '</TicketGet>' +
        '</soapenv:Body>' +
        '</soapenv:Envelope>'
    });
    var tickets = null;
    request.success(
      function (html) {
        var xml = null;
        var domParser = new DOMParser();
        xml = domParser.parseFromString(html, 'text/xml').
        childNodes[0].
        childNodes[0].
        childNodes[0].
        childNodes[0];
        var jsonObject = CommonService.xml2json(xml);
        if (typeof jsonObject.ErrorCode != 'undefined') {
          AuthService.logout($window);
          deferred.reject('会话过期,请重新登录');
        } else {
          var status = '';
          if (jsonObject.StateType == 'closed') {
            status = '完成';
          } else if (jsonObject.StateType == 'new') {
            status = '新建';
          } else if (jsonObject.StateType == 'open') {
            status = '处理中'
          } else {
            status = '挂起';
          }
          var Articles = [];
          if (jsonObject.Article instanceof Array) {
            Articles = jsonObject.Article;
          } else {
            Articles.push(jsonObject.Article);
          }
          tickets = {
            id: jsonObject.TicketID,
            title: jsonObject.Title,
            description: Articles[0].Body.substr(0, 20),
            status: status,
            created: jsonObject.Created,
            queue: jsonObject.Queue.replace('队列', ''),
            articles: Articles
          };
          deferred.resolve(tickets);
        }
      }
    ).error(function (status) {
      deferred.reject(status);
    });
    return deferred.promise;
  };
  var getAll = function ($http, sessionId, customId) {
    var deferred = $q.defer();
    var request = $http({
      method: "post",
      url: wsUrl,
      headers: {
        'Content-Type': 'text/xml;charset=UTF-8',
        'Access-Control-Allow-Headers': 'Content-Type'
      },
      data: '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" ' +
        'xmlns:tic="http://www.otrs.org/TicketConnector/"> ' +
        '<soapenv:Header/>' +
        '<soapenv:Body>' +
        '<TicketSearch>' +
        '  <tic:SessionID>' + sessionId + '</tic:SessionID>' +
        '  <tic:CustomerUserID>' + customId + '</tic:CustomerUserID>' +
        '</TicketSearch>' +
        '</soapenv:Body>' +
        '</soapenv:Envelope>'
    });
    request.success(
      function (html) {
        var xml = null;
        var domParser = new DOMParser();
        xml = domParser.parseFromString(html, 'text/xml').
        childNodes[0].
        childNodes[0].
        childNodes[0];
        var jsonObject = CommonService.xml2json(xml).TicketID;
        if (typeof jsonObject == 'undefined') {
          AuthService.logout($window);
          deferred.reject('会话过期,请重新登录');
        } else {
          deferred.resolve(jsonObject);
        }
      }
    ).error(function (status) {
      deferred.reject(status);
    });
    return deferred.promise;
  };
  var getOne = function ($http, ticketId, sessionId, customId) {
    var deferred = $q.defer();
    var tickets = null;
    var promise = getByid($http, ticketId, sessionId, customId);
    promise.then(function (data) {
      tickets = data;
      deferred.resolve(tickets);
    });
    return deferred.promise;
  };
  var updateTicket = function ($http, ticketId, sessionId, customId, body) {
    var deferred = $q.defer();
    var request = $http({
      method: "post",
      url: wsUrl,
      headers: {
        'Content-Type': 'text/xml;charset=UTF-8',
        'Access-Control-Allow-Headers': 'Content-Type'
      },
      data: '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" ' +
        'xmlns:tic="http://www.otrs.org/TicketConnector/"> ' +
        '<soapenv:Header/>' +
        '<soapenv:Body>' +
        '<TicketUpdate> ' +
      //'<tic:SessionID>' + sessionId + '</tic:SessionID>' +
      '<tic:TicketID>' + ticketId + '</tic:TicketID>' +
      //'<tic:CustomerUserID>' + customId + '</tic:CustomerUserID>' +
      '<tic:UserLogin>test</tic:UserLogin>' +
        '<tic:Password>test</tic:Password>' +
        '<tic:Ticket>' +
        '<tic:PriorityID>5</tic:PriorityID>' +
        '</tic:Ticket>' +
        '<tic:Article>' +
        '<tic:From>' + customId + '</tic:From>' +
        '<tic:Subject>用户反馈</tic:Subject>' +
        '<tic:Body>' + body + '</tic:Body>' +
        '<tic:Charset>utf8</tic:Charset>' +
        '<tic:MimeType>text/plain</tic:MimeType>' +
        '</tic:Article>' +
        '</TicketUpdate>' +
        '</soapenv:Body> ' +
        '</soapenv:Envelope>'
    });
    request.success(
      function (html) {
        console.log(html);
        deferred.resolve('updated');
      }
    ).error(function (status) {
      deferred.reject(status);
    });
    return deferred.promise;
  };
  return {
    getByStartAndEnd: function ($http, sessionId, customId, start, end, step) {
      var deferred = $q.defer();
      var ticketsearch = [];
      getAll($http, sessionId, customId).then(function (jsonObject) {
        var ticketIdList = [];
        if (jsonObject instanceof Array) {
          ticketIdList = jsonObject;
        } else {
          ticketIdList.push(jsonObject);
        }
        var j = ticketIdList.length;
        //结束位不能超过长度
        if (end > j) {
          end = j;
        }
        //开始位不能大于结束位
        if (start >= end) {
          start = end - step;
          if (start < 0) {
            start = 0;
          }
        }
        console.log('起始位置:' + start + ' 结束位置:' + end);
        //for 循环同步方法:定义promise数组,将每次循环返回值(promise)压入promise数组
        //$q.all的回调里,返回上层的承诺deferred.resolve(ticketsearch);
        var promiseFor = [];
        for (var i = start; i < end; i++) {
          promiseFor.push(getByid($http, ticketIdList[i], sessionId, 1).then(function (data) {
            ticketsearch.push(data);
          }));
        }
        $q.all(promiseFor).then(function () {
          //for 产生的数据由于执行顺序的问题,结果可能不是按顺序排列的,所以要重新排序列
          ticketsearch.sort(function sortByid(ta, tb) {
            return tb.id - ta.id;
          });
          deferred.resolve(ticketsearch);
        });
      }, function (err) {
        deferred.reject(err);
      });
      return deferred.promise;
    },
    get: function ($http, ticketId, sessionId) {
      return getOne($http, ticketId, sessionId, 1);
    },
    updateTicket: function ($http, ticketId, sessionId, customId, body) {
      return updateTicket($http, ticketId, sessionId, customId, body);
    }
  };
})


text:
package com.martin.alllibrary.base.mvc;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.martin.alllibrary.util.showUtil.KeyboardUtils;
import com.martin.alllibrary.util.showUtil.ProgressDialogUtils;
import com.martin.alllibrary.util.showUtil.ToastUtils;
import com.martin.alllibrary.util.showUtil.WindowUtils;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

public abstract class BaseActivity extends RxAppCompatActivity {

    private static final String TAG = BaseActivity.class.getSimpleName();

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseApplication.addActivity(this);
        Log.e(TAG, "onCreate: " + getClass().getSimpleName());
    }

    public Context getContext() {
        return this;
    }

    public BaseActivity getActivity() {
        return this;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        BaseApplication.deleteActivity(this.getClass().getSimpleName());
        ProgressDialogUtils.getInstance().hideProgress();
    }

    protected void showKeyboard(boolean toShow) {
        KeyboardUtils.showKeyboard(getActivity(), toShow);
    }

    /**
     * 延时弹出键盘
     */
    protected void showKeyboardDelayed(View focus) {
        KeyboardUtils.showKeyboardDelayed(getActivity(), focus);
    }

    public boolean isDestroyedCompatible() {
        return super.isDestroyed();
    }

    public void showProgress() {
        showProgress(null, true);
    }

    public void showProgress(boolean cancelAble) {
        showProgress(null, cancelAble);
    }

    public void showProgress(String message) {
        showProgress(message, true);
    }

    public void showProgress(String message, boolean cancelAble) {
        ProgressDialogUtils.getInstance().showProgress(getActivity(), message, cancelAble);
    }

    public void hideProgress() {
        ProgressDialogUtils.getInstance().hideProgress();
    }

    public void showToast(String message) {
        showToast(message, true);
    }

    public void showToast(String message, boolean isShort) {
        if (isShort) {
            ToastUtils.showCustomToast(getContext(), message);
        } else {
            ToastUtils.showLongCustomToast(getContext(), message);
        }
    }

    public void showToast(int res) {
        showToast(getResources().getString(res));
    }

    /**
     * 设置导航栏颜色
     */
    public void setWindowStatusBarColor(int colorResId) {
        WindowUtils.setWindowStatusBarColor(colorResId, getActivity());
    }

    /**
     * 设置 全屏
     */
    public void setAllScreen() {
        WindowUtils.setAllScreen(getActivity());
    }

    public String noNull(String s) {
        return s == null ? "" : s;
    }

    public String getText(EditText editText) {
        if (editText != null) {
            return editText.getText().toString().trim();
        } else return "";
    }

    public String getText(TextView textView) {
        if (textView != null) {
            return textView.getText().toString().trim();
        } else return "";
    }

    protected <T extends View> T findView(int resId) {
        return (T) (findViewById(resId));
    }

}


text:
"""

This driver connects Cinder to an installed DRBDmanage instance, see
  http://oss.linbit.com/drbdmanage/
  http://git.linbit.com/drbdmanage.git/
for more details.

"""

import six
import socket
import uuid

from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import importutils
from oslo_utils import units

from cinder import exception
from cinder.i18n import _, _LW, _LI
from cinder.volume import driver

try:
    import dbus
    import drbdmanage.consts as dm_const
    import drbdmanage.exceptions as dm_exc
    import drbdmanage.utils as dm_utils
except ImportError:
    dbus = None
    dm_const = None
    dm_exc = None
    dm_utils = None

LOG = logging.getLogger(__name__)

drbd_opts = [
    cfg.StrOpt('drbdmanage_redundancy',
               default='1',
               help='Number of nodes that should replicate the data.'),
    cfg.BoolOpt('drbdmanage_devs_on_controller',
                default=True,
                help='''If set, the c-vol node will receive a useable
                /dev/drbdX device, even if the actual data is stored on
                other nodes only.
                This is useful for debugging, maintenance, and to be
                able to do the iSCSI export from the c-vol node.''')
    # TODO(PM): offsite_redundancy?
    # TODO(PM): choose DRBDmanage storage pool?
]

CONF = cfg.CONF
CONF.register_opts(drbd_opts)

AUX_PROP_CINDER_VOL_ID = "cinder-id"
DM_VN_PREFIX = 'CV_'  # sadly 2CV isn't allowed by DRBDmanage
DM_SN_PREFIX = 'SN_'

class DrbdManageDriver(driver.VolumeDriver):
    """Cinder driver that uses DRBDmanage for storage."""

    VERSION = '1.0.0'
    drbdmanage_dbus_name = 'org.drbd.drbdmanaged'
    drbdmanage_dbus_interface = '/interface'

    def __init__(self, *args, **kwargs):
        self.empty_list = dbus.Array([], signature="a(s)")
        self.empty_dict = dbus.Array([], signature="a(ss)")
        super(DrbdManageDriver, self).__init__(*args, **kwargs)
        self.configuration.append_config_values(drbd_opts)
        if not self.drbdmanage_dbus_name:
            self.drbdmanage_dbus_name = 'org.drbd.drbdmanaged'
        if not self.drbdmanage_dbus_interface:
            self.drbdmanage_dbus_interface = '/interface'
        self.drbdmanage_redundancy = int(getattr(self.configuration,
                                                 'drbdmanage_redundancy', 1))
        self.drbdmanage_devs_on_controller = bool(
            getattr(self.configuration,
                    'drbdmanage_devs_on_controller',
                    True))
        self.dm_control_vol = ".drbdctrl"

        # Copied from the LVM driver, see
        # I43190d1dac33748fe55fa00f260f32ab209be656
        target_driver = self.target_mapping[
            self.configuration.safe_get('iscsi_helper')]

        LOG.debug('Attempting to initialize DRBD driver with the '
                  'following target_driver: %s',
                  target_driver)

        self.target_driver = importutils.import_object(
            target_driver,
            configuration=self.configuration,
            db=self.db,
            executor=self._execute)

    def dbus_connect(self):
        self.odm = dbus.SystemBus().get_object(self.drbdmanage_dbus_name,
                                               self.drbdmanage_dbus_interface)
        self.odm.ping()

    def call_or_reconnect(self, fn, *args):
        """Call DBUS function; on a disconnect try once to reconnect."""
        try:
            return fn(*args)
        except dbus.DBusException as e:
            LOG.warning(_LW("Got disconnected; trying to reconnect. (%s)"), e)
            self.dbus_connect()
            # Old function object is invalid, get new one.
            return getattr(self.odm, fn._method_name)(*args)

    def do_setup(self, context):
        """Any initialization the volume driver does while starting."""
        super(DrbdManageDriver, self).do_setup(context)
        self.dbus_connect()

    def check_for_setup_error(self):
        """Verify that requirements are in place to use DRBDmanage driver."""
        if not all((dbus, dm_exc, dm_const, dm_utils)):
            msg = _('DRBDmanage driver setup error: some required '
                    'libraries (dbus, drbdmanage.*) not found.')
            LOG.error(msg)
            raise exception.VolumeDriverException(message=msg)
        if self.odm.ping() != 0:
            message = _('Cannot ping DRBDmanage backend')
            raise exception.VolumeBackendAPIException(data=message)

    def _clean_uuid(self):
        """Returns a UUID string, WITHOUT braces."""
        # Some uuid library versions put braces around the result!?
        # We don't want them, just a plain [0-9a-f-]+ string.
        id = str(uuid.uuid4())
        id = id.replace("{", "")
        id = id.replace("}", "")
        return id

    def _check_result(self, res, ignore=None, ret=0):
        seen_success = False
        seen_error = False
        result = ret
        for (code, fmt, arg_l) in res:
            # convert from DBUS to Python
            arg = dict(arg_l)
            if ignore and code in ignore:
                if not result:
                    result = code
                continue
            if code == dm_exc.DM_SUCCESS:
                seen_success = True
                continue
            seen_error = _("Received error string: %s") % (fmt % arg)

        if seen_error:
            raise exception.VolumeBackendAPIException(data=seen_error)
        if seen_success:
            return ret
        # by default okay - or the ignored error code.
        return ret

    # DRBDmanage works in kiB units; Cinder uses GiB.
    def _vol_size_to_dm(self, size):
        return int(size * units.Gi / units.Ki)

    def _vol_size_to_cinder(self, size):
        return int(size * units.Ki / units.Gi)

    def is_clean_volume_name(self, name, prefix):
        try:
            if (name.startswith(CONF.volume_name_template % "") and
                    uuid.UUID(name[7:]) is not None):
                return prefix + name[7:]
        except ValueError:
            return None

        try:
            if uuid.UUID(name) is not None:
                return prefix + name
        except ValueError:
            return None

    def _priv_hash_from_volume(self, volume):
        return dm_utils.dict_to_aux_props({
            AUX_PROP_CINDER_VOL_ID: volume['id'],
        })

    def snapshot_name_from_cinder_snapshot(self, snapshot):
        sn_name = self.is_clean_volume_name(snapshot['id'], DM_SN_PREFIX)
        return sn_name

    def _res_and_vl_data_for_volume(self, volume, empty_ok=False):
        """Find DRBD resource and volume ID.

        A DRBD resource might consist of several "volumes"
        (think consistency groups).
        So we have to find the number of the volume within one resource.
        Returns resource name, volume number, and resource
        and volume properties.
        """

        # If we get a string, use it as-is.
        # Else it's a dictionary; then get the ID.
        if isinstance(volume, six.string_types):
            v_uuid = volume
        else:
            v_uuid = volume['id']

        res, rl = self.call_or_reconnect(self.odm.list_volumes,
                                         self.empty_dict,
                                         0,
                                         dm_utils.dict_to_aux_props(
                                             {AUX_PROP_CINDER_VOL_ID: v_uuid}),
                                         self.empty_dict)
        self._check_result(res)

        if (not rl) or (len(rl) == 0):
            if empty_ok:
                LOG.debug("No volume %s found.", v_uuid)
                return None, None, None, None
            raise exception.VolumeBackendAPIException(
                data=_("volume %s not found in drbdmanage") % v_uuid)
        if len(rl) > 1:
            raise exception.VolumeBackendAPIException(
                data=_("multiple resources with name %s found by drbdmanage") %
                v_uuid)

        (r_name, r_props, vols) = rl[0]
        if len(vols) != 1:
            raise exception.VolumeBackendAPIException(
                data=_("not exactly one volume with id %s") %
                v_uuid)

        (v_nr, v_props) = vols[0]

        LOG.debug("volume %(uuid)s is %(res)s/%(nr)d; %(rprop)s, %(vprop)s",
                  {'uuid': v_uuid, 'res': r_name, 'nr': v_nr,
                   'rprop': r_props, 'vprop': v_props})

        return r_name, v_nr, r_props, v_props

    def _resource_and_snap_data_from_snapshot(self, snapshot, empty_ok=False):
        """Find DRBD resource and snapshot name from the snapshot ID."""
        s_uuid = snapshot['id']
        res, rs = self.call_or_reconnect(self.odm.list_snapshots,
                                         self.empty_dict,
                                         self.empty_dict,
                                         0,
                                         dm_utils.dict_to_aux_props(
                                             {AUX_PROP_CINDER_VOL_ID: s_uuid}),
                                         self.empty_dict)
        self._check_result(res)

        if (not rs) or (len(rs) == 0):
            if empty_ok:
                return None
            else:
                raise exception.VolumeBackendAPIException(
                    data=_("no snapshot with id %s found in drbdmanage") %
                    s_uuid)
        if len(rs) > 1:
            raise exception.VolumeBackendAPIException(
                data=_("multiple resources with snapshot ID %s found") %
                s_uuid)

        (r_name, snaps) = rs[0]
        if len(snaps) != 1:
            raise exception.VolumeBackendAPIException(
                data=_("not exactly one snapshot with id %s") % s_uuid)

        (s_name, s_props) = snaps[0]

        LOG.debug("snapshot %(uuid)s is %(res)s/%(snap)s",
                  {'uuid': s_uuid, 'res': r_name, 'snap': s_name})

        return r_name, s_name, s_props

    def _resource_name_volnr_for_volume(self, volume, empty_ok=False):
        res, vol, _, _ = self._res_and_vl_data_for_volume(volume, empty_ok)
        return res, vol

    def local_path(self, volume):
        dres, dvol = self._resource_name_volnr_for_volume(volume)

        res, data = self.call_or_reconnect(self.odm.text_query,
                                           [dm_const.TQ_GET_PATH,
                                            dres,
                                            str(dvol)])
        self._check_result(res)
        if len(data) == 1:
            return data[0]
        message = _('Got bad path information from DRBDmanage! (%s)') % data
        raise exception.VolumeBackendAPIException(data=message)

    def create_volume(self, volume):
        """Creates a DRBD resource.

        We address it later on via the ID that gets stored
        as a private property.
        """

        # TODO(PM): consistency groups
        dres = self.is_clean_volume_name(volume['id'], DM_VN_PREFIX)

        res = self.call_or_reconnect(self.odm.create_resource,
                                     dres,
                                     self.empty_dict)
        self._check_result(res, ignore=[dm_exc.DM_EEXIST], ret=None)

        # If we get DM_EEXIST, then the volume already exists, eg. because
        # deploy gave an error on a previous try (like ENOSPC).
        # Still, there might or might not be the volume in the resource -
        # we have to check that explicitly.
        (_, drbd_vol) = self._resource_name_volnr_for_volume(volume,
                                                             empty_ok=True)
        if not drbd_vol:
            props = self._priv_hash_from_volume(volume)
            # TODO(PM): properties - redundancy, etc
            res = self.call_or_reconnect(self.odm.create_volume,
                                         dres,
                                         self._vol_size_to_dm(volume['size']),
                                         props)
            self._check_result(res)

        # If we crashed between create_volume and the deploy call,
        # the volume might be defined but not exist on any server. Oh my.
        res = self.call_or_reconnect(self.odm.auto_deploy,
                                     dres, self.drbdmanage_redundancy,
                                     0, True)
        self._check_result(res)

        if self.drbdmanage_devs_on_controller:
            # FIXME: Consistency groups, vol#
            res = self.call_or_reconnect(self.odm.assign,
                                         socket.gethostname(),
                                         dres,
                                         self.empty_dict)
            self._check_result(res, ignore=[dm_exc.DM_EEXIST])

        return 0

    def delete_volume(self, volume):
        """Deletes a resource."""
        dres, dvol = self._resource_name_volnr_for_volume(
            volume,
            empty_ok=True)

        if not dres:
            # OK, already gone.
            return True

        # TODO(PM): check if in use? Ask whether Primary, or just check result?
        res = self.call_or_reconnect(self.odm.remove_volume, dres, dvol, False)
        self._check_result(res, ignore=[dm_exc.DM_ENOENT])

        res, rl = self.call_or_reconnect(self.odm.list_volumes,
                                         [dres],
                                         0,
                                         self.empty_dict,
                                         self.empty_list)
        self._check_result(res)

        # We expect the _resource_ to be here still (we just got a volnr from
        # it!), so just query the volumes.
        # If the resource has no volumes anymore, the current DRBDmanage
        # version (errorneously, IMO) returns no *resource*, too.
        if len(rl) > 1:
            message = _('DRBDmanage expected one resource ("%(res)s"), '
                        'got %(n)d') % {'res': dres, 'n': len(rl)}
            raise exception.VolumeBackendAPIException(data=message)

        # Delete resource, if empty
        if (not rl) or (not rl[0]) or (len(rl[0][2]) == 0):
            res = self.call_or_reconnect(self.odm.remove_resource, dres, False)
            self._check_result(res, ignore=[dm_exc.DM_ENOENT])

    def create_volume_from_snapshot(self, volume, snapshot):
        """Creates a volume from a snapshot."""

        LOG.debug("create vol from snap: from %(snap)s make %(vol)s",
                  {'snap': snapshot['id'], 'vol': volume['id']})
        # TODO(PM): Consistency groups.
        dres, sname, sprop = self._resource_and_snap_data_from_snapshot(
            snapshot)

        new_res = self.is_clean_volume_name(volume['id'], DM_VN_PREFIX)

        r_props = self.empty_dict
        # TODO(PM): consistency groups => different volume number possible
        v_props = [(0, self._priv_hash_from_volume(volume))]

        res = self.call_or_reconnect(self.odm.restore_snapshot,
                                     new_res,
                                     dres,
                                     sname,
                                     r_props,
                                     v_props)
        return self._check_result(res, ignore=[dm_exc.DM_ENOENT])

    def create_cloned_volume(self, volume, src_vref):
        temp_id = self._clean_uuid()
        snapshot = {'id': temp_id}

        self.create_snapshot({'id': temp_id, 'volume_id': src_vref['id']})

        self.create_volume_from_snapshot(volume, snapshot)

        self.delete_snapshot(snapshot)

    def _update_volume_stats(self):
        data = {}

        data["vendor_name"] = 'Open Source'
        data["driver_version"] = self.VERSION
        data["storage_protocol"] = self.target_driver.protocol
        # This has to match the name set in the cinder volume driver spec,
        # so keep it lowercase
        data["volume_backend_name"] = "drbdmanage"
        data["pools"] = []

        res, free, total = self.call_or_reconnect(self.odm.cluster_free_query,
                                                  self.drbdmanage_redundancy)
        self._check_result(res)

        location_info = ('DrbdManageDriver:%(cvol)s:%(dbus)s' %
                         {'cvol': self.dm_control_vol,
                          'dbus': self.drbdmanage_dbus_name})

        # TODO(PM): multiple DRBDmanage instances and/or multiple pools
        single_pool = {}
        single_pool.update(dict(
            pool_name=data["volume_backend_name"],
            free_capacity_gb=self._vol_size_to_cinder(free),
            total_capacity_gb=self._vol_size_to_cinder(total),
            reserved_percentage=self.configuration.reserved_percentage,
            location_info=location_info,
            QoS_support=False))

        data["pools"].append(single_pool)

        self._stats = data

    def get_volume_stats(self, refresh=True):
        """Get volume status."""

        self._update_volume_stats()
        return self._stats

    def extend_volume(self, volume, new_size):
        dres, dvol = self._resource_name_volnr_for_volume(volume)

        res = self.call_or_reconnect(self.odm.resize_volume,
                                     dres, dvol, -1,
                                     {"size": self._vol_size_to_dm(new_size)},
                                     0)
        self._check_result(res)
        return 0

    def create_snapshot(self, snapshot):
        """Creates a snapshot."""
        sn_name = self.snapshot_name_from_cinder_snapshot(snapshot)

        dres, dvol = self._resource_name_volnr_for_volume(
            snapshot["volume_id"])

        res, data = self.call_or_reconnect(self.odm.list_assignments,
                                           self.empty_dict,
                                           [dres],
                                           0,
                                           self.empty_dict,
                                           self.empty_dict)
        self._check_result(res)

        nodes = [d[0] for d in data]
        if len(nodes) < 1:
            raise exception.VolumeBackendAPIException(
                _('Snapshot res "%s" that is not deployed anywhere?') %
                (dres))

        props = self._priv_hash_from_volume(snapshot)
        res = self.call_or_reconnect(self.odm.create_snapshot,
                                     dres, sn_name, nodes, props)
        self._check_result(res)

    def delete_snapshot(self, snapshot):
        """Deletes a snapshot."""

        dres, sname, _ = self._resource_and_snap_data_from_snapshot(
            snapshot, empty_ok=True)

        if not dres:
            # resource already gone?
            LOG.warning(_LW("snapshot: %s not found, "
                            "skipping delete operation"), snapshot['id'])
            LOG.info(_LI('Successfully deleted snapshot: %s'), snapshot['id'])
            return True

        res = self.call_or_reconnect(self.odm.remove_snapshot,
                                     dres, sname, True)
        return self._check_result(res, ignore=[dm_exc.DM_ENOENT])

    # #######  Interface methods for DataPath (Target Driver) ########

    def ensure_export(self, context, volume):
        volume_path = self.local_path(volume)
        return self.target_driver.ensure_export(
            context,
            volume,
            volume_path)

    def create_export(self, context, volume, connector):
        volume_path = self.local_path(volume)
        export_info = self.target_driver.create_export(
            context,
            volume,
            volume_path)

        return {'provider_location': export_info['location'],
                'provider_auth': export_info['auth'], }

    def remove_export(self, context, volume):
        return self.target_driver.remove_export(context, volume)

    def initialize_connection(self, volume, connector):
        return self.target_driver.initialize_connection(volume, connector)

    def validate_connector(self, connector):
        return self.target_driver.validate_connector(connector)

    def terminate_connection(self, volume, connector, **kwargs):
        return None


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _socket = require('socket.io');

var _socket2 = _interopRequireDefault(_socket);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

// TODO: emit function
// TODO: create rooms and events for each module
var ResponseSocket = function () {
  function ResponseSocket(socket, socketCallback) {
    _classCallCheck(this, ResponseSocket);

    this.socket = socket;
    this.send = socketCallback;
  }

  _createClass(ResponseSocket, null, [{
    key: 'voidCallback',
    value: function voidCallback() {}
  }]);

  return ResponseSocket;
}();

// TODO: implements methods GET, POST, ETC

var SocketServer = function () {
  function SocketServer(httpServer, modulesHandler) {
    _classCallCheck(this, SocketServer);

    this.httpServer = httpServer;
    this.modulesHandler = modulesHandler;
  }

  _createClass(SocketServer, [{
    key: 'start',
    value: function start() {
      this.io = (0, _socket2.default)(this.httpServer.app);
      this.io.on('connect', this.socketHandlerFunction(this.modulesHandler));
    }
  }, {
    key: 'socketHandlerFunction',
    value: function socketHandlerFunction(modulesHandler) {
      return function (socket) {
        var mapActions = modulesHandler.mapActions;
        if (mapActions['connect']) {
          mapActions['connect'](ResponseSocket.voidCallback, null);
        }
        Object.keys(mapActions).forEach(function (key) {
          var action = mapActions[key];
          socket.on(key, function (params, socketCallbackParam) {
            if (!action.auth || params.auth === action.auth) {
              var socketCallback = typeof socketCallbackParam === 'function' ? socketCallbackParam : ResponseSocket.voidCallback;
              var connection = new ResponseSocket(socket, socketCallback);
              action.handler(connection, params);
            }
          });
        });
      };
    }
  }]);

  return SocketServer;
}();

exports.default = SocketServer;