text:
mod macros;

mod decode;
mod encode;

pub mod error;

mod util;
mod xz;

use std::io;

/// Compression helpers.
pub mod compress {
    pub use crate::encode::options::*;
}

/// Decompression helpers.
pub mod decompress {
    pub use crate::decode::options::*;

    #[cfg(feature = "raw_decoder")]
    #[cfg_attr(docsrs, doc(cfg(raw_decoder)))]
    pub mod raw {
        //! Raw decoding primitives for LZMA/LZMA2 streams.
        pub use crate::decode::lzma::{LzmaDecoder, LzmaParams, LzmaProperties};
        pub use crate::decode::lzma2::Lzma2Decoder;
    }

    #[cfg(feature = "stream")]
    #[cfg_attr(docsrs, doc(cfg(stream)))]
    pub use crate::decode::stream::Stream;
}

/// Decompress LZMA data with default [`Options`](decompress/struct.Options.html).
pub fn lzma_decompress<R: io::BufRead, W: io::Write>(
    input: &mut R,
    output: &mut W,
) -> error::Result<()> {
    lzma_decompress_with_options(input, output, &decompress::Options::default())
}

/// Decompress LZMA data with the provided options.
pub fn lzma_decompress_with_options<R: io::BufRead, W: io::Write>(
    input: &mut R,
    output: &mut W,
    options: &decompress::Options,
) -> error::Result<()> {
    let params = decode::lzma::LzmaParams::read_header(input, options)?;
    let mut decoder = decode::lzma::LzmaDecoder::new(params, options.memlimit)?;
    decoder.decompress(input, output)
}

/// Compresses data with LZMA and default [`Options`](compress/struct.Options.html).
pub fn lzma_compress<R: io::BufRead, W: io::Write>(
    input: &mut R,
    output: &mut W,
) -> io::Result<()> {
    lzma_compress_with_options(input, output, &compress::Options::default())
}

/// Compress LZMA data with the provided options.
pub fn lzma_compress_with_options<R: io::BufRead, W: io::Write>(
    input: &mut R,
    output: &mut W,
    options: &compress::Options,
) -> io::Result<()> {
    let encoder = encode::dumbencoder::Encoder::from_stream(output, options)?;
    encoder.process(input)
}

/// Decompress LZMA2 data with default [`Options`](decompress/struct.Options.html).
pub fn lzma2_decompress<R: io::BufRead, W: io::Write>(
    input: &mut R,
    output: &mut W,
) -> error::Result<()> {
    decode::lzma2::Lzma2Decoder::new().decompress(input, output)
}

/// Compress data with LZMA2 and default [`Options`](compress/struct.Options.html).
pub fn lzma2_compress<R: io::BufRead, W: io::Write>(
    input: &mut R,
    output: &mut W,
) -> io::Result<()> {
    encode::lzma2::encode_stream(input, output)
}

/// Decompress XZ data with default [`Options`](decompress/struct.Options.html).
pub fn xz_decompress<R: io::BufRead, W: io::Write>(
    input: &mut R,
    output: &mut W,
) -> error::Result<()> {
    decode::xz::decode_stream(input, output)
}

/// Compress data with XZ and default [`Options`](compress/struct.Options.html).
pub fn xz_compress<R: io::BufRead, W: io::Write>(input: &mut R, output: &mut W) -> io::Result<()> {
    encode::xz::encode_stream(input, output)
}


text:
文字サイズの変化 group: article

(breakpoint)	(fontsize)

.echo-***-sm	.echo-***	.echo-***-lg

            md以下
            xs
            sm
            md

            lg以上
            sm
            md
            lg

この表の解説

redpajama_set_name: RedPajamaGithub


text:
package org.neo4j.server.rest.transactional;

import java.net.URI;
import java.util.Iterator;
import java.util.List;

public enum ResultDataContent
{
    row
    {
        @Override
        public ResultDataContentWriter writer( URI baseUri )
        {
            return new RowWriter();
        }
    },
    graph
    {
        @Override
        public ResultDataContentWriter writer( URI baseUri )
        {
            return new GraphExtractionWriter();
        }
    },
    rest
    {
        @Override
        public ResultDataContentWriter writer( URI baseUri )
        {
            return new RestRepresentationWriter( baseUri );
        }
    };

    public abstract ResultDataContentWriter writer( URI baseUri );

    public static ResultDataContent[] fromNames( List<?> names )
    {
        if ( names == null || names.isEmpty() )
        {
            return null;
        }
        ResultDataContent[] result = new ResultDataContent[names.size()];
        Iterator<?> name = names.iterator();
        for ( int i = 0; i < result.length; i++ )
        {
            Object contentName = name.next();
            if ( contentName instanceof String )
            {
                try
                {
                    result[i] = valueOf( ((String) contentName).toLowerCase() );
                }
                catch ( IllegalArgumentException e )
                {
                    throw new IllegalArgumentException( "Invalid result data content specifier: " + contentName );
                }
            }
            else
            {
                throw new IllegalArgumentException( "Invalid result data content specifier: " + contentName );
            }
        }
        return result;
    }
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   >

    <RelativeLayout
        android:id="@+id/score_one"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="#5CACEE">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            >

            <ImageView
                android:id="@+id/score_back"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_marginLeft="20dp"
                android:src="@mipmap/backhome"
                />
            <TextView
                android:id="@+id/score_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:textSize="23dp"
                android:text="我的积分"/>

            <ImageView
                android:id="@+id/score_index"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_alignTop="@+id/score_back"
                android:layout_alignParentRight="true"
                android:layout_marginRight="20dp"
                android:src="@mipmap/back"
                />

        </RelativeLayout>

    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/score_two"
        android:layout_centerInParent="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <RelativeLayout
            android:id="@+id/score_shuzi"
            android:layout_width="230dp"
            android:background="@mipmap/yuanhuan"
            android:layout_height="230dp"
            android:layout_marginTop="30dp"
            android:layout_centerHorizontal="true">
            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true">

            <TextView
                android:id="@+id/score_tv_shuzi"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="积分余额"
                android:textColor="#40E0D0"

                android:textSize="23sp"/>

                <TextView
                    android:id="@+id/score_tv2_shuzi"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="214"
                    android:textColor="#00BFFF"
                    android:layout_below="@+id/score_tv_shuzi"
                    android:layout_centerHorizontal="true"

                    android:textSize="52sp"/>
            </RelativeLayout>

        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/score_exchange"
            android:layout_width="match_parent"
            android:layout_marginTop="10dp"
            android:layout_below="@+id/score_shuzi"
            android:layout_height="wrap_content">
            <Button
                android:layout_width="wrap_content"
                android:layout_height="70dp"
                android:layout_centerHorizontal="true"
                android:text="去兑换"
                android:textColor="#00BFFF"
                android:textSize="23sp"
                android:background="@mipmap/duihuan"/>

        </RelativeLayout>

        <!--
        以后补充账单明细,用listView形式
        -->

      <!--  <RelativeLayout
            android:id="@+id/score_detail"
            android:layout_width="match_parent"
            android:layout_marginTop="10dp"
            android:background="#E0E0E0"
            android:layout_below="@+id/score_exchange"
            android:layout_height="30dp">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="账单明细"
                android:layout_centerVertical="true"
                android:textSize="19sp"
                />

        </RelativeLayout>
-->
    </RelativeLayout>

</RelativeLayout>


text:
#include "clustertest.h"

#include <cluster_framework/auth_provider_service.h>
#include <cluster_framework/bucket.h>
#include <cluster_framework/cluster.h>
#include <include/mcbp/protocol/unsigned_leb128.h>
#include <protocol/connection/client_connection.h>
#include <protocol/connection/client_mcbp_commands.h>
#include <protocol/connection/frameinfo.h>
#include <thread>

class CollectionsTests : public cb::test::ClusterTest {
protected:
    void testSubdocRbac(MemcachedConnection& conn, const std::string& key);
    static std::unique_ptr<MemcachedConnection> getConnection() {
        auto bucket = cluster->getBucket("default");
        auto conn = bucket->getConnection(Vbid(0));
        conn->authenticate("@admin", "password", "PLAIN");
        conn->selectBucket(bucket->getName());
        conn->setFeature(cb::mcbp::Feature::Collections, true);
        return conn;
    }

    static void mutate(MemcachedConnection& conn,
                       std::string id,
                       MutationType type) {
        Document doc{};
        doc.value = R"({"json":true})";
        doc.info.id = std::move(id);
        doc.info.datatype = cb::mcbp::Datatype::JSON;
        const auto info = conn.mutate(doc, Vbid{0}, type);
        EXPECT_NE(0, info.cas);
    }
};

// Verify that I can store documents within the collections
TEST_F(CollectionsTests, TestBasicOperations) {
    auto conn = getConnection();
    mutate(*conn,
           createKey(CollectionEntry::fruit, "TestBasicOperations"),
           MutationType::Add);
    mutate(*conn,
           createKey(CollectionEntry::fruit, "TestBasicOperations"),
           MutationType::Set);
    mutate(*conn,
           createKey(CollectionEntry::fruit, "TestBasicOperations"),
           MutationType::Replace);
}

TEST_F(CollectionsTests, TestInvalidCollection) {
    auto conn = getConnection();
    try {
        // collections 1 to 7 are reserved and invalid from a client
        mutate(*conn, createKey(1, "TestInvalidCollection"), MutationType::Add);
        FAIL() << "Einval not detected";
    } catch (const ConnectionError& e) {
        EXPECT_EQ(cb::mcbp::Status::Einval, e.getReason());
    }
    try {
        // collection 1000 is unknown
        mutate(*conn,
               createKey(1000, "TestInvalidCollection"),
               MutationType::Add);
        FAIL() << "UnknownCollection not detected";
    } catch (const ConnectionError& e) {
        EXPECT_EQ(cb::mcbp::Status::UnknownCollection, e.getReason());
    }
}

static BinprotSubdocCommand subdocInsertXattrPath(const std::string& key,
                                                  const std::string& path) {
    using namespace cb::mcbp;
    return BinprotSubdocCommand(ClientOpcode::SubdocDictAdd,
                                key,
                                path,
                                "{}",
                                SUBDOC_FLAG_XATTR_PATH | SUBDOC_FLAG_MKDIR_P,
                                mcbp::subdoc::doc_flag::Mkdoc);
}

void CollectionsTests::testSubdocRbac(MemcachedConnection& conn,
                                      const std::string& key) {
    auto fruit = createKey(CollectionEntry::fruit, "TestBasicRbac");
    auto vegetable = createKey(CollectionEntry::vegetable, "TestBasicRbac");

    // Check subdoc, privilege checks happen in 2 places
    // 1) we're checking we can do the xattr write
    auto subdoc = subdocInsertXattrPath(fruit, "nosys");
    auto response = BinprotMutationResponse(conn.execute(subdoc));
    EXPECT_TRUE(response.isSuccess()) << to_string(response.getStatus());
    subdoc = subdocInsertXattrPath(fruit, "_sys");
    response = BinprotMutationResponse(conn.execute(subdoc));
    EXPECT_TRUE(response.isSuccess()) << to_string(response.getStatus());

    // 2) XTOC evaluates xattr read privs separately.
    // connection only has xattr read, 1 entry comes back
    BinprotSubdocMultiLookupCommand cmd;
    cmd.setKey(fruit);
    cmd.addGet("$XTOC", SUBDOC_FLAG_XATTR_PATH);
    conn.sendCommand(cmd);
    BinprotSubdocMultiLookupResponse resp;
    resp.clear();
    conn.recvResponse(resp);
    EXPECT_TRUE(resp.isSuccess()) << to_string(resp.getStatus());
    ASSERT_EQ(1, resp.getResults().size());
    EXPECT_EQ(cb::mcbp::Status::Success, resp.getResults().front().status);
    EXPECT_EQ(R"(["nosys"])", resp.getResults().front().value);
}

TEST_F(CollectionsTests, TestBasicRbac) {
    const std::string username{"TestBasicRbac"};
    const std::string password{"TestBasicRbac"};
    cluster->getAuthProviderService().upsertUser({username, password, R"({
  "buckets": {
    "default": {
      "scopes": {
        "0": {
          "collections": {
            "0": {
              "privileges": [
                "Read"
              ]
            },
            "9": {
              "privileges": [
                "Read",
                "Insert",
                "Delete",
                "Upsert",
                "XattrRead",
                "XattrWrite",
                "SystemXattrWrite"
              ]
            }
          }
        }
      }
    }
  },
  "privileges": [],
  "domain": "external"
})"_json});

    auto conn = getConnection();
    mutate(*conn,
           createKey(CollectionEntry::defaultC, "TestBasicRbac"),
           MutationType::Add);
    mutate(*conn,
           createKey(CollectionEntry::fruit, "TestBasicRbac"),
           MutationType::Add);
    mutate(*conn,
           createKey(CollectionEntry::vegetable, "TestBasicRbac"),
           MutationType::Add);

    // I'm allowed to read from the default collection and read and write
    // to the fruit collection
    conn->authenticate(username, password);
    conn->selectBucket("default");

    testSubdocRbac(*conn, "TestBasicRbac");

    conn->get(createKey(CollectionEntry::defaultC, "TestBasicRbac"), Vbid{0});
    conn->get(createKey(CollectionEntry::fruit, "TestBasicRbac"), Vbid{0});

    // I cannot get from the vegetable collection
    try {
        conn->get(createKey(CollectionEntry::vegetable, "TestBasicRbac"),
                  Vbid{0});
        FAIL() << "Should not be able to fetch in vegetable collection";
    } catch (const ConnectionError& error) {
        // No privileges so we would get unknown collection error
        ASSERT_TRUE(error.isUnknownCollection())
                << to_string(error.getReason());
        EXPECT_EQ(
                cluster->collections.getUidString(),
                error.getErrorJsonContext()["manifest_uid"].get<std::string>());
    }

    // I'm only allowed to write in Fruit
    mutate(*conn,
           createKey(CollectionEntry::fruit, "TestBasicRbac"),
           MutationType::Set);
    for (auto c : std::vector<CollectionID>{
                 {CollectionEntry::defaultC, CollectionEntry::vegetable}}) {
        try {
            mutate(*conn, createKey(c, "TestBasicRbac"), MutationType::Set);
            FAIL() << "Should only be able to store in the fruit collection";
        } catch (const ConnectionError& error) {
            if (c == CollectionEntry::defaultC.getId()) {
                // Default: we have read, but not write so access denied
                ASSERT_TRUE(error.isAccessDenied());
            } else {
                // Nothing at all in vegetable, so unknown
                ASSERT_TRUE(error.isUnknownCollection());
                EXPECT_EQ(cluster->collections.getUidString(),
                          error.getErrorJsonContext()["manifest_uid"]
                                  .get<std::string>());
            }
        }
    }

    auto fruit = conn->getCollectionId("_default.fruit");
    EXPECT_EQ(CollectionEntry::fruit.getId(), fruit.getCollectionId());
    auto defaultScope = conn->getScopeId("_default");
    EXPECT_EQ(CollectionEntry::defaultC.getId(), defaultScope.getScopeId());
    // Now failure, we have no privs in customer_scope
    try {
        conn->getCollectionId("customer_scope.customer_collection1");
        FAIL() << "Expected an error";
    } catch (const ConnectionError& error) {
        EXPECT_TRUE(error.isUnknownCollection());
        EXPECT_EQ(
                cluster->collections.getUidString(),
                error.getErrorJsonContext()["manifest_uid"].get<std::string>());
    }
    try {
        conn->getScopeId("customer_scope");
        FAIL() << "Expected an error";
    } catch (const ConnectionError& error) {
        EXPECT_TRUE(error.isUnknownScope());
        EXPECT_EQ(
                cluster->collections.getUidString(),
                error.getErrorJsonContext()["manifest_uid"].get<std::string>());
    }

    // Check we get a restricted view of the manifest, only have access to
    // two collections
    auto json = conn->getCollectionsManifest();
    ASSERT_EQ(1, json["scopes"].size());
    EXPECT_EQ("_default", json["scopes"][0]["name"]);
    EXPECT_EQ("0", json["scopes"][0]["uid"]);
    EXPECT_EQ(2, json["scopes"][0]["collections"].size());
    EXPECT_EQ(1,
              std::count_if(json["scopes"][0]["collections"].begin(),
                            json["scopes"][0]["collections"].end(),
                            [](nlohmann::json entry) {
                                return entry["name"] == "_default" &&
                                       entry["uid"] == "0";
                            }));
    EXPECT_EQ(1,
              std::count_if(json["scopes"][0]["collections"].begin(),
                            json["scopes"][0]["collections"].end(),
                            [](nlohmann::json entry) {
                                return entry["name"] == "fruit" &&
                                       entry["uid"] == "9";
                            }));

    cluster->getAuthProviderService().removeUser(username);
}

TEST_F(CollectionsTests, ResurrectCollection) {
    // Store a key to the collection
    auto conn = getConnection();
    mutate(*conn,
           createKey(CollectionEntry::vegetable, "Generation1"),
           MutationType::Add);

    auto bucket = cluster->getBucket("default");
    ASSERT_NE(nullptr, bucket);
    cluster->collections.remove(CollectionEntry::vegetable);
    bucket->setCollectionManifest(cluster->collections.getJson());
    cluster->collections.add(CollectionEntry::vegetable);
    bucket->setCollectionManifest(cluster->collections.getJson());
    mutate(*conn,
           createKey(CollectionEntry::vegetable, "Generation2"),
           MutationType::Add);

    // Generation 1 is lost, the first drop was accepted and the keys created
    // before the resurrection of vegetable are dropped.
    try {
        conn->get(createKey(CollectionEntry::vegetable, "Generation1"),
                  Vbid{0});
        FAIL() << "Should not be able to fetch in Generation1 key";
    } catch (const ConnectionError& error) {
        ASSERT_TRUE(error.isNotFound()) << to_string(error.getReason());
    }
    conn->get(createKey(CollectionEntry::vegetable, "Generation2"), Vbid{0});
}


text:
  Escoulis est
       un village
       géographiquement positionné dans le département de Haute-Garonne en Midi-Pyrénées. Elle totalisait 75 habitants en 2008.

Le nombre d'habitations, à Escoulis, était réparti en 2011 en deux appartements et 54 maisons soit
 un marché relativement équilibré.

À proximité de Escoulis sont positionnées géographiquement les villes de
Touille située à 5 km, 259 habitants,
Ausseing à 4 km, 67 habitants,
Salies-du-Salat située à 5 km, 1 936 habitants,
Cassagne située à 3 km, 627 habitants,
Belbèze-en-Comminges située à 2 km, 109 habitants,
Betchat à 2 km, 348 habitants,
 entre autres. De plus, Escoulis est située à seulement 18 km de La Trinité.

Si vous envisagez de demenager à Escoulis, vous pourrez aisément trouver une maison à vendre.


text:
using System;
using System.Reactive.Linq;

using ReactiveUI;

using Guess5.Lib.Helper;
using Guess5.Lib.Model;
using System.Reactive;
using System.Threading.Tasks;
using System.Diagnostics;

namespace Guess5.Droid.ViewModel
{
    public class ViewModel_Game : ReactiveObject
    {
        public ReactiveActivity CurrentActivity { get; set; }

        /// <summary>
        /// This is part of the alphabet letter png filenames.
        /// The naming convention for the png file is "letter_?.png" where ? is the alphabet
        /// </summary>
        private static string LetterFile { get; set; } = "letter_";

        /// <summary>
        /// This is part of the hangman image png filenames.
        /// The naming convention for the png file is "hangman_0n.png" where n is a number
        /// </summary>
        private static string HangmanImage { get; set; } = "hangman";

        /// <summary>
        /// This is the name of the question mark png file name
        /// </summary>
        private static string QuestionMarkImage { get; set; } = "question_mark";

        /// <summary>
        /// variable stores the hidden word.
        /// </summary>
        public string hidden_word { get; private set; }

        /* ==== Declare variables to store hiddent letter image. I have called them Slot Image =================*/
        private string _slot01_Image = QuestionMarkImage;
        public string Slot01_Image {
            get => _slot01_Image;
            set => this.RaiseAndSetIfChanged(ref _slot01_Image, LetterFile + value);
        }

        private string _slot02_Image = QuestionMarkImage;
        public string Slot02_Image {
            get => _slot02_Image;
            set => this.RaiseAndSetIfChanged(ref _slot02_Image, LetterFile + value);
        }

        private string _slot03_Image = QuestionMarkImage;
        public string Slot03_Image {
            get => _slot03_Image;
            set => this.RaiseAndSetIfChanged(ref _slot03_Image, LetterFile + value);
        }

        private string _slot04_Image = QuestionMarkImage;
        public string Slot04_Image {
            get => _slot04_Image;
            set => this.RaiseAndSetIfChanged(ref _slot04_Image, LetterFile + value);
        }

        private string _slot05_Image = QuestionMarkImage;
        public string Slot05_Image {
            get => _slot05_Image;
            set => this.RaiseAndSetIfChanged(ref _slot05_Image, LetterFile + value);
        }

        /* ==== End of Slot Image Declaration ===================================================================*/

        /* ==== Declare variable to store hangman image  ========================================================*/
        private string _hangman_image = "hangman00"; // set the default image to load when activity start
        public string Hangman_Image {
            get => _hangman_image;
            set => this.RaiseAndSetIfChanged(ref _hangman_image, HangmanImage + value.PadLeft(2, '0'));
        }
        /* ======================================================================================================*/

        /* ==== Declare variable to store letter for each button on the view/screen =============================*/

        /* There are total 15 buttons. Hence have to declare 15 variables to store letter for each button */

        private string _btn01 = string.Empty;
        public string Btn01 {
            get => _btn01.ToUpper();
            set => this.RaiseAndSetIfChanged(ref _btn01, value);
        }

        private string _btn02 = string.Empty;
        public string Btn02 {
            get => _btn02.ToUpper();
            set => this.RaiseAndSetIfChanged(ref _btn02, value);
        }

        private string _btn03 = string.Empty;
        public string Btn03 {
            get => _btn03.ToUpper();
            set => this.RaiseAndSetIfChanged(ref _btn03, value);
        }

        private string _btn04 = string.Empty;
        public string Btn04 {
            get => _btn04.ToUpper();
            set => this.RaiseAndSetIfChanged(ref _btn04, value);
        }

        private string _btn05 = string.Empty;
        public string Btn05 {
            get => _btn05.ToUpper();
            set => this.RaiseAndSetIfChanged(ref _btn05, value);
        }

        private string _btn06 = string.Empty;
        public string Btn06 {
            get => _btn06.ToUpper();
            set => this.RaiseAndSetIfChanged(ref _btn06, value);
        }

        private string _btn07 = string.Empty;
        public string Btn07 {
            get => _btn07.ToUpper();
            set => this.RaiseAndSetIfChanged(ref _btn07, value);
        }

        private string _btn08 = string.Empty;
        public string Btn08 {
            get => _btn08.ToUpper();
            set => this.RaiseAndSetIfChanged(ref _btn08, value);
        }

        private string _btn09 = string.Empty;
        public string Btn09 {
            get => _btn09.ToUpper();
            set => this.RaiseAndSetIfChanged(ref _btn09, value);
        }

        private string _btn10 = string.Empty;
        public string Btn10 {
            get => _btn10.ToUpper();
            set => this.RaiseAndSetIfChanged(ref _btn10, value);
        }

        private string _btn11 = string.Empty;
        public string Btn11 {
            get => _btn11.ToUpper();
            set => this.RaiseAndSetIfChanged(ref _btn11, value);
        }

        private string _btn12 = string.Empty;
        public string Btn12 {
            get => _btn12.ToUpper();
            set => this.RaiseAndSetIfChanged(ref _btn12, value);
        }

        private string _btn13 = string.Empty;
        public string Btn13 {
            get => _btn13.ToUpper();
            set => this.RaiseAndSetIfChanged(ref _btn13, value);
        }

        private string _btn14 = string.Empty;
        public string Btn14 {
            get => _btn14.ToUpper();
            set => this.RaiseAndSetIfChanged(ref _btn14, value);
        }

        private string _btn15 = string.Empty;
        public string Btn15 {
            get => _btn15.ToUpper();
            set => this.RaiseAndSetIfChanged(ref _btn15, value);
        }

        /* ==== End of declaration of button letter variables ================================================ */

        /* =================================================================================================== */

        /* Current Score */
        private int _score;
        public string Score {
            get => _score.ToString();
            set { } // add this bit of code so that the Reactive UI data bind will work
        }

        /* Highest Score */
        private int _highestscore = 0;
        public string HighestScore  {
            get => _highestscore > 0 ? _highestscore.ToString() : "";
            set { } // add this bit of code so that the Reactive UI data bind will work
        }

        /* ==================================================================================================== */

        /* ===== Declare variable to store the Timer Counter value. ============================= */
        private int _timer;
        public string Timer  {
            /*  How to add zero-padding to a string
                https://stackoverflow.com/questions/3122677/add-zero-padding-to-a-string */
            get => _timer.ToString().PadLeft(2, '0');
            set {
                if (int.TryParse(value, out int i)) this.RaiseAndSetIfChanged(ref _timer, i);
            }
        }
        /* ===== End of decaration for Timer Counter variable  =================================== */

        /*
            This flag check whether the "game" is still running.
            The flag is set to true whenever a new game started.
            It will remain true during the game session.
            The flag is set to false when the user lose a game
         */
        private bool _is_running_flag;
        public bool Is_Game_Still_Running {
            get => _is_running_flag ;
            set => this.RaiseAndSetIfChanged(ref _is_running_flag, value);
        }

        private bool _restart_timer_flag;
        public bool Restart_Timer
        {
            get => _restart_timer_flag;
            set => this.RaiseAndSetIfChanged(ref _restart_timer_flag, value);
        }

        private static int MAX_TICK { get; set; } = 20;
        public void TimerTick()
        {
            if (Is_Game_Still_Running)
            {
                _timer = (_timer == 0) ? MAX_TICK : _timer - 1;
                this.RaisePropertyChanged("Timer");
            }
        }

        public void TimerTick2(int counter) {
            _timer = counter;
            this.RaisePropertyChanged("Timer");
        }

        /* ======================================================= */

        /* the winning/lossing flag */
        private bool _winning_flag = false;
        public bool Is_Game_Won {
            get => _winning_flag;
            set => this.RaiseAndSetIfChanged(ref _winning_flag, value);
        }

        /* store the button number in 0n format (where n is a number) */
        public string Btn_Tag { get; set; }

        /* store the letter value on the button */
        private static string QuestionMark { get; set; } = "?";
        private string _button_letter = QuestionMark;
        public string Btn_Text {
            get => _button_letter;
            set => this.RaiseAndSetIfChanged(ref _button_letter, value);
        }

        private string _toast;
        public string Toast { get => _toast; set => this.RaiseAndSetIfChanged(ref _toast, value); }
        private static int MAX_GUESS { get; set; } = 6;
        private static int MAX_COUNT { get; set; } = 10;

        private int _worng_guess = 0;
        private int _correct_guess = 0;
        private int _hangman_count = 6;

        public ReactiveCommand<Unit, Unit> commandStart;

        public ViewModel_Game()
        {
            GenerateHiddenWord();

            ButtonLetterInitializer();

            //Is_Game_Still_Running = false;

            SetComanndStart();

            //this.WhenAnyValue(x => x.Restart_Timer)
            //    .Subscribe( _ =>
            //    {
            //        var interval = Observable.Interval(TimeSpan.FromMilliseconds(1000));
            //        IDisposable timer = interval.Subscribe( i =>
            //            { //System.Diagnostics.Debug.WriteLine(i);
            //                _timer = (int)i % MAX_COUNT ;
            //                System.Diagnostics.Debug.WriteLine(_timer);
            //                this.RaisePropertyChanged("Timer");
            //                Debug.WriteLine($"Timer counter : {_timer}");
            //            });

            //        //void doDispose()
            //        //{
            //        //    timer.Dispose();
            //        //}

            //        //Action doDisposeAction = new Action(doDispose);

            //        //this.WhenAnyValue(y => y.Restart_Timer)
            //        //    .Subscribe( (z) => {
            //        //        timer.Dispose();
            //        //    });

            //    });

            /* for debug purpose */
            //hidden_word = "heels";
            //ShowHiddenWord();
            //SetTimer();
        }

        /// <summary>
        /// function that return a random 5 letters hidden words
        /// </summary>
        private void GenerateHiddenWord() { hidden_word = WordsHelper.GetNextWord(); }

        /// <summary>
        /// Initialize all the 15 letters buttons "keyboard" at the start of a new game.
        /// It will contain
        /// </summary>
        private void ButtonLetterInitializer()
        {
            string letter_list = WordsHelper.GenerateRandomLetter(hidden_word);
            for (int i = 0; i < 15; i++)
            {
                string value = "" + letter_list[i];
                switch (i + 1)
                {
                    case 1: Btn01 = value; break;
                    case 2: Btn02 = value; break;
                    case 3: Btn03 = value; break;
                    case 4: Btn04 = value; break;
                    case 5: Btn05 = value; break;
                    case 6: Btn06 = value; break;
                    case 7: Btn07 = value; break;
                    case 8: Btn08 = value; break;
                    case 9: Btn09 = value; break;
                    case 10: Btn10 = value; break;
                    case 11: Btn11 = value; break;
                    case 12: Btn12 = value; break;
                    case 13: Btn13 = value; break;
                    case 14: Btn14 = value; break;
                    case 15: Btn15 = value; break;
                }
            }
        }

        private IDisposable timerCounterDisposable = null ;

        private void SetComanndStart()
        {
            /*
             * http://dotnetpattern.com/csharp-action-delegate
             */

            // Debug
            Is_Game_Still_Running = true;

            void doStartButton()
            {
                /* check whether any game is running*/
                if (!Is_Game_Still_Running)
                {
                    //Is_Game_Still_Running = true;
                }
                else
                {
                    //Is_Game_Still_Running = false;

                }

                //Restart_Timer = true;
                //this.RaisePropertyChanged("Restart_Timer");

                //// Debug
                //Debug.WriteLine($"Is_Game_Still_Running {Is_Game_Still_Running}");
                //Debug.WriteLine($"Restart_Timer {Restart_Timer}");
            }

            Action doStartAction = new Action(doStartButton);
            //commandStart = ReactiveCommand.Create(doStartAction);

            /* ========= DEBUG ========================== */
            /* create a Aaction to test the timer counter */

            void restartTimerCounter()
            {
                //RunOnUiThread(() => ViewModel.TimerTick2(counter));
                /* Dispose if an obervable for the timer counter is running */
                if (timerCounterDisposable != null)
                {
                     timerCounterDisposable.Dispose();
                }

                //_timer = MAX_COUNT;
                //this.RaisePropertyChanged("Timer");

                /*
                 https://social.msdn.microsoft.com/Forums/en-US/c4acaf34-3136-4206-a6f9-ef5afba74b2b/interval-with-immediate-start?forum=rx
                 */

                timerCounterDisposable = Observable.Interval(TimeSpan.FromSeconds(1))
                            .Take(MAX_COUNT)
                            .Distinct()
                            //.Delay(TimeSpan.FromSeconds(1))
                            .Repeat()
                            .Subscribe(value =>
                            {
                                CurrentActivity.RunOnUiThread(() =>
                                {
                                    var counter = MAX_COUNT - (int)value;
                                    _timer = counter;
                                    this.RaisePropertyChanged("Timer");
                                    Debug.WriteLine($"Timer counter : {_timer}");
                                });
                            });
            }

            Action restartTimerAction = new Action(restartTimerCounter);
            commandStart = ReactiveCommand.Create(restartTimerAction);
        }

        private void CommentOut()
        {
            this.WhenAny(x => x.Btn_Text, _ => string.Empty).Subscribe(Func => {

                /* get the letter on the button */
                char ch = Btn_Text.ToLower()[0]; /* convert string to char */
                if (hidden_word.LastIndexOf(ch) != -1)
                {
                    /* Count the number of time the letter appear in the hidden words*/
                    int count = CountLetter(ch);

                    /* Calculate the score and update to total score*/
                    int score = WordsHelper.GetScore(ch);
                    _score += (_timer + score) * count;
                    this.RaisePropertyChanged("Score"); /* Trigger Property Changed */

                    /* Since the user has found letter/letters in the hidden word.
                       reset the timer to MAX_TICK*/
                    //_timer = MAX_TICK;

                    /* v0.6 update the highest score */
                    if (_correct_guess == MAX_COUNT)
                    {
                        _highestscore += _score;
                        this.RaisePropertyChanged("HighestScore"); /* Trigger Property Changed */

                        _winning_flag = true;
                        this.RaisePropertyChanged("IsWinning"); /* Trigger Property Changed */
                    }
                }
                else
                {
                    SetHangmanImage(); /* set the hangmen image*/
                                       //_timer = MAX_TICK; /* reset the timer counter */
                                       /* User has so amny guesses based on  MAX_GUESS */
                }

                if (Is_Game_Still_Running)
                    _timer = MAX_TICK; /* reset the timer counter */
                this.RaisePropertyChanged("Timer"); /* Trigger Property Changed */

                /* Not a best way of doing */
                _button_letter = QuestionMark;
            });

            this.WhenAny(x => x.Btn_Text, _ => string.Empty).Subscribe( Func =>  {

                /* get the letter on the button */
                char ch = Btn_Text.ToLower()[0]; /* convert string to char */
                if (hidden_word.LastIndexOf(ch) != -1)
                {
                    /* Count the number of time the letter appear in the hidden words*/
                    int count = CountLetter(ch);

                    /* Calculate the score and update to total score*/
                    int score = WordsHelper.GetScore(ch);
                    _score += (_timer + score ) * count ;
                    this.RaisePropertyChanged("Score"); /* Trigger Property Changed */

                    /* Since the user has found letter/letters in the hidden word.
                       reset the timer to MAX_TICK*/
                    //_timer = MAX_TICK;

                    /* v0.6 update the highest score */
                    if (_correct_guess==MAX_COUNT)
                    {
                        _highestscore += _score;
                        this.RaisePropertyChanged("HighestScore"); /* Trigger Property Changed */

                        _winning_flag = true;
                        this.RaisePropertyChanged("IsWinning"); /* Trigger Property Changed */
                    }
                }
                else
                {
                    SetHangmanImage(); /* set the hangmen image*/
                                       //_timer = MAX_TICK; /* reset the timer counter */
                                       /* User has so amny guesses based on  MAX_GUESS */
                }

                if(Is_Game_Still_Running)
                    _timer = MAX_TICK; /* reset the timer counter */
                this.RaisePropertyChanged("Timer"); /* Trigger Property Changed */

                /* Not a best way of doing */
                _button_letter = QuestionMark;
            });

            this.WhenAny(x => x.Timer, _ => string.Empty).Subscribe( Func =>  {
                if(_timer==0) {
                    SetHangmanImage();
                }
            });

            int CountLetter(char letter)
            {
                int count = 0;
                for (int i = 0; i < hidden_word.Length; i++)
                    if (hidden_word[i] == letter)
                    {
                        ShowHiddenWord(i + 1);
                        _correct_guess++;
                        if (_correct_guess == MAX_COUNT)
                        {
                            Is_Game_Still_Running = false;
                            this.RaisePropertyChanged("Run_Flag");
                        }
                        count++;
                    }
                return count;
            }

        }

        public void SetHangmanImage()
        {

            _hangman_count = ++_hangman_count % 7;
            Hangman_Image = _hangman_count.ToString();
            this.RaisePropertyChanged("Hangman_Image");

            /* increment wrong guess counter
               but not during intialization of button when the letter is question mark */
            if (Hangman_Image != "hangman00")
                _worng_guess++;

            if (_worng_guess == MAX_GUESS)
            {
                _highestscore += _score;
                this.RaisePropertyChanged("HighestScore"); /* Trigger Property Changed */

                _winning_flag = false;
                this.RaisePropertyChanged("IsWinning"); /* Trigger Property Changed */

                Is_Game_Still_Running = false; /* set the flag to start the timer */
                this.RaisePropertyChanged("Run_Flag"); /* Trigger Property Changed */
            }

        }

        public void Reset()
        {
            Is_Game_Still_Running = true;
            this.RaisePropertyChanged("Run_Flag");

            _hangman_count = 0;
            _hangman_image = "hangman00";
            this.RaisePropertyChanged("Hangman_Image");

            _slot01_Image = QuestionMarkImage;
            this.RaisePropertyChanged("Slot01_Image");

            _slot02_Image = QuestionMarkImage;
            this.RaisePropertyChanged("Slot02_Image");

            _slot03_Image = QuestionMarkImage;
            this.RaisePropertyChanged("Slot03_Image");

            _slot04_Image = QuestionMarkImage;
            this.RaisePropertyChanged("Slot04_Image");

            _slot05_Image = QuestionMarkImage;
            this.RaisePropertyChanged("Slot05_Image");

            _score = 0;
            this.RaisePropertyChanged("Score");

            _timer = MAX_TICK;
            this.RaisePropertyChanged("Timer");

            _correct_guess = 0;
            _worng_guess = 0;
            _winning_flag = false;

            GenerateHiddenWord();

            ButtonLetterInitializer();
        }

        private void ShowHiddenWord(int i)
        {
            string getString(char ch) =>  ch.ToString();

            switch (i)
            {
                case 1: Slot01_Image = getString(hidden_word[0]); break;
                case 2: Slot02_Image = getString(hidden_word[1]); break;
                case 3: Slot03_Image = getString(hidden_word[2]); break;
                case 4: Slot04_Image = getString(hidden_word[3]); break;
                case 5: Slot05_Image = getString(hidden_word[4]); break;
            }
        }

        //private void SetTimer()
        //{
        //    /* http://www.introtorx.com/Content/v1.0.10621.0/04_CreatingObservableSequences.html#ObservableTimer  */
        //    var interval = Observable.Interval(TimeSpan.FromMilliseconds(1000));

        //    interval.ObserveOn(Scheduler.TaskPool)
        //        .Subscribe(i => Timer = (i % 10).ToString());
        //}
    }
}


text:
package com.socialize.ui.profile;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import com.socialize.entity.JSONFactory;
import com.socialize.util.BitmapUtils;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * @author Jason Polites
 */
public class UserSettingsFactory extends JSONFactory<UserSettings> {

	public static final String FIRST_NAME = "first_name";
	public static final String LAST_NAME = "last_name";
	public static final String IMAGE_DATA = "picture";
	public static final String AUTO_POST_FACEBOOK = "auto_post_fb";
	public static final String AUTO_POST_TWITTER = "auto_post_tw";
	public static final String NOTIFICATIONS_ENABLED = "notifications_enabled";
	public static final String SHARE_LOCATION = "share_location";
	public static final String SHOW_AUTH = "show_auth_dialog";

	private BitmapUtils bitmapUtils;

	@Override
	public Object instantiateObject(JSONObject object) {
		return new UserSettings();
	}

	@Override
	protected void fromJSON(JSONObject object, UserSettings user) throws JSONException {
		user.setFirstName(getString(object,FIRST_NAME));
		user.setLastName(getString(object,LAST_NAME));
		user.setAutoPostFacebook(getBoolean(object,AUTO_POST_FACEBOOK, false));
		user.setAutoPostTwitter(getBoolean(object,AUTO_POST_TWITTER, false));
		user.setLocationEnabled(getBoolean(object,SHARE_LOCATION, true));
		user.setNotificationsEnabled(getBoolean(object,NOTIFICATIONS_ENABLED, true));
		user.setShowAuthDialog(getBoolean(object,SHOW_AUTH, true));
	}

	@Override
	protected void toJSON(UserSettings user, JSONObject object) throws JSONException {

		String encoded = null;

		try {
			if(user.getImage() != null) {
				encoded = bitmapUtils.encode(user.getImage());
			}
			else if(user.getLocalImagePath() != null) {

				BitmapFactory.Options bfo = new BitmapFactory.Options();
				bfo.inDither = true;
				bfo.inSampleSize = 4;

				Bitmap bm = BitmapFactory.decodeFile(user.getLocalImagePath(), bfo);

				encoded = bitmapUtils.encode(bm);

				bm.recycle();

				user.setLocalImagePath(null);
			}
		}
		catch (Throwable e) {
			// TODO: Handle OOM errors by changing sample size on profile images
			e.printStackTrace();
		}

		object.put(FIRST_NAME, user.getFirstName());
		object.put(LAST_NAME, user.getLastName());

		if(encoded != null) {
			object.put(IMAGE_DATA, encoded);
		}

		object.put(AUTO_POST_FACEBOOK, user.isAutoPostFacebook());
		object.put(AUTO_POST_TWITTER, user.isAutoPostTwitter());
		object.put(SHARE_LOCATION, user.isLocationEnabled());
		object.put(NOTIFICATIONS_ENABLED, user.isNotificationsEnabled());
		object.put(SHOW_AUTH, user.isShowAuthDialog());
	}

	public void setBitmapUtils(BitmapUtils bitmapUtils) {
		this.bitmapUtils = bitmapUtils;
	}
}


text:
import argparse

def parse_args():
  parser = argparse.ArgumentParser(description='Read and write various settings.')
  parser.add_argument('-r', '--revision', dest='revision', type=int, default=3, help='HashFast board major revision number')
  parser.add_argument('-d', '--read-die-settings', dest='read_die_settings', action='store_true', help='read die settings')
  parser.add_argument('-w', '--write-die-settings', dest='write_die_settings', type=str, nargs=4, metavar=('DIE:mVLT@FRQ'), help='write die settings')
  return parser.parse_args()

if __name__ == '__main__':
  # parse args before other imports
  args = parse_args()

import sys
from hf.usb import usbbulk
from hf.load import talkusb
from hf.load.routines import settings

def main(args):
  # query device
  dev = usbbulk.poll_hf_bulk_device()
  print (dev.info())
  print (dev.init())

  # Fix: talkusb patch
  talkusb.epr = dev.epr
  talkusb.epw = dev.epw
  #talkusb.talkusb(hf.INIT, None, 0)

  def printmsg(msg):
    print(msg)

  setter = settings.SettingsRoutine(talkusb.talkusb, 1, printmsg)

  if args.read_die_settings:
    setter.global_state = 'read'
    while setter.one_cycle():
      pass

  if args.write_die_settings is not None:
    if args.revision is 3:
      setter.set_reference(25)
    else:
      setter.set_reference(125)
    die_settings = args.write_die_settings
    for die_setting in die_settings:
      die, setting = die_setting.split(':')
      vlt, frq     = setting.split('@')
      setter.setup(int(die), int(frq), int(vlt))
    while setter.one_cycle():
      pass

if __name__ == "__main__":
   main(args)


text:
import numpy
import theano
from theano.tensor.nnet import conv
from theano.tensor.signal import downsample
import theano.tensor as T

class ConvPoolLayer(object):
    def __init__(self, rng, input, filter_shape, image_shape, poolsize, activation, weights_variance, subsample=(1, 1)):

        assert image_shape[1] == filter_shape[1]

        if activation == 'tanh':
            activation_function = lambda x: T.tanh(x)
            fan_in = numpy.prod(filter_shape[1:])
            fan_out = (filter_shape[0] * numpy.prod(filter_shape[2:]) / numpy.prod(poolsize))
            W_bound = numpy.sqrt(6. / (fan_in + fan_out))
            W_values = numpy.asarray(rng.uniform(low=-W_bound, high=W_bound, size=filter_shape), dtype='float32')
            b_values = numpy.zeros((filter_shape[0],), dtype='float32')

        elif activation == 'relu':
            activation_function = lambda x: T.maximum(0.0, x)
            W_values = numpy.asarray(rng.normal(0.0, weights_variance, size=filter_shape), dtype='float32')
            b_values = numpy.ones((filter_shape[0],), dtype='float32') / 10.0
        else:
            raise ValueError('unknown activation function')

        self.W = theano.shared(value=W_values, name='W', borrow=True)
        self.b = theano.shared(value=b_values, name='b', borrow=True)

        conv_out = conv.conv2d(input, self.W, filter_shape=filter_shape, image_shape=image_shape, subsample=subsample)
        pooled_out = downsample.max_pool_2d(conv_out, poolsize, ignore_border=True) if poolsize > 1 else conv_out
        self.output = activation_function(pooled_out + self.b.dimshuffle('x', 0, 'x', 'x'))
        self.params = [self.W, self.b]


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/edit_dropdown"
    android:layout_width="wrap_content"
    android:layout_height="120dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:layout_gravity="center"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/label_text"
        android:paddingLeft="10dp"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Placeholder" />

    <Spinner
        android:id="@+id/value_spinner"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textAlignment="center"
        android:imeOptions="actionDone" />
    <LinearLayout
        android:id="@+id/LinearLayout02"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:layout_alignParentBottom="true">
    <Button
        android:id="@+id/btn_save"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="center"
        android:imeActionId="1"
        android:text="Save"/>

    <Button
        android:id="@+id/btn_cancel"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="center"
        android:imeActionId="0"
        android:text="Cancel"/>
        </LinearLayout>
</LinearLayout>


text:
Android-Bootstrap
=================
Android Bootstrap is an Android library which provides custom views styled according to the
 [Twitter Bootstrap Specification](http://getbootstrap.com/). This allows you to spend more time
  on development rather than trying to get a consistent theme across your app, especially if you are already familiar with the Bootstrap Framework.

Quick Start
===========
 [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.beardedhen/androidbootstrap/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.beardedhen/androidbootstrap)
 [![CircleCI](https://circleci.com/gh/Bearded-Hen/Android-Bootstrap/tree/develop.svg?style=shield)](https://circleci.com/gh/Bearded-Hen/Android-Bootstrap/tree/develop)

 Add the following dependency to your build.gradle, ensuring you replace 'X.X.X' with the latest version on the button above:

 ```java
 dependencies {
    compile 'com.beardedhen:androidbootstrap:{X.X.X}'
 }
 ```

 You should also override your application class with the following:

 ```java
 public class SampleApplication extends Application {
     @Override public void onCreate() {
         super.onCreate();
         TypefaceProvider.registerDefaultIconSets();
     }
 }
 ```

 You should then checkout the library and investigate the sample code, which covers most of the features.
 The sample app is also available on [Google Play](https://play.google.com/store/apps/details?id=com.fractalwrench.androidbootstrap.sample).

Support
==============
If you have a question about how to use the project, please ask a question on [StackOverflow](http://stackoverflow.com/questions/tagged/android-bootstrap-widgets), using the tag **android-bootstrap-widgets**.

If you think you have found a bug in the library, you should [create a new issue](https://github.com/Bearded-Hen/Android-Bootstrap/issues/new) instead.

Javadoc
============
The javadoc for the project is hosted on [Github](http://bearded-hen.github.io/Android-Bootstrap/).

Examples
============

### BootstrapButton
A button that supports Glyph icons, and is themeable using Bootstrap Brands.
   ```xml
<com.beardedhen.androidbootstrap.BootstrapButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="BootstrapButton"
    app:bootstrapBrand="success"
    app:bootstrapSize="lg"
    app:buttonMode="regular"
    app:showOutline="false"
    app:roundedCorners="true"
    />
```

###BootstrapButtonGroup
Allows BootstrapButtons to be grouped together and their attributes controlled en masse.
   ```xml
<com.beardedhen.androidbootstrap.BootstrapButtonGroup
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="BootstrapButtonGroup"
    android:orientation="vertical"
    app:bootstrapBrand="success"
    app:bootstrapSize="lg"
    app:roundedCorners="true"
    >
    <com.beardedhen.androidbootstrap.BootstrapButton
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="BootstrapButton 1"
       />
    <com.beardedhen.androidbootstrap.BootstrapButton
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="BootstrapButton 2"
       />
</com.beardedhen.androidbootstrap.BootstrapButtonGroup>
```

### AwesomeTextView
A text widget that displays Glyph icons, and is themeable using Bootstrap Brands.
   ```xml
<com.beardedhen.androidbootstrap.AwesomeTextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:bootstrapBrand="success"
    app:fontAwesomeIcon="fa_android"
    />
```

###BootstrapProgressBar
Displays progress in a bar from 0-100, and animates updates to the current progress.
   ```xml
<com.beardedhen.androidbootstrap.BootstrapProgressBar
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:animated="true"
    app:bootstrapBrand="warning"
    app:progress="78"
    app:striped="true"
    />
```

### BootstrapProgressBarGroup
Allows BootstrapProgressBars to be group together to have the effect of stacked progress bar.
   ```xml
        <com.beardedhen.androidbootstrap.BootstrapProgressBarGroup
            android:id="@+id/example_progress_bar_group_round_group"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            app:bootstrapSize="md"
            app:bootstrapMaxProgress="100">

            <com.beardedhen.androidbootstrap.BootstrapProgressBar
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                app:bootstrapBrand="success"
                app:bootstrapProgress="20"
                />

            <com.beardedhen.androidbootstrap.BootstrapProgressBar
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                app:bootstrapBrand="danger"
                app:bootstrapProgress="20"
                />

            </com.beardedhen.androidbootstrap.BootstrapProgressBarGroup>
```

###BootstrapLabel
Displays non-clickable text in a widget similar to the BootstrapButton, sizable using H1-H6 elements.
   ```xml
<com.beardedhen.androidbootstrap.BootstrapLabel
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:bootstrapBrand="primary"
    app:bootstrapHeading="h3"
    app:roundedCorners="true"
    android:text="Bootstrap Label"
    />
```

### BootstrapEditText
Allows editing of text in a widget themed using BootstrapBrand.
   ```xml
<com.beardedhen.androidbootstrap.BootstrapEditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:bootstrapSize="md"
    app:bootstrapBrand="info"
    />
```

###BootstrapCircleThumbnail
Displays images in a center-cropped Circular View, themed with BootstrapBrand.
   ```xml
<com.beardedhen.androidbootstrap.BootstrapCircleThumbnail
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/my_drawable"
    app:bootstrapBrand="danger"
    app:hasBorder="true"
    />
```

### BootstrapThumbnail
Displays images in a rectangular View, themed with BootstrapBrand.
   ```xml
<com.beardedhen.androidbootstrap.BootstrapThumbnail
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/my_drawable"
    app:bootstrapBrand="info"
    app:hasBorder="true"
    />
```

###BootstrapWell
Displays a view in a themed container.

```xml
<com.beardedhen.androidbootstrap.BootstrapWell
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="8dp"
        app:bootstrapSize="xl">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:text="Look, I'm in a large well!"
            />
    </com.beardedhen.androidbootstrap.BootstrapWell>
```

###BootstrapDropDown
Displays a view with dropdown options, supplied by an array of strings.

```xml
<com.beardedhen.androidbootstrap.BootstrapDropDown
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="8dp"
                app:bootstrapText="Medium {fa_thumbs_o_up}"
                app:bootstrapBrand="regular"
                app:roundedCorners="true"
                app:bootstrapSize="md"
                app:dropdownResource="@array/bootstrap_dropdown_example_data"
                app:bootstrapExpandDirection="down"/>
```

 Custom Styles
============
Custom styles can be applied to any of the views in this library by creating a class which implements
BootstrapBrand, and setting it on the View. Please see the sample code of BootstrapButton for more detail.

 ```java

     class CustomBootstrapStyle implements BootstrapBrand {
         // specify desired colors here
     }

     BootstrapButton btn = new BootstrapButton(context);
     btn.setBootstrapBrand(new CustomBootstrapStyle(this);
 ```

Contributing
============
Contributions are very welcome! There are 3 main ways you can help out:

1. Add more Icon Typefaces, using the instructions [here](https://github.com/Bearded-Hen/Android-Bootstrap/blob/master/ADD_FONT.md)
2. Help implement views which are present in the  [Twitter Bootstrap Specification](http://getbootstrap.com/) but are not yet in this library.
3. Raise an issue if you see a bug or are unsure on how something works, or even better - send a pull-request with a fix!

Versioning
==========
This project uses [Semantic Versioning](http://semver.org/). There are several breaking changes in V2.X of the library, including:

- AwesomeTextView replaces FontAwesomeText
- Various altered method signatures/attributes for views
- Global BootstrapBrand/BootstrapSize attributes replace view-specific enums

Please consider what effect these changes might have on your app before upgrading!

Contact
=======
If you have any questions, issues, or just want to let us know where you're using Android Bootstrap
 tweet us at [@BeardedHen](https://twitter.com/beardedhen), email support@beardedhen.com,
  or head over to our [website](http://beardedhen.com/) to see more of our creations.

Hall of Fame
======
Checkout [AppBrain](http://www.appbrain.com/stats/libraries/details/androidbootstrap/android-bootstrap) to see some of the apps which use Android Bootstrap!


text:
namespace Incoding.MvcContrib.MVD
{
    #region << Using >>

    using System.Text;
    using System.Web;
    using System.Web.Routing;
    using Incoding.CQRS;
    using Incoding.Extensions;

    #endregion

    public class QueryHttpHandler : IHttpHandler
    {
        public class QueryHandlerRoute : IRouteHandler
        {
            public IHttpHandler GetHttpHandler(RequestContext requestContext)
            {
                return new QueryHttpHandler();
            }
        }

        #region IHttpHandler Members

        public void ProcessRequest(HttpContext context)
        {
            var dispatcher = new DefaultDispatcher();
            var parameter = dispatcher.Query(new GetMvdParameterQuery()
                                             {
                                                     Params = context.Request.Params
                                             });
            context.Response.ContentType = "application/json";
            context.Response.ContentEncoding = Encoding.UTF8;
            var instanceForQuery = dispatcher.Query(new CreateByTypeQuery() { Type = parameter.Type });
            context.Response.Write(IncodingResult.Success(dispatcher.Query(new MVDExecute(new HttpContextWrapper(context)) { Instance = new CommandComposite((IMessage)instanceForQuery) })).ToJsonString());
        }

        public bool IsReusable { get { return false; } }

        public static readonly IRouteHandler Route = new QueryHandlerRoute();

        #endregion
    }
}


text:
package org.apache.wicket.markup.html.form;

import org.apache.wicket.core.util.string.CssUtils;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.parser.XmlTag.TagType;
import org.apache.wicket.util.lang.Args;

/**
 * A component that represents HTML  tag. This component will automatically make the
 * form component output an id attribute and link its for attribute with that
 * value.
 *
 * @author Igor Vaynberg (ivaynberg)
 */
public class FormComponentLabel extends WebMarkupContainer
{
	private static final long serialVersionUID = 1L;

	public static final String REQUIRED_CSS_CLASS_KEY = CssUtils.key(FormComponentLabel.class,
			"required");

	public static final String INVALID_CSS_CLASS_KEY = CssUtils.key(FormComponentLabel.class,
			"invalid");

	public static final String DISABLED_CSS_CLASS_KEY = CssUtils.key(FormComponentLabel.class,
			"disabled");

	private final LabeledWebMarkupContainer component;

	/**
	 * Constructor
	 *
	 * @param id
	 *            component id
	 * @param component
	 *            component that this label is linked to
	 */
	public FormComponentLabel(String id, LabeledWebMarkupContainer component)
	{
		super(id);

		this.component = Args.notNull(component, "component");
		component.setOutputMarkupId(true);
	}

	/**
	 *
	 * @see org.apache.wicket.Component#onComponentTag(org.apache.wicket.markup.ComponentTag)
	 */
	@Override
	protected void onComponentTag(ComponentTag tag)
	{
		super.onComponentTag(tag);

		checkComponentTag(tag, "label");

		LabeledWebMarkupContainer formComponent = getFormComponent();

		tag.put("for", formComponent.getMarkupId());

		if (formComponent instanceof FormComponent<?>)
		{
			FormComponent<?> fc = (FormComponent<?>) formComponent;

			if (fc.isRequired())
			{
				tag.append("class", getString(REQUIRED_CSS_CLASS_KEY), " ");
			}
			if (fc.isValid() == false)
			{
				tag.append("class", getString(INVALID_CSS_CLASS_KEY), " ");
			}
		}

		if (formComponent.isEnabledInHierarchy() == false)
		{
			tag.append("class", getString(DISABLED_CSS_CLASS_KEY), " ");
		}

		// always transform the tag to  so even labels defined as  render
		tag.setType(TagType.OPEN);
	}

	/**
	 * Returns LabeledWebMarkupContainer bound to this label. This will be a FormComponent, a Radio
	 * or a Check.
	 *
	 * @return form component
	 */
	public LabeledWebMarkupContainer getFormComponent()
	{
		return component;
	}
}


text:
package com.bootdo.finance.controller;

import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bootdo.finance.domain.FxActiveDO;
import com.bootdo.finance.service.FxActiveService;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;

/**
 * 活动
 *
 * @author chglee
 * @email 1992lcg@163.com
 * @date 2017-09-16 17:14:55
 */
@Controller
@RequestMapping("/finance/fxActive")
public class FxActiveController {
	@Autowired
	private FxActiveService fxActiveService;

	@GetMapping()
//	@RequiresPermissions("blog:fxActive")
	String FxActive(){
	    return "finance/fxActive/fxActive";
	}

	@ResponseBody
	@GetMapping("/list")
//	@RequiresPermissions("blog:list")
	public PageUtils list(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);
		List<FxActiveDO> fxActiveList = fxActiveService.list(query);
		int total = fxActiveService.count(query);
		PageUtils pageUtils = new PageUtils(fxActiveList, total);
		return pageUtils;
	}

	@GetMapping("/add")
	//@RequiresPermissions("blog:bComments")
	String add(){
	    return "finance/fxActive/add";
	}
	@GetMapping("/edit")
	//@RequiresPermissions("blog:bComments")
	String edit(Long id,ModelMap model){
		FxActiveDO fxActive = fxActiveService.get(id);
		model.addAttribute("FxActive", fxActive);
	    return "finance/fxActive/edit";
	}
	/**
	 * 信息
	 */
	@RequestMapping("/info/{id}")
	@RequiresPermissions("blog:info")
	public R info(@PathVariable("id") Long id){
		FxActiveDO fxActive = fxActiveService.get(id);
		return R.ok().put("fxActive", fxActive);
	}

	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("finance:save")
	public R save( FxActiveDO fxActive){
		if(fxActiveService.save(fxActive)>0){
			return R.ok();
		}
		return R.error();
	}

	/**
	 * 修改
	 */
	@RequestMapping("/update")
	@RequiresPermissions("finance:update")
	public R update(@RequestBody FxActiveDO fxActive){
		fxActiveService.update(fxActive);

		return R.ok();
	}

	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("blog:remove")
	public R remove( Long id){
		if(fxActiveService.remove(id)>0){
		return R.ok();
		}
		return R.error();
	}

	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("finance:remove")
	public R remove(@RequestParam("ids[]") Long[] ids){
		fxActiveService.batchRemove(ids);

		return R.ok();
	}

}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/news_activity_fragment_id"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="16dp"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="famaf.unc.edu.ar.activitiesassignment.ar.edu.unc.famaf.redditreader.NewsActivityFragment"
    tools:showIn="@layout/activity_news">

    <ListView
        android:id="@+id/postsLV"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        />

    <TextView
        android:id="@+id/loginStatusTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="No user logged yet"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"

        />

</RelativeLayout>


text:
namespace Microsoft.Azure.Batch.Protocol.Models
{
    using System.Linq;

    /// <summary>
    /// Information about a task running on a compute node.
    /// </summary>
    public partial class TaskInformation
    {
        /// <summary>
        /// Initializes a new instance of the TaskInformation class.
        /// </summary>
        public TaskInformation() { }

        /// <summary>
        /// Initializes a new instance of the TaskInformation class.
        /// </summary>
        /// <param name="taskState">The current state of the task.</param>
        /// <param name="taskUrl">The URL of the task.</param>
        /// <param name="jobId">The id of the job to which the task
        /// belongs.</param>
        /// <param name="taskId">The id of the task.</param>
        /// <param name="subtaskId">The id of the subtask if the task is a
        /// multi-instance task.</param>
        /// <param name="executionInfo">Information about the execution of the
        /// task.</param>
        public TaskInformation(TaskState taskState, string taskUrl = default(string), string jobId = default(string), string taskId = default(string), int? subtaskId = default(int?), TaskExecutionInformation executionInfo = default(TaskExecutionInformation))
        {
            TaskUrl = taskUrl;
            JobId = jobId;
            TaskId = taskId;
            SubtaskId = subtaskId;
            TaskState = taskState;
            ExecutionInfo = executionInfo;
        }

        /// <summary>
        /// Gets or sets the URL of the task.
        /// </summary>
        [Newtonsoft.Json.JsonProperty(PropertyName = "taskUrl")]
        public string TaskUrl { get; set; }

        /// <summary>
        /// Gets or sets the id of the job to which the task belongs.
        /// </summary>
        [Newtonsoft.Json.JsonProperty(PropertyName = "jobId")]
        public string JobId { get; set; }

        /// <summary>
        /// Gets or sets the id of the task.
        /// </summary>
        [Newtonsoft.Json.JsonProperty(PropertyName = "taskId")]
        public string TaskId { get; set; }

        /// <summary>
        /// Gets or sets the id of the subtask if the task is a multi-instance
        /// task.
        /// </summary>
        [Newtonsoft.Json.JsonProperty(PropertyName = "subtaskId")]
        public int? SubtaskId { get; set; }

        /// <summary>
        /// Gets or sets the current state of the task.
        /// </summary>
        /// <remarks>
        /// Possible values include: 'active', 'preparing', 'running',
        /// 'completed'
        /// </remarks>
        [Newtonsoft.Json.JsonProperty(PropertyName = "taskState")]
        public TaskState TaskState { get; set; }

        /// <summary>
        /// Gets or sets information about the execution of the task.
        /// </summary>
        [Newtonsoft.Json.JsonProperty(PropertyName = "executionInfo")]
        public TaskExecutionInformation ExecutionInfo { get; set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public virtual void Validate()
        {
            if (this.ExecutionInfo != null)
            {
                this.ExecutionInfo.Validate();
            }
        }
    }
}


text:
This folder contains a script and settings to generate ICs for the Price &
Laibe (2015) dust settling test.  Running the tests will generate them in
sub-folders

Files:
* make_price_laibe.py
    * Script to generate the ICs.

* settings_cubic_grid.py
  settings_glass.py
  settings_hexagonal.py
    * Settings files For IC generation


text:
//--------------------------------------------------------------------------
//
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//
//  File: PlinqExtensions.cs
//
//--------------------------------------------------------------------------

using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace System.Linq
{
    /// Extension methods for Parallel LINQ.
    public static class ParallelLinqExtensions
    {
        /// Takes the top elements as if they were sorted.
        /// <typeparam name="TSource">Specifies the type of the elements.</typeparam>
        /// <typeparam name="TKey">Specifies the type of the keys used to compare elements.</typeparam>
        /// <param name="source">The source elements.</param>
        /// <param name="keySelector">A function used to extract a key from each element.</param>
        /// <param name="count">The number of elements to take.</param>
        /// <returns></returns>
        public static IEnumerable<TSource> TakeTop<TSource, TKey>(this ParallelQuery<TSource> source,
            Func<TSource, TKey> keySelector,
            int count)
        {
            // We want to sort in descending order, so we need the opposite of the default comparer
            var comparer = new DescendingDefaultComparer<TKey>();

            // Aggregate, using a sorted list per thread to keep track of the best N elements,
            // then merge those at the end.
            return source.Aggregate(
                () => new SortedTopN<TKey, TSource>(count, comparer),

                (accum, item) =>
                {
                    accum.Add(keySelector(item), item);
                    return accum;
                },

                (accum1, accum2) =>
                {
                    foreach (var item in accum2) accum1.Add(item);
                    return accum1;
                },

                (accum) => accum.Values);
        }

        /// A comparer that comparers using the inverse of the default comparer.
        /// <typeparam name="T">Specifies the type being compared.</typeparam>
        private class DescendingDefaultComparer<T> : IComparer<T>
        {
            private static Comparer<T> _defaultComparer = Comparer<T>.Default;
            public int Compare(T x, T y) { return _defaultComparer.Compare(y, x); }
        }

        /// Implements a map-reduce operation.
        /// <typeparam name="TSource">Specifies the type of the source elements.</typeparam>
        /// <typeparam name="TMapped">Specifies the type of the mapped elements.</typeparam>
        /// <typeparam name="TKey">Specifies the type of the element keys.</typeparam>
        /// <typeparam name="TResult">Specifies the type of the results.</typeparam>
        /// <param name="source">The source elements.</param>
        /// <param name="map">A function used to get the target data from a source element.</param>
        /// <param name="keySelector">A function used to get a key from the target data.</param>
        /// <param name="reduce">A function used to reduce a group of elements.</param>
        /// <returns>The result elements of the reductions.</returns>
        public static ParallelQuery<TResult> MapReduce<TSource, TMapped, TKey, TResult>(
            this ParallelQuery<TSource> source,
            Func<TSource, TMapped> map,
            Func<TMapped, TKey> keySelector,
            Func<IGrouping<TKey, TMapped>, TResult> reduce)
        {
            return source.
                Select(map).
                GroupBy(keySelector).
                Select(reduce);
        }

        /// Implements a map-reduce operation.
        /// <typeparam name="TSource">Specifies the type of the source elements.</typeparam>
        /// <typeparam name="TMapped">Specifies the type of the mapped elements.</typeparam>
        /// <typeparam name="TKey">Specifies the type of the element keys.</typeparam>
        /// <typeparam name="TResult">Specifies the type of the results.</typeparam>
        /// <param name="source">The source elements.</param>
        /// <param name="map">A function used to get an enumerable of target data from a source element.</param>
        /// <param name="keySelector">A function used to get a key from target data.</param>
        /// <param name="reduce">A function used to reduce a group of elements to an enumerable of results.</param>
        /// <returns>The result elements of the reductions.</returns>
        public static ParallelQuery<TResult> MapReduce<TSource, TMapped, TKey, TResult>(
            this ParallelQuery<TSource> source,
            Func<TSource, IEnumerable<TMapped>> map,
            Func<TMapped, TKey> keySelector,
            Func<IGrouping<TKey, TMapped>, IEnumerable<TResult>> reduce)
        {
            return source.
                SelectMany(map).
                GroupBy(keySelector).
                SelectMany(reduce);
        }

        /// Runs the query and outputs its results into the target collection.
        /// <typeparam name="TSource">Specifies the type of elements output from the query.</typeparam>
        /// <param name="source">The source query.</param>
        /// <param name="target">The target collection.</param>
        public static void OutputToProducerConsumerCollection<TSource>(
            this ParallelQuery<TSource> source,
            IProducerConsumerCollection<TSource> target)
        {
            // Validate arguments
            if (source == null) throw new ArgumentNullException("source");
            if (target == null) throw new ArgumentNullException("target");

            // Store all results into the collection
            source.ForAll(item => target.TryAdd(item));
        }

        /// This is the method to opt into Parallel LINQ.
        /// <typeparam name="TSource">Specifies the type of elements provided to the query.</typeparam>
        /// <param name="source">The source query.</param>
        /// <param name="parallelOptions">The options to use for query processing.</param>
        /// <returns>The source as a ParallelQuery to bind to ParallelEnumerable extension methods.</returns>
        public static ParallelQuery<TSource> AsParallel<TSource>(
            this IEnumerable<TSource> source,
            ParallelLinqOptions parallelOptions)
        {
            if (source == null) throw new ArgumentNullException("source");

            // Validate unsupported options
            if (parallelOptions.TaskScheduler != null && parallelOptions.TaskScheduler != TaskScheduler.Default)
            {
                throw new ArgumentException("Parallel LINQ only supports the default TaskScheduler.");
            }

            // First convert to PLINQ
            var result = source.AsParallel();

            // Then apply all of the options as requested...
            if (parallelOptions.Ordered)
            {
                result = result.AsOrdered();
            }
            if (parallelOptions.CancellationToken.CanBeCanceled)
            {
                result = result.WithCancellation(parallelOptions.CancellationToken);
            }
            if (parallelOptions.MaxDegreeOfParallelism >= 1)
            {
                result = result.WithDegreeOfParallelism(parallelOptions.MaxDegreeOfParallelism);
            }
            if (parallelOptions.ExecutionMode != ParallelExecutionMode.Default)
            {
                result = result.WithExecutionMode(parallelOptions.ExecutionMode);
            }
            if (parallelOptions.MergeOptions != ParallelMergeOptions.Default)
            {
                result = result.WithMergeOptions(parallelOptions.MergeOptions);
            }
            return result;
        }
    }
}


text:
var THREE = require('three');
var Iconeezin = require('iconeezin');

var MonumentRoom = function( geom, materials ) {
	THREE.Object3D.call(this);

	this.kionokranoMesh = geom['delay/models/kionokrano'];
	this.podiumObject = geom['delay/models/podium'];

	// Prepare materials
	this.wallsMaterial = materials.wallsMaterial;
	this.ceilingMaterial = materials.ceilingMaterial;
	this.floorMaterial = materials.floorMaterial;
	this.pillarMaterial = materials.pillarMaterial;
	this.kionokranoMaterial = materials.kionokranoMaterial;
	this.frameMaterial = materials.frameMaterial;
	this.podiumMaterial = materials.podiumMaterial;
	this.doorMaterial = materials.doorMaterial;
	this.doorFrameMaterial = materials.doorFrameMaterial;

	// Create a podium material
	var canvas = document.createElement('canvas');
	canvas.width = 2048;
	canvas.height = 1024;

	// Create texture & get context handler
	this.podiumMessageCtx = canvas.getContext('2d');
	this.podiumMessageTexture = new THREE.Texture(canvas);
	this.podiumMessageLines = [];
	this.podiumMessageProgress = 0;

	// Create message material
	this.podiummessageMaterial = new THREE.MeshBasicMaterial({
	    map: this.podiumMessageTexture,
	    transparent: false,
	    color: 0xffffff
	});

	// Local properties
	this.pathEnter = null;
	this.pathLeave = null;
	this.length = 0;

	// this.lightA = new THREE.PointLight(0xffffff, 0.25);
	// this.lightA.castShadow = true;
	// this.lightB = new THREE.PointLight(0xffffff, 0.25);
	// this.lightB.castShadow = true;

};

MonumentRoom.prototype = Object.assign(Object.create(THREE.Object3D.prototype), {
	constructor: MonumentRoom,

	setupMataerials: function() {

	},

	/**
	 * Redraw the podium message
	 */
	redrawPodiumMessage: function() {
		var ovd = 25,
			ctx = this.podiumMessageCtx,
			l1 = this.podiumMessageLines[0] || "",
			l2 = this.podiumMessageLines[1] || "",
			l3 = this.podiumMessageLines[2] || "",
			l4 = this.podiumMessageLines[3] || "",
			chars = l1.length + l2.length + l3.length + l4.length;

		ctx.fillStyle = "#000000";
		ctx.fillRect(0, 0, 2048, 1024);
		ctx.globalCompositeOperation = "source-over";

		// Draw message
		ctx.textAlign = "center";
		ctx.font="bold 110px Tahoma";
		ctx.fillStyle = "#ffffff";
		ctx.fillText( l1, 1024, 366 );
		ctx.fillText( l2, 1024, 498 );
		ctx.fillText( l3, 1024, 631 );
		ctx.fillText( l4, 1024, 763 );

		// Draw progress
		ctx.globalCompositeOperation = "multiply";
		ctx.fillStyle = "#ff0000";
		var p_chars = Math.round(this.podiumMessageProgress * chars),
			steps = [ [l1.length,ctx.measureText(l1).width,253],
					  [l2.length,ctx.measureText(l2).width,385],
					  [l3.length,ctx.measureText(l3).width,518],
					  [l4.length,ctx.measureText(l4).width,650] ];
		for (var i=0; i<4; i++) {
			if (p_chars <= 0) break;
			var c = steps[i][0], tW = steps[i][1], y = steps[i][2], w = tW;
			if (p_chars < c) tW *= p_chars / c;
			p_chars -= c;

			// Draw progress overlay
			ctx.fillRect( 1024-w/2-ovd,y-ovd,tW+ovd*2,113+ovd*2 );
		}

		this.podiumMessageTexture.needsUpdate = true;
	},

	/**
	 * Update the podium message
	 */
	setPodiumMessage: function( lines ) {
		this.podiumMessageLines = lines;
		this.podiumMessageProgress = 0;
		this.redrawPodiumMessage();
	},

	/**
	 * Update podium message progress
	 */
	setPodiumMessageProgress: function( progress ) {
		this.podiumMessageProgress = progress;
		this.redrawPodiumMessage();
	},

	/**
	 * Rebuild monument room with the given scale
	 */
	rebuild: function( scale ) {
		var pillarHeight = 5,
			frameHeight = 0.25,
			innerPadding = 1,
			height = (pillarHeight + frameHeight) * scale,
			length = 10 * scale,
			width = 6 * scale,
			innerLength = length - innerPadding*2,
			innerWidth = width - innerPadding*2;

		// Reset
		this.reset();

		// Create wall box
		this.addWalls( length, width, height, scale );

		// Create side pillars
		var lPillars = Math.round(innerLength / 4),
			sPillars = innerLength / lPillars,
			xLeft = -(innerWidth/2), xRight = (innerWidth/2);
		for (var i=0, y=1; i<=lPillars; i++, y+=sPillars) {
			this.addPillars( xLeft, y, pillarHeight, frameHeight, scale );
			this.addPillars( xRight, y, pillarHeight, frameHeight, scale );
		}

		// Create front pillars
		if (scale >= 2) {
			var wPillars = 2 * scale,
				wsPillars = innerWidth / wPillars;
			for (var i=0, x=xLeft+wsPillars; i<wPillars-1; i++, x+=wsPillars) {
				if (i == (wPillars-2)/2) continue; // Gap in the middle
				this.addPillars( x, innerPadding, pillarHeight, frameHeight, scale );
				this.addPillars( x, innerLength+innerPadding, pillarHeight, frameHeight, scale );
			}
		}

		// Add junction frames
		this.addJunctionFrames( innerLength, innerWidth, innerPadding,
								pillarHeight + frameHeight, frameHeight, scale );

		// Put a new podium in the middle
		var podium = this.podiumObject.clone();
		podium.position.set( 0,innerLength/2+innerPadding,0 );
		podium.children[0].material = this.podiumMaterial;
		podium.children[1].material = this.podiummessageMaterial;
		this.add(podium);

		// Prepare the enter and leave paths
		this.pathEnter = new THREE.CubicBezierCurve3(
			new THREE.Vector3( 0.0000, 1.00000, 0 ),
			new THREE.Vector3( 0.0000, 2.00000, 0 ),
			new THREE.Vector3( 0.0000, podium.position.y-3, 0.0 ),
			new THREE.Vector3( 0.0000, podium.position.y-2, 0.0 )
		);
		this.pathLeave = new THREE.CubicBezierCurve3(
			new THREE.Vector3( 0.0000, podium.position.y-2, 0.0 ),
			new THREE.Vector3( -4.0, podium.position.y+length/5, 0.0 ),
			new THREE.Vector3( 0.0000, length-7, 0.0 ),
			new THREE.Vector3( 0.0000, length, 0.0 )
		);

		// Keep properties
		this.length = length;

		// Update lights
		// this.lightA.position.set(
		// 		0, 2/5*length, height/2
		// 	);
		// this.lightB.position.set(
		// 		0, 3/5*length, height/2
		// 	);

		// this.traverse(function(o) {
		// 	o.castShadow = true;
		// 	o.receiveShadow = true;
		// });

	},

	/**
	 * Remove all children
	 */
	reset: function() {

		// Dispatch all children
		for (var i=0; i<this.children.length; i++) {
			this.children[i].parent = null;
			this.children[i].dispatchEvent( { type: 'removed' } );
		}

		// Dispose all geometries
		this.traverse(function(obj) {
			if (obj instanceof THREE.Mesh) {
				obj.geometry.dispose();
			}
		});
		this.children = [];

	},

	addWalls: function( length, width, height, scale ) {

		var doorWidth = 2,
			doorHeight = 3,
			doorFrame = 0.15;

		//
		// Create geometry for the doored walls
		//
		var doorWallGeom = new THREE.Geometry();
		doorWallGeom.vertices.push(
			new THREE.Vector3( -width/2, 0, height ),
			new THREE.Vector3(  width/2, 0, height ),
			new THREE.Vector3( -width/2, 0, 0 ),
			new THREE.Vector3(  width/2, 0, 0 ),
			new THREE.Vector3( -width/2, 0, doorHeight ),
			new THREE.Vector3(  width/2, 0, doorHeight ),
			new THREE.Vector3( -doorWidth/2, 0, doorHeight ),
			new THREE.Vector3(  doorWidth/2, 0, doorHeight ),
			new THREE.Vector3( -doorWidth/2, 0, 0 ),
			new THREE.Vector3(  doorWidth/2, 0, 0 )
		);
		doorWallGeom.faces.push(
			new THREE.Face3( 0, 4, 5 ),
			new THREE.Face3( 5, 1, 0 ),
			new THREE.Face3( 4, 2, 8 ),
			new THREE.Face3( 4, 8, 6 ),
			new THREE.Face3( 7, 9, 3 ),
			new THREE.Face3( 7, 3, 5 )
		);

		// Generate UVs
		var tX = scale * 2, tY = scale * 2,
			dY = (1- (doorHeight / height)),
			dX = (doorWidth / width),
			fvUVs = [],
			uvs = [ // Vertex UVs
				new THREE.Vector2( 0, 0 ),
				new THREE.Vector2( tX, 0 ),
				new THREE.Vector2( 0, tY ),
				new THREE.Vector2( tX, tY ),
				new THREE.Vector2( 0, dY*tY ),
				new THREE.Vector2( tX, dY*tY ),
				new THREE.Vector2( (0.5 - dX)*tX, dY*tY ),
				new THREE.Vector2( (0.5 + dX)*tX, dY*tY ),
				new THREE.Vector2( (0.5 - dX)*tX, tY ),
				new THREE.Vector2( (0.5 + dX)*tX, tY )
			];
		for (var i=0; i<doorWallGeom.faces.length; ++i) {
			fvUVs.push([
					uvs[ doorWallGeom.faces[i].a ],
					uvs[ doorWallGeom.faces[i].b ],
					uvs[ doorWallGeom.faces[i].c ]
			]);
		}

		// Compute face normals
		doorWallGeom.faceVertexUvs = [ fvUVs ];
		doorWallGeom.uvsNeedUpdate = true;
		doorWallGeom.computeFaceNormals();

		//
		// Create side walls
		//
		var wTx = 4 * scale, wTy = 4 * scale;
		var sideGeometry = new THREE.PlaneBufferGeometry( width, length, 1, 1 );
		var attrib = sideGeometry.getAttribute('uv');
		attrib.needsUpdate = true;
		attrib.array.set([
			0, wTy,
			wTx, wTy,
			0, 0,
			wTx, 0
		]);

		var wallLeft = new THREE.Mesh( sideGeometry, this.wallsMaterial );
		var wallRight = new THREE.Mesh( sideGeometry, this.wallsMaterial );

		wallLeft.rotation.set( Math.PI/2, -Math.PI/2, Math.PI/2 );
		wallLeft.position.set( -width/2, length/2, height/2 );
		wallRight.rotation.set( Math.PI/2, Math.PI/2, Math.PI/2 );
		wallRight.position.set( width/2, length/2, height/2 );

		wallLeft.castShadow = true;
		wallRight.castShadow = true;

		this.add(wallLeft);
		this.add(wallRight);

		//
		// Create near and far walls
		//
		var wallNear = new THREE.Mesh( doorWallGeom, this.wallsMaterial );
		var wallFar = new THREE.Mesh( doorWallGeom, this.wallsMaterial );

		wallNear.position.set( 0, 0, 0 );
		wallFar.position.set( 0, length, 0 );
		wallFar.rotation.set( 0, 0, Math.PI );

		wallNear.castShadow = true;
		wallFar.castShadow = true;

		this.add(wallNear);
		this.add(wallFar);

		//
		// Create the top and bottom planes for rendering ceiling and floor
		//
		var cftX = 2 * scale, cftY = 3 * scale;
		var planeGeom = new THREE.PlaneBufferGeometry( width, length, 1, 1 );
		var attrib = planeGeom.getAttribute('uv');
		attrib.needsUpdate = true;
		attrib.array.set([
			0, cftY,
			cftX, cftY,
			0, 0,
			cftX, 0
		]);

		var topPlaneMesh = new THREE.Mesh( planeGeom, this.ceilingMaterial );
		var botPlaneMesh = new THREE.Mesh( planeGeom, this.floorMaterial );

		topPlaneMesh.position.set( 0, length/2, height );
		topPlaneMesh.rotation.set( Math.PI, 0, 0 );
		this.add(topPlaneMesh);

		botPlaneMesh.position.set( 0, length/2, 0 );
		botPlaneMesh.receiveShadow = true;
		this.add(botPlaneMesh);

		//
		// Create door hinges
		//
		this.doorLPivot = new THREE.Object3D();
		this.doorRPivot = new THREE.Object3D();
		this.doorLPivot.position.set( -doorWidth/2, length, 0 );
		this.doorRPivot.position.set(  doorWidth/2, length, 0 );
		this.add(this.doorLPivot);
		this.add(this.doorRPivot);

		this.doorLPivot.rotation.set( 0, 0, 0 );
		this.doorRPivot.rotation.set( 0, 0, -Math.PI );

		//
		// Create door sides
		//
		var doorGeometry = new THREE.BoxGeometry( doorWidth/2, 0.1, doorHeight );
		var doorL = new THREE.Mesh( doorGeometry, this.doorMaterial );
		var doorR = new THREE.Mesh( doorGeometry, this.doorMaterial );

		doorL.position.set( doorWidth/4, -0.05, doorHeight/2 );
		doorR.position.set( doorWidth/4,  0.05, doorHeight/2 );

		this.doorLPivot.add( doorL );
		this.doorRPivot.add( doorR );

		//
		// Create door frames
		//
		var vFrameGeometry = new THREE.BoxGeometry( doorFrame, doorFrame, doorHeight+doorFrame );
		var hFrameGeometry = new THREE.BoxGeometry( doorWidth+2*doorFrame, doorFrame, doorFrame );
		var lFrame = new THREE.Mesh( vFrameGeometry, this.doorFrameMaterial );
		var rFrame = new THREE.Mesh( vFrameGeometry, this.doorFrameMaterial );
		var tFrame = new THREE.Mesh( hFrameGeometry, this.doorFrameMaterial );

		lFrame.position.set( -doorWidth/2-doorFrame/2, length, doorHeight/2 );
		rFrame.position.set(  doorWidth/2+doorFrame/2, length, doorHeight/2 );
		tFrame.position.set(  0, length, doorHeight );

		this.add( lFrame );
		this.add( rFrame );
		this.add( tFrame );

	},

	addPillars: function( x,y,height,spacing,repeats ) {
		var z = 0, step = height + spacing;
		for (var i=0; i<repeats; i++, z += step) {
			this.addPillar(x,y,z,height);
		}
	},

	addPillar: function( x,y,z,height ) {

		// Remove height of kionokrano
		height -= 0.4;

		//
		// Pillar
		//
		var geom = new THREE.CylinderBufferGeometry( 0.25, 0.4, height, 12, 1 );
		var mesh = new THREE.Mesh( geom, this.pillarMaterial );

		mesh.position.set( x, y, z+height/2 );
		mesh.rotation.set( Math.PI/2, 0, 0 );
		mesh.castShadow = true;
		this.add( mesh );

		//
		// Kionokrano
		//
		var mesh = this.kionokranoMesh.children[0].clone();
		mesh.material = this.kionokranoMaterial;
		mesh.position.set( x,y,z+height );
		mesh.castShadow = true;
		this.add( mesh );

	},

	addJunctionFrames: function( length, width, padding, step, frameHeight, repeats ) {
		var z = step;
		for (var i=0; i<repeats; i++, z+=step) {
			this.addJunctionFrame( length, width, z, padding, frameHeight );
		}
	},

	addJunctionFrame: function( length, width, z, padding, frameHeight ) {
		var frameWidth = 1.0;
		var xGeom = new THREE.BoxGeometry( frameWidth, length+frameWidth, frameHeight );
		var yGeom = new THREE.BoxGeometry( width+frameWidth, frameWidth, frameHeight );

		var meshL = new THREE.Mesh( xGeom, this.frameMaterial );
		var meshR = new THREE.Mesh( xGeom, this.frameMaterial );
		var meshN = new THREE.Mesh( yGeom, this.frameMaterial );
		var meshF = new THREE.Mesh( yGeom, this.frameMaterial );

		meshL.position.set( -width/2, length/2+padding, z-frameHeight/2 );
		meshR.position.set(  width/2, length/2+padding, z-frameHeight/2 );
		meshN.position.set(  0, padding, z-frameHeight/2 );
		meshF.position.set(  0, length+padding, z-frameHeight/2 );

		this.add( meshL );
		this.add( meshR );
		this.add( meshN );
		this.add( meshF );

	},

	openDoor: function( cb ) {
		Iconeezin.Runtime.runTween((function(i) {

			this.doorLPivot.rotation.set( 0, 0, (-Math.PI/2)*i );
			this.doorRPivot.rotation.set( 0, 0, -Math.PI+(Math.PI/2)*i );

		}).bind(this), 1000, cb);
	},

});

module.exports = MonumentRoom;