text:
class NCursesStream
{
    /// \brief wrapper class around NCurses initialization and de-initialization methods
    struct NCurses
    {
        /// \brief constructor. Initializes ncurses
        NCurses()
        {
            initscr();
            cbreak();
            keypad(stdscr, TRUE);
            curs_set(0); // hide the cursor
            refresh();
        }
        /// \brief destructor. tears down ncurses
        ~NCurses()
        {
            endwin();
        }
    };

    /// \brief parent class for all windows. Essentially an object oriented wrapper around the ncurses window
    class Window
    {
    protected:
        size_t mHeight; ///< height of the window
        size_t mWidth; ///< width of the window
        size_t mStartRow; ///< start row of the window (origin is top left)
        size_t mStartCol; ///< start column of the window (origin is top left)

        WINDOW* mAddress; ///< reference to ncurses window controlled by this object

    public:
        /// \brief Constructs a window with the given geometric position
        /// \param height the height of the window, in characters
        /// \param width the width of the window, in characters
        /// \param start_row the start row of the window
        /// \param start_col the start column of the window
        Window(size_t height, size_t width, size_t start_row, size_t start_col)
        : mHeight(height),
          mWidth(width),
          mStartRow(start_row),
          mStartCol(start_col),
          mAddress( newwin(static_cast<int>(mHeight), static_cast<int>(mWidth), static_cast<int>(mStartRow), static_cast<int>(mStartCol)) )
        {
            //std::cerr << "Window(" << height << "," << width << "," << start_row << "," << start_col << ")\n"; // XXX
        }

        /// \brief Destroys a window
        ~Window()
        {
            delwin(mAddress);
            mAddress = nullptr;
        }

        // accessor method
        inline size_t Height() const { return mHeight; }
        inline size_t Width() const { return mWidth; }
        inline size_t StartRow() const { return mStartRow; }
        inline size_t EndRow() const { return StartRow() + Height(); }
        inline size_t StartColumn() const { return mStartCol; }
        inline size_t EndColumn() const { return StartColumn() + Width(); }
        inline void Refresh() { wrefresh(mAddress); }
    };

    /// \brief Window with a box on the outer edge
    struct BoxWindow : public Window
    {
        BoxWindow(size_t height, size_t width, size_t start_row, size_t start_col)
        : Window(height, width, start_row, start_col)
        {
            box(mAddress, 0, 0);
        }
    };

    class InputWindow : public Window
    {
        const std::string mPrompt = "> ";
        const size_t mMaxInputLength;

    public:
        InputWindow(size_t height, size_t width, size_t start_row, size_t start_col)
        : Window(height, width, start_row, start_col),
          mPrompt("> "),
          mMaxInputLength(Width() - mPrompt.length())
        {
            mvwprintw(mAddress, 0, 0, "%s", mPrompt.c_str());
        }

        std::string Read()
        {
            bool enter_received = false;
            std::string msg;

            while( !enter_received )
            {
                auto c = wgetch(mAddress);
                switch( c )
                {
                case 0x08: // backspace
                case 0x7F: // delete
                    if( !msg.empty() )
                        msg.pop_back();
                    break;
                case '\n':
                case '\r':
                    enter_received = true;
                    break;
                default:
                    if( std::isprint(c) )
                        msg.push_back(c);
                }
                mvwprintw(mAddress, 0, mPrompt.length(), "%s", msg.c_str());
                wclrtoeol(mAddress);
                wrefresh(mAddress);
            }
            wmove(mAddress, 0, mPrompt.length());
            wclrtoeol(mAddress);

            wrefresh(mAddress);
            return msg;
        }
    };

    class DisplayWindow : public Window
    {
    public:
        DisplayWindow(size_t height, size_t width, size_t start_row, size_t start_col)
        : Window(height, width, start_row, start_col)
        {
        }

        void Write(const Maze<Cell>& dungeon)
        {
            for(unsigned row=0; row<dungeon.Rows(); ++row)
            {
                wmove(mAddress, row, 0);
                for(unsigned col=0; col<dungeon.Columns(); ++col)
                {
                    if( dungeon.At(row, col).Opened() )
                    {
                        waddch(mAddress, ' ');
                    }
                    else
                    {
                        bool closed_above = dungeon.Contains(row-1,col) && !dungeon.At(row-1,col).Opened();
                        bool closed_below = dungeon.Contains(row+1,col) && !dungeon.At(row+1,col).Opened();
                        bool closed_left  = dungeon.Contains(row,col-1) && !dungeon.At(row,col-1 ).Opened();
                        bool closed_right = dungeon.Contains(row,col+1) && !dungeon.At(row,col+1).Opened();

                        if( closed_above && closed_below && closed_right && closed_left )
                            waddch(mAddress, ACS_PLUS);
                        else if( closed_below && closed_right && closed_left )
                            waddch(mAddress, ACS_TTEE);
                        else if( closed_above && closed_right && closed_left )
                            waddch(mAddress, ACS_BTEE);
                        else if( closed_above && closed_below && closed_left )
                            waddch(mAddress, ACS_RTEE);
                        else if( closed_above && closed_below && closed_right)
                            waddch(mAddress, ACS_LTEE);
                        else if( closed_below && closed_right )
                            waddch(mAddress, ACS_ULCORNER);
                        else if( closed_below && closed_left )
                            waddch(mAddress, ACS_URCORNER);
                        else if( closed_above && closed_right )
                            waddch(mAddress, ACS_LLCORNER);
                        else if( closed_above && closed_left )
                            waddch(mAddress, ACS_LRCORNER);
                        else if( closed_left || closed_right )
                            waddch(mAddress, ACS_HLINE);
                        else if( closed_above || closed_below )
                            waddch(mAddress, ACS_VLINE);
                        else
                            throw std::runtime_error("Display: Unhandled cell detected");
                    }
                }
            }
            wrefresh(mAddress);
        }
    };

    class OutputWindow : public BoxWindow
    {
    public:
        OutputWindow(size_t height, size_t width, size_t start_row, size_t start_col)
        : BoxWindow(height, width, start_row, start_col)
        {
            box(mAddress, 0, 0);
        }

        void Write(const std::string& msg)
        {
            // put the message into the history, splitting lines that are longer than the window or have a newline

            // split on newlines
            std::vector<std::string> lines;
            boost::split(lines, msg, boost::is_any_of("\r\n"));

            // split long-lines into two lines
            for(auto itr=lines.begin(); itr!=lines.end(); ++itr)
            {
                if( itr->size() > Width() - 2 )
                {
                    lines.insert(itr, itr->substr(0, Width()-2));
                    itr->erase(Width()-2);
                }
            }

            //TODO: handle messages longer than Height()-2 lines long
            //TODO: add ability to scroll up and see history

            if(lines.size() > Height()-2)
            {
                mvwprintw(mAddress, 1, 1, "ERROR: Message too long (%d lines)", lines.size());
            }
            else
            {
                for(size_t i=1; i<(Height()-2); ++i)
                {
                    wmove(mAddress, i, 1);
                    if( lines.size() >= i )
                        wprintw(mAddress, "%s", lines.at(i-1).c_str());
                    wclrtoeol(mAddress);
                }
            }
            box(mAddress, 0, 0);
            wrefresh(mAddress);
        }
    };

    NCurses mNCurses; ///< structure for construction and destruction of the ncurses environment
    DisplayWindow mDisplayWindow; ///< used to display map of current location
    BoxWindow mCharacterWindow; ///< used to display current character statistics
    OutputWindow mOutputWindow; ///< used for output game narraration
    InputWindow mInputWindow; ///< used for input of commands
    BoxWindow mOuterWindow; ///< outer window containing all game windows

public:
    NCursesStream(size_t display_height=30, size_t display_width=50, size_t output_window_height=5, size_t character_window_width=10)
    : mNCurses(),
      mDisplayWindow(display_height, display_width, 1, 1),
      mCharacterWindow(mDisplayWindow.Height(), character_window_width, mDisplayWindow.StartRow(), mDisplayWindow.EndColumn()+1),
      mOutputWindow(output_window_height, mCharacterWindow.EndColumn()-mDisplayWindow.StartColumn(), mDisplayWindow.EndRow(), mDisplayWindow.StartColumn()),
      mInputWindow(1,                     mOutputWindow.Width(), mOutputWindow.EndRow(), mDisplayWindow.StartColumn()),
      mOuterWindow(mInputWindow.EndRow()+1, mInputWindow.EndColumn()+1, 0, 0)
    {
        mOuterWindow.Refresh();
        mDisplayWindow.Refresh();
        mCharacterWindow.Refresh();
        mOutputWindow.Refresh();
        mInputWindow.Refresh();
    }

    ~NCursesStream()
    {
    }

    void flush()
    {
        refresh();
    }

    // TODO: add iomanip methods:
    // SetMazePaneHeight
    // SetMazePaneWidth
    // SetCharacterPaneHeight
    // SetCharacterPaneWidth
    // SetIOPaneHeight
    // SetIOPaneWidth

    //TODO: make these templates, with specialization for character and dungeon. All other info goes to the
    // narration window
    friend NCursesStream& operator<<(NCursesStream& out, const Character& character);
    friend NCursesStream& operator<<(NCursesStream& out, const std::string& narraration);
    friend NCursesStream& operator<<(NCursesStream& out, const Maze<Cell>& dungeon);

    friend NCursesStream& operator>>(NCursesStream& in, std::string& str);
};

NCursesStream& operator<<(NCursesStream& out, const Character& character)
{
    //TODO
    return out;
}
NCursesStream& operator<<(NCursesStream& out, const std::string& narraration)
{
    out.mOutputWindow.Write(narraration);
    return out;
}
NCursesStream& operator>>(NCursesStream& in, std::string& str)
{
    str = in.mInputWindow.Read();
    return in;
}

//TODO: make a template
NCursesStream& operator<<(NCursesStream& out, const Maze<Cell>& dungeon)
{
    out.mDisplayWindow.Write(dungeon);
    return out;
}

#endif // NCURSES_STREAM_HPP


text:
{%- capture title -%}
IOBTagger
{%- endcapture -%}

{%- capture model -%}
model
{%- endcapture -%}

{%- capture model_description -%}
Merges token tags and NER labels from chunks in the specified format.
For example output columns as inputs from
[NerConverter](/docs/en/annotators#nerconverter)
and [Tokenizer](/docs/en/annotators#tokenizer) can be used to merge.
{%- endcapture -%}

{%- capture model_input_anno -%}
TOKEN, CHUNK
{%- endcapture -%}

{%- capture model_output_anno -%}
NAMED_ENTITY
{%- endcapture -%}

{%- capture model_python_medical -%}
from johnsnowlabs import *
# Pipeline stages are defined where NER is done. NER is converted to chunks.
data = spark.createDataFrame([["A 63-year-old man presents to the hospital ..."]]).toDF("text")
docAssembler = nlp.DocumentAssembler().setInputCol("text").setOutputCol("document")
sentenceDetector = nlp.SentenceDetector().setInputCols(["document"]).setOutputCol("sentence")
tokenizer = nlp.Tokenizer().setInputCols(["sentence"]).setOutputCol("token")
embeddings = nlp.WordEmbeddingsModel.pretrained("embeddings_clinical", "en", "clinical/models").setInputCols(["sentence", "token"]).setOutputCol("embs")
nerModel = medical.NerModel.pretrained("ner_jsl", "en", "clinical/models").setInputCols(["sentence", "token", "embs"]).setOutputCol("ner")
nerConverter = nlp.NerConverter().setInputCols(["sentence", "token", "ner"]).setOutputCol("ner_chunk")

# Define the IOB tagger, which needs tokens and chunks as input. Show results.
iobTagger = medical.IOBTagger().setInputCols(["token", "ner_chunk"]).setOutputCol("ner_label")
pipeline = Pipeline(stages=[docAssembler, sentenceDetector, tokenizer, embeddings, nerModel, nerConverter, iobTagger])

result.selectExpr("explode(ner_label) as a") \
  .selectExpr("a.begin","a.end","a.result as chunk","a.metadata.word as word") \
  .where("chunk!='O'").show(5, False)

+-----+---+-----------+-----------+
|begin|end|chunk      |word       |
+-----+---+-----------+-----------+
|5    |15 |B-Age      |63-year-old|
|17   |19 |B-Gender   |man        |
|64   |72 |B-Modifier |recurrent  |
|98   |107|B-Diagnosis|cellulitis |
|110  |119|B-Diagnosis|pneumonias |
+-----+---+-----------+-----------+

{%- endcapture -%}

{%- capture model_python_legal -%}
from johnsnowlabs import *
# Pipeline stages are defined where NER is done. NER is converted to chunks.

docAssembler = nlp.DocumentAssembler().setInputCol("text").setOutputCol("document")
sentenceDetector = nlp.SentenceDetector().setInputCols(["document"]).setOutputCol("sentence")
tokenizer = nlp.Tokenizer().setInputCols(["sentence"]).setOutputCol("token")
embeddings = nlp.WordEmbeddingsModel.pretrained("embeddings_clinical", "en", "clinical/models").setInputCols(["sentence", "token"]).setOutputCol("embs")
ner_model = legal.NerModel.pretrained("legner_orgs_prods_alias", "en", "legal/models").setInputCols(["sentence", "token", "embs"]).setOutputCol("ner")
nerConverter = nlp.NerConverter().setInputCols(["sentence", "token", "ner"]).setOutputCol("ner_chunk")

# Define the IOB tagger, which needs tokens and chunks as input. Show results.
iobTagger = legal.IOBTagger().setInputCols(["token", "ner_chunk"]).setOutputCol("ner_label")
pipeline = Pipeline(stages=[docAssembler, sentenceDetector, tokenizer, embeddings, ner_model, nerConverter, iobTagger])
{%- endcapture -%}

{%- capture model_python_finance -%}
from johnsnowlabs import *
# Pipeline stages are defined where NER is done. NER is converted to chunks.

docAssembler = nlp.DocumentAssembler().setInputCol("text").setOutputCol("document")
sentenceDetector = nlp.SentenceDetector().setInputCols(["document"]).setOutputCol("sentence")
tokenizer = nlp.Tokenizer().setInputCols(["sentence"]).setOutputCol("token")
embeddings = nlp.WordEmbeddingsModel.pretrained("embeddings_clinical", "en", "clinical/models").setInputCols(["sentence", "token"]).setOutputCol("embs")
ner_model = finance.NerModel.pretrained("finner_orgs_prods_alias","en","finance/models").setInputCols(["sentence", "token", "embs"]).setOutputCol("ner")
nerConverter = nlp.NerConverter().setInputCols(["sentence", "token", "ner"]).setOutputCol("ner_chunk")

# Define the IOB tagger, which needs tokens and chunks as input. Show results.
iobTagger = finance.IOBTagger().setInputCols(["token", "ner_chunk"]).setOutputCol("ner_label")
pipeline = Pipeline(stages=[docAssembler, sentenceDetector, tokenizer, embeddings, ner_model, nerConverter, iobTagger])
{%- endcapture -%}

{%- capture model_scala_medical -%}
from johnsnowlabs import *
// Pipeline stages are defined where NER is done. NER is converted to chunks.
val data = Seq(("A 63-year-old man presents to the hospital ...")).toDF("text")
val docAssembler = new nlp.DocumentAssembler().setInputCol("text").setOutputCol("document")
val sentenceDetector = new nlp.SentenceDetector().setInputCols("document").setOutputCol("sentence")
val tokenizer = new nlp.Tokenizer().setInputCols("sentence").setOutputCol("token")
val embeddings = nlp.WordEmbeddingsModel.pretrained("embeddings_clinical", "en", "clinical/models").setInputCols(Array("sentence", "token")).setOutputCol("embs")
val nerModel = medical.NerModel.pretrained("ner_jsl", "en", "clinical/models").setInputCols(Array("sentence", "token", "embs")).setOutputCol("ner")
val nerConverter = new nlp.NerConverter().setInputCols(Array("sentence", "token", "ner")).setOutputCol("ner_chunk")

// Define the IOB tagger, which needs tokens and chunks as input. Show results.
val iobTagger = new medical.IOBTagger().setInputCols(Array("token", "ner_chunk")).setOutputCol("ner_label")
val pipeline = new Pipeline().setStages(Array(docAssembler, sentenceDetector, tokenizer, embeddings, nerModel, nerConverter, iobTagger))

result.selectExpr("explode(ner_label) as a")
  .selectExpr("a.begin","a.end","a.result as chunk","a.metadata.word as word")
  .where("chunk!='O'").show(5, false)

+-----+---+-----------+-----------+
|begin|end|chunk      |word       |
+-----+---+-----------+-----------+
|5    |15 |B-Age      |63-year-old|
|17   |19 |B-Gender   |man        |
|64   |72 |B-Modifier |recurrent  |
|98   |107|B-Diagnosis|cellulitis |
|110  |119|B-Diagnosis|pneumonias |
+-----+---+-----------+-----------+

{%- endcapture -%}

{%- capture model_scala_legal -%}
from johnsnowlabs import *
// Pipeline stages are defined where NER is done. NER is converted to chunks.
val docAssembler = new nlp.DocumentAssembler().setInputCol("text").setOutputCol("document")
val sentenceDetector = new nlp.SentenceDetector().setInputCols("document").setOutputCol("sentence")
val tokenizer = new nlp.Tokenizer().setInputCols("sentence").setOutputCol("token")
val embeddings = nlp.WordEmbeddingsModel.pretrained("embeddings_clinical", "en", "clinical/models").setInputCols(Array("sentence", "token")).setOutputCol("embs")
val ner_model = legal.NerModel.pretrained("legner_orgs_prods_alias", "en", "legal/models").setInputCols(Array("sentence", "token", "embs")).setOutputCol("ner")
val nerConverter = new nlp.NerConverter().setInputCols(Array("sentence", "token", "ner")).setOutputCol("ner_chunk")

// Define the IOB tagger, which needs tokens and chunks as input. Show results.
val iobTagger = new legal.IOBTagger().setInputCols(Array("token", "ner_chunk")).setOutputCol("ner_label")
val pipeline = new Pipeline().setStages(Array(docAssembler, sentenceDetector, tokenizer, embeddings, ner_model, nerConverter, iobTagger))
{%- endcapture -%}

{%- capture model_scala_finance -%}
from johnsnowlabs import *
// Pipeline stages are defined where NER is done. NER is converted to chunks.
val docAssembler = new nlp.DocumentAssembler().setInputCol("text").setOutputCol("document")
val sentenceDetector = new nlp.SentenceDetector().setInputCols("document").setOutputCol("sentence")
val tokenizer = new nlp.Tokenizer().setInputCols("sentence").setOutputCol("token")
val embeddings = nlp.WordEmbeddingsModel.pretrained("embeddings_clinical", "en", "clinical/models").setInputCols(Array("sentence", "token")).setOutputCol("embs")
val ner_model = finance.NerModel.pretrained("finner_orgs_prods_alias","en","finance/models").setInputCols(Array("sentence", "token", "embs")).setOutputCol("ner")
val nerConverter = new nlp.NerConverter().setInputCols(Array("sentence", "token", "ner")).setOutputCol("ner_chunk")

// Define the IOB tagger, which needs tokens and chunks as input. Show results.
val iobTagger = new legal.IOBTagger().setInputCols(Array("token", "ner_chunk")).setOutputCol("ner_label")
val pipeline = new Pipeline().setStages(Array(docAssembler, sentenceDetector, tokenizer, embeddings, ner_model, nerConverter, iobTagger))
{%- endcapture -%}

{%- capture model_api_link -%}
[IOBTagger](https://nlp.johnsnowlabs.com/licensed/api/com/johnsnowlabs/nlp/annotators/ner/IOBTagger)
{%- endcapture -%}

{% include templates/licensed_approach_model_medical_fin_leg_template.md
title=title
model=model
model_description=model_description
model_input_anno=model_input_anno
model_output_anno=model_output_anno
model_python_medical=model_python_medical
model_python_legal=model_python_legal
model_python_finance=model_python_finance
model_scala_medical=model_scala_medical
model_scala_legal=model_scala_legal
model_scala_finance=model_scala_finance
model_api_link=model_api_link%}

redpajama_set_name: RedPajamaGithub


text:
using System;
using UIKit;

namespace BackgroundExecution
{
	public class Application
	{
		public static void Main (string[] args)
		{
			UIApplication.Main (args, null, "AppDelegate");
		}
	}
}


text:
void carregarImagemPGM(ImagemPGM * imagem, char * const mensagem) {
	printf("CARREGAR IMAGEM\n");

	if (!imagem_isEmpty(imagem)) {
		imagem_destroy(imagem);
	}

	char *endereco = NULL;

	int imagemCarregadaComSucesso = 0;

	while (!imagemCarregadaComSucesso) {
		endereco = getEnderecoArquivo(mensagem, EXTENSAO);
		imagemCarregadaComSucesso = imagem_read(imagem, endereco);
		free(endereco);

		if(!imagemCarregadaComSucesso) {
			print_error("A imagem passada não foi localizada.");
			printf("Pressione ENTER para continuar");
		}
	}

	print_sucess("IMAGEM CARREGADA COM SUCESSO");
}
void salvarImagemPGM(ImagemPGM * imagem, char * const mensagem) {
	printf("SALVAR IMAGEM\n");

	char *endereco = getEnderecoArquivo(mensagem, EXTENSAO);
	imagem_save(imagem, endereco);
	free(endereco);

	print_sucess("IMAGEM SALVA COM SUCESSO");
}

void dadosSimplesDaImagem(ImagemPGM * imagem) {
	printf("Dados da imagem: \n");
	printf(" ALTURA: %d\n", imagem->headArquivo.height);
	printf(" LARGURA: %d\n", imagem->headArquivo.width);
}


text:
struct CoreAccountInfo;

namespace syncer {

// Interface that allows platform-specific logic related to accessing locally
// available trusted vault encryption keys.
class TrustedVaultClient {
 public:
  TrustedVaultClient() = default;
  virtual ~TrustedVaultClient() = default;

  using CallbackList = base::CallbackList<void()>;
  using Subscription = CallbackList::Subscription;

  // Registers an observer-like callback that will be invoked when the content
  // of the vault has changed (e.g. new keys added). The subscription must not
  // outlive |*this|.
  virtual std::unique_ptr<Subscription> AddKeysChangedObserver(
      const base::RepeatingClosure& cb) = 0;

  // Attempts to fetch decryption keys, required by sync to resume.
  // Implementations are expected to NOT prompt the user for actions. |cb| is
  // called on completion with known keys or an empty list if none known.
  // Concurrent calls to FetchKeys() must not be issued since implementations
  // may not support them.
  virtual void FetchKeys(
      const CoreAccountInfo& account_info,
      base::OnceCallback<void(const std::vector<std::vector<uint8_t>>&)>
          cb) = 0;

  // Invoked when the result of FetchKeys() contains keys that cannot decrypt
  // the pending cryptographer (Nigori) keys, which should only be possible if
  // the provided keys are not up-to-date. |cb| is run upon completion and
  // returns false if the call did not make any difference (e.g. the operation
  // is unsupported) or true if some change may have occurred (which indicates a
  // second FetchKeys() attempt is worth). Concurrent calls to MarkKeysAsStale()
  // must not be issued since implementations may not support them.
  virtual void MarkKeysAsStale(const CoreAccountInfo& account_info,
                               base::OnceCallback<void(bool)> cb) = 0;

  // Allows implementations to store encryption keys fetched by other means such
  // as Web interactions. Implementations are free to completely ignore these
  // keys, so callers may not assume that later calls to FetchKeys() would
  // necessarily return the keys passed here.
  virtual void StoreKeys(const std::string& gaia_id,
                         const std::vector<std::vector<uint8_t>>& keys,
                         int last_key_version) = 0;

  // Allows implementation to remove all previously stored keys.
  // Implementations must erase all keys saved during StoreKeys() call. Used
  // when accounts cookies deleted by the user action.
  virtual void RemoveAllStoredKeys() = 0;

 private:
  DISALLOW_COPY_AND_ASSIGN(TrustedVaultClient);
};

}  // namespace syncer

#endif  // COMPONENTS_SYNC_DRIVER_TRUSTED_VAULT_CLIENT_H_


text:
extern "Java"
{
  namespace gnu
  {
    namespace javax
    {
      namespace crypto
      {
        namespace jce
        {
            class PBKDF2SecretKeyFactory$HMacRipeMD160;
        }
      }
    }
  }
}

class gnu::javax::crypto::jce::PBKDF2SecretKeyFactory$HMacRipeMD160 : public ::gnu::javax::crypto::jce::PBKDF2SecretKeyFactory
{

public:
  PBKDF2SecretKeyFactory$HMacRipeMD160();
  static ::java::lang::Class class$;
};

#endif // __gnu_javax_crypto_jce_PBKDF2SecretKeyFactory$HMacRipeMD160__


text:
import { Contact, ContactType } from "../../server/schema/Contact";
import Keyword from "../../server/schema/keywords";

const person: Contact = {
  name: "Tomáš Konrády",
  about:
    "Frontend developer at Lundegaard a.s. Lover of Ramda and creator of ramda-extension and react-union libraries.",
  image: {
    url: "people/tomas.jpg",
  },
  social: {
    twitter: "konnnyy",
    github: "tommmyy",
    linkedin: "tomaskonrady",
  },
  location: {
    country: {
      name: "Czech Republic",
      code: "CZ",
    },
    city: "Hradec Králové",
  },
  keywords: [Keyword.REACT, Keyword.TOOLING],
  type: [ContactType.SPEAKER],
};

export default person;


text:
//
// Copyright (c) articy Software GmbH & Co. KG. All rights reserved.
//

#pragma once

#include "CoreMinimal.h"
#include "Engine/Texture2D.h"
#include "ArticyBaseTypes.h"
/**
 *
 */

class UArticyObject;

namespace UserInterfaceHelperFunctions
{
	enum EImageSize
	{
		Small,
		Medium,
		Large
	};

	const ARTICYEDITOR_API FSlateBrush* GetArticyTypeImage(const UArticyObject* ArticyObject, EImageSize Size);

	ARTICYEDITOR_API UTexture2D* GetDisplayImage(const UArticyObject* ArticyObject);
	ARTICYEDITOR_API bool RetrievePreviewImage(const UArticyObject* ArticyObject, FSlateBrush& OutSlateBrush);
	ARTICYEDITOR_API bool RetrieveSpeakerPreviewImage(const UArticyObject* ArticyObject, FSlateBrush& OutSlateBrush);

	const ARTICYEDITOR_API FArticyId* GetTargetID(const UArticyObject* ArticyObject);
	const ARTICYEDITOR_API FString GetDisplayName(const UArticyObject* ArticyObject);
	const ARTICYEDITOR_API FLinearColor GetColor(const UArticyObject* ArticyObject);
	//const TArray< GetColor(const UArticyObject* ArticyObject);

	const ARTICYEDITOR_API bool ShowObjectInArticy(const UArticyObject* ArticyObject);
	const ARTICYEDITOR_API bool ShowObjectInArticy(const FArticyId ArticyId, bool bNewTab);
};


text:
import superimport

import pyprobml_utils as pml

import numpy as np
np.set_printoptions(precision=3)
import matplotlib.pyplot as plt
import math
import os
import warnings
import pandas as pd

import jax
print("jax version {}".format(jax.__version__))
print("jax backend {}".format(jax.lib.xla_bridge.get_backend().platform))

import jax.numpy as jnp
from jax import random, vmap

rng_key = random.PRNGKey(0)
rng_key, rng_key_ = random.split(rng_key)

import numpyro
import numpyro.distributions as dist
from numpyro.infer import Predictive

import arviz as az

from jax.scipy.special import expit
from functools import partial

### Model with just offset term

def model_meta(prior_std, obs=None):
    a = numpyro.sample("a", dist.Normal(0, prior_std))
    numpyro.sample("obs", dist.Binomial(logits=a), obs=obs)

fig, ax = plt.subplots()
colors = ['r', 'k']
for i, sigma in enumerate([1.5, 10]):
  model = partial(model_meta, sigma)
  prior = Predictive(model, num_samples=10000)(random.PRNGKey(1999))
  p = expit(prior["a"])
  label = r'variance={:0.2f}$'.format(sigma)
  az.plot_kde(p, ax=ax, plot_kwargs = {'color': colors[i]}, label=label, legend=True)
pml.savefig('logreg_prior_offset.pdf', dpi=300)
plt.show()


text:
importScripts('components/threads/client.js');

var client = threads.client('music-service', new BroadcastChannel('music-service'));

function ArtistsService(worker) {
  var stopAfter = ServiceWorkerWare.decorators.stopAfter;

  worker.get('/api/artists', stopAfter((request) => {
    return new Promise((resolve) => {
      client.method('getArtists').then((artists) => {
        resolve(new Response(JSON.stringify(artists), {
          headers: { 'Content-Type': 'application/json' }
        }));
      });
    });
  }));

  worker.get('/api/artists/info/:filePath', stopAfter((request) => {
    return new Promise((resolve) => {
      var filePath = '/' + decodeURIComponent(request.parameters.filePath);
      client.method('getArtist', filePath)
        .then((songs) => {
          resolve(new Response(JSON.stringify(songs), {
            headers: { 'Content-Type': 'application/json' }
          }));
        })
        .catch((error) => {
          resolve(new Response('', { status: 404 }));
        });
    });
  }));
}


text:
package org.apache.drill.yarn.client;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.Map;

import org.apache.drill.yarn.core.AppSpec;
import org.apache.drill.yarn.core.DoYUtil;
import org.apache.drill.yarn.core.DrillOnYarnConfig;
import org.apache.drill.yarn.core.LaunchSpec;
import org.apache.drill.yarn.core.YarnClientException;
import org.apache.drill.yarn.core.YarnRMClient;
import org.apache.hadoop.yarn.api.ApplicationConstants;
import org.apache.hadoop.yarn.api.protocolrecords.GetNewApplicationResponse;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.LocalResource;
import org.apache.hadoop.yarn.api.records.YarnApplicationState;

import com.typesafe.config.Config;

/**
 * Launch the AM through YARN. Builds the launch description, then tracks
 * the launch operation itself. Finally, provides the user with links to
 * track the AM both through YARN and via the AM's own web UI.
 */

public class AMRunner {
  private Config config;
  private boolean verbose;
  private ApplicationId appId;
  public Map<String, LocalResource> resources;
  public String drillArchivePath;
  public String siteArchivePath;
  public String remoteDrillHome;
  public String remoteSiteDir;
  private YarnRMClient client;
  private GetNewApplicationResponse appResponse;
  private boolean dryRun;

  public AMRunner(Config config, boolean verbose, boolean dryRun) {
    this.config = config;
    this.verbose = verbose;
    this.dryRun = dryRun;
  }

  public void run() throws ClientException {
    connectToYarn();
    if (dryRun) {
      doDryRun();
    } else {
      doLaunch();
    }
  }

  private void connectToYarn() {
    System.out.print("Loading YARN Config...");
    client = new YarnRMClient();
    System.out.println(" Loaded.");
  }

  private void doDryRun() throws ClientException {
    AppSpec master = buildSpec();
    dump(master, System.out);
  }

  private void doLaunch() throws ClientException {
    createApp();
    AppSpec master = buildSpec();
    if (verbose) {
      dump(master, System.out);
    }
    validateResources(master);
    launchApp(master);
    waitForStartAndReport(master.appName);
    writeAppIdFile();
  }

  private void dump(AppSpec master, PrintStream out) {
    out.println("----------------------------------------------");
    out.println("Application Master Launch Spec");
    master.dump(out);
    out.println("----------------------------------------------");
  }

  private AppSpec buildSpec() throws ClientException {
    AppSpec master = new AppSpec();

    // Heap memory

    String heapMem = config.getString( DrillOnYarnConfig.AM_HEAP );
    master.env.put( DrillOnYarnConfig.AM_HEAP_ENV_VAR, heapMem );

    // Any additional VM arguments from the config file.

    addIfSet( master, DrillOnYarnConfig.AM_VM_ARGS, DrillOnYarnConfig.AM_JAVA_OPTS_ENV_VAR );

    // Any user specified override jars
    // Not really needed by the AM.

    addIfSet( master, DrillOnYarnConfig.AM_PREFIX_CLASSPATH, DrillOnYarnConfig.DRILL_CLASSPATH_PREFIX_ENV_VAR );

    // Any user specified classpath.

    addIfSet( master, DrillOnYarnConfig.AM_CLASSPATH, DrillOnYarnConfig.DRILL_CLASSPATH_ENV_VAR );

    // Any user-specified library path

    addIfSet( master, DrillOnYarnConfig.JAVA_LIB_PATH, DrillOnYarnConfig.DOY_LIBPATH_ENV_VAR );

    // AM logs (of which there are none.
    // Relies on the LOG_DIR_EXPANSION_VAR marker which is replaced by
    // the container log directory.
    // Must be set for the AM to prevent drill-config.sh from trying to create
    // the log directory in $DRILL_HOME (which won't be writable under YARN.)

    if (!config.getBoolean(DrillOnYarnConfig.DISABLE_YARN_LOGS)) {
      master.env.put("DRILL_YARN_LOG_DIR",
          ApplicationConstants.LOG_DIR_EXPANSION_VAR);
    }

    // AM launch script
    // The drill home location is either a non-localized location,
    // or, more typically, the expanded Drill directory under the
    // container's working directory. When the localized directory,
    // we rely on the fact that the current working directory is
    // set to the container directory, so we just need the name
    // of the Drill folder under the cwd.

    master.command = remoteDrillHome + "/bin/drill-am.sh";

    // If site dir, add that as an argument.

    if ( remoteSiteDir != null ) {
      master.cmdArgs.add( "--site" );
      master.cmdArgs.add( remoteSiteDir );
    }

    // Strangely, YARN has no way to tell an AM what its app ID
    // is. So, we pass it along here.

    String appIdStr = dryRun ? "Unknown" : appId.toString();
    master.env.put( DrillOnYarnConfig.APP_ID_ENV_VAR, appIdStr );

    // Debug launch: dumps environment variables and other information
    // in the launch script.

    if ( config.getBoolean( DrillOnYarnConfig.AM_DEBUG_LAUNCH ) ) {
      master.env.put( DrillOnYarnConfig.DRILL_DEBUG_ENV_VAR, "1" );
    }

    // If localized, add the drill and optionally site archive.

    if ( config.getBoolean( DrillOnYarnConfig.LOCALIZE_DRILL) ) {

      // Also, YARN has no way to tell an AM what localized resources are
      // available, so we pass them along as environment variables.

      master.env.put( DrillOnYarnConfig.DRILL_ARCHIVE_ENV_VAR, drillArchivePath );
      if ( siteArchivePath != null ) {
        master.env.put( DrillOnYarnConfig.SITE_ARCHIVE_ENV_VAR, siteArchivePath );
      }
    }

    // Localized resources

    master.resources.putAll( resources );

    // Container specification.

    master.memoryMb = config.getInt( DrillOnYarnConfig.AM_MEMORY );
    master.vCores = config.getInt( DrillOnYarnConfig.AM_VCORES );
    master.disks = config.getDouble( DrillOnYarnConfig.AM_DISKS );
    master.appName = config.getString( DrillOnYarnConfig.APP_NAME );
    master.queueName = config.getString( DrillOnYarnConfig.YARN_QUEUE );
    master.priority = config.getInt( DrillOnYarnConfig.YARN_PRIORITY );
    master.nodeLabelExpr = config.getString( DrillOnYarnConfig.AM_NODE_LABEL_EXPR );
    return master;
  }

  private void addIfSet(LaunchSpec spec, String configParam, String envVar) {
    String value = config.getString(configParam);
    if (!DoYUtil.isBlank(value)) {
      spec.env.put(envVar, value);
    }
  }

  private void createApp() throws ClientException {
    try {
      appResponse = client.createAppMaster();
    } catch (YarnClientException e) {
      throw new ClientException("Failed to allocate Drill application master",
          e);
    }
    appId = appResponse.getApplicationId();
    System.out.println("Application ID: " + appId.toString());
  }

  private void validateResources( AppSpec master ) throws ClientException {

    // Memory and core checks per YARN app specs.

    int maxMemory = appResponse.getMaximumResourceCapability().getMemory();
    int maxCores = appResponse.getMaximumResourceCapability().getVirtualCores();
    if (verbose) {
      System.out.println("Max Memory: " + maxMemory);
      System.out.println("Max Cores: " + maxCores);
    }

    // YARN behaves very badly if we request a container larger than the
    // maximum.

    if (master.memoryMb > maxMemory) {
     throw new ClientException( "YARN maximum memory is " + maxMemory
         + " but the application master requests " + master.memoryMb );
    }
    if (master.vCores > maxCores) {
      throw new ClientException("YARN maximum vcores is " + maxCores
          + " but the application master requests " + master.vCores);
    }

    // Verify the limits for the Drillbit as well.

    if (config.getInt(DrillOnYarnConfig.DRILLBIT_MEMORY) > maxMemory) {
      throw new ClientException(
          "YARN maximum memory is " + maxMemory + " but the Drillbit requests "
              + config.getInt(DrillOnYarnConfig.DRILLBIT_MEMORY));
    }
    if (config.getInt(DrillOnYarnConfig.DRILLBIT_VCORES) > maxCores) {
      throw new ClientException("YARN maximum vcores is " + maxCores
          + " but the Drillbit requests "
          + config.getInt(DrillOnYarnConfig.DRILLBIT_VCORES));
    }
  }

  private void launchApp(AppSpec master) throws ClientException {
    try {
      client.submitAppMaster(master);
    } catch (YarnClientException e) {
      throw new ClientException("Failed to start Drill application master", e);
    }
  }

  /**
   * Write the app id file needed for subsequent commands. The app id file is
   * the only way we know the YARN application associated with our Drill-on-YARN
   * session. This file is ready by subsequent status, resize and stop commands
   * so we can find our Drill AM on the YARN cluster.
   *
   * @throws ClientException
   */

  private void writeAppIdFile() throws ClientException {
    // Write the appid file that lets us work with the app later
    // (Analogous to a pid file.)
    // File goes into the directory above Drill Home (which should be the
    // folder that contains the localized archive) and is named for the
    // ZK cluster (to ensure that the name is a valid file name.)

    File appIdFile = ClientCommand.getAppIdFile();
    try {
      PrintWriter writer = new PrintWriter(new FileWriter(appIdFile));
      writer.println(appId);
      writer.close();
    } catch (IOException e) {
      throw new ClientException(
          "Failed to write appid file: " + appIdFile.getAbsolutePath());
    }
  }

  /**
   * Poll YARN to track the launch process of the application so that we can
   * wait until the AM is live before pointing the user to the AM's web UI.
   */

  private class StartMonitor {
    StatusCommand.Reporter reporter;
    private YarnApplicationState state;
    private int pollWaitSec;
    private int startupWaitSec;

    public StartMonitor() {
      pollWaitSec = config.getInt(DrillOnYarnConfig.CLIENT_POLL_SEC);
      if (pollWaitSec < 1) {
        pollWaitSec = 1;
      }
      startupWaitSec = config.getInt(DrillOnYarnConfig.CLIENT_START_WAIT_SEC);
    }

    void run(String appName) throws ClientException {
      System.out.print("Launching " + appName + "...");
      reporter = new StatusCommand.Reporter(client);
      reporter.getReport();
      if (!reporter.isStarting()) {
        return;
      }
      updateState(reporter.getState());
      try {
        int attemptCount = startupWaitSec / pollWaitSec;
        for (int attempt = 0; attempt < attemptCount; attempt++) {
          if (!poll()) {
            break;
          }
        }
      } finally {
        System.out.println();
      }
      reporter.display(verbose, true);
      if (reporter.isStarting()) {
        System.out.println(
            "Application Master is slow to start, use the 'status' command later to check status.");
      }
    }

    private boolean poll() throws ClientException {
      try {
        Thread.sleep(pollWaitSec * 1000);
      } catch (InterruptedException e) {
        return false;
      }
      reporter.getReport();
      if (!reporter.isStarting()) {
        return false;
      }
      YarnApplicationState newState = reporter.getState();
      if (newState == state) {
        System.out.print(".");
        return true;
      }
      System.out.println();
      updateState(newState);
      return true;
    }

    private void updateState(YarnApplicationState newState) {
      state = newState;
      if (verbose) {
        System.out.print("Application State: ");
        System.out.println(state.toString());
        System.out.print("Starting...");
      }
    }
  }

  private void waitForStartAndReport(String appName) throws ClientException {
    StartMonitor monitor = new StartMonitor();
    monitor.run(appName);
  }
}


text:
import _ from 'lodash';
import { Observable } from 'rx';
import {
  combineActions,
  createAction,
  createAsyncTypes,
  createTypes,
  handleActions
} from 'berkeleys-redux-utils';
import { createSelector } from 'reselect';

import fetchUserEpic from './fetch-user-epic.js';
import updateMyCurrentChallengeEpic from './update-my-challenge-epic.js';
import fetchChallengesEpic from './fetch-challenges-epic.js';
import navSizeEpic from './nav-size-epic.js';

import { createFilesMetaCreator } from '../files';
import { updateThemeMetacreator, entitiesSelector } from '../entities';
import { types as challenges } from '../routes/Challenges/redux';
import { challengeToFiles } from '../routes/Challenges/utils';

import ns from '../ns.json';

import { themes, invertTheme } from '../../utils/themes.js';

export const epics = [
  fetchUserEpic,
  fetchChallengesEpic,
  updateMyCurrentChallengeEpic,
  navSizeEpic
];

export const types = createTypes([
  'onRouteHome',

  'appMounted',
  'analytics',
  'updateTitle',

  createAsyncTypes('fetchChallenge'),
  createAsyncTypes('fetchChallenges'),

  createAsyncTypes('fetchUser'),
  'showSignIn',

  'handleError',
  // used to hit the server
  'hardGoTo',
  'delayedRedirect',

  // night mode
  'toggleNightMode',
  'postThemeComplete'
], ns);

const throwIfUndefined = () => {
  throw new TypeError('Argument must not be of  type `undefined`');
};

// createEventMetaCreator({
//   category: String,
//   action: String,
//   label?: String,
//   value?: Number
// }) => () => Object
export const createEventMetaCreator = ({
  // categories are features or namespaces of the app (capitalized):
  //   Map, Nav, Challenges, and so on
  category = throwIfUndefined,
  // can be a one word the event
  // click, play, toggle.
  // This is not a hard and fast rule
  action = throwIfUndefined,
  // any additional information
  // when in doubt use redux action type
  // or a short sentence describing the action
  label,
  // used to tack some specific value for a GA event
  value
} = throwIfUndefined) => () => ({
  analytics: {
    type: 'event',
    category,
    action,
    label,
    value
  }
});

export const onRouteHome = createAction(types.onRouteHome);
export const appMounted = createAction(types.appMounted);
export const fetchChallenge = createAction(
  '' + types.fetchChallenge,
  (dashedName, block) => ({ dashedName, block })
);
export const fetchChallengeCompleted = createAction(
  types.fetchChallenge.complete,
  null,
  meta => ({
    ...meta,
    ..._.flow(challengeToFiles, createFilesMetaCreator)(meta.challenge)
  })
);
export const fetchChallenges = createAction('' + types.fetchChallenges);
export const fetchChallengesCompleted = createAction(
  types.fetchChallenges.complete,
  (entities, result) => ({ entities, result }),
  entities => ({ entities })
);

// updateTitle(title: String) => Action
export const updateTitle = createAction(types.updateTitle);

// fetchUser() => Action
// used in combination with fetch-user-epic
export const fetchUser = createAction(types.fetchUser);
export const fetchUserComplete = createAction(
  types.fetchUser.complete,
  ({ result }) => result,
  _.identity
);

export const showSignIn = createAction(types.showSignIn);

// used when server needs client to redirect
export const delayedRedirect = createAction(types.delayedRedirect);

// hardGoTo(path: String) => Action
export const hardGoTo = createAction(types.hardGoTo);

export const createErrorObservable = error => Observable.just({
  type: types.handleError,
  error
});
// doActionOnError(
//   actionCreator: (() => Action|Null)
// ) => (error: Error) => Observable[Action]
export const doActionOnError = actionCreator => error => Observable.of(
  {
    type: types.handleError,
    error
  },
  actionCreator()
);

export const toggleNightMode = createAction(
  types.toggleNightMode,
  null,
  (username, theme) => updateThemeMetacreator(username, invertTheme(theme))
);
export const postThemeComplete = createAction(
  types.postThemeComplete,
  null,
  updateThemeMetacreator
);

const defaultState = {
  title: 'Learn To Code | freeCodeCamp',
  isSignInAttempted: false,
  user: '',
  csrfToken: '',
  // eventually this should be only in the user object
  currentChallenge: '',
  superBlocks: []
};

export const getNS = state => state[ns];
export const csrfSelector = state => getNS(state).csrfToken;
export const titleSelector = state => getNS(state).title;

export const currentChallengeSelector = state => getNS(state).currentChallenge;
export const superBlocksSelector = state => getNS(state).superBlocks;
export const signInLoadingSelector = state => !getNS(state).isSignInAttempted;

export const usernameSelector = state => getNS(state).user || '';
export const userSelector = createSelector(
  state => getNS(state).user,
  state => entitiesSelector(state).user,
  (username, userMap) => userMap[username] || {}
);

export const themeSelector = _.flow(
  userSelector,
  user => user.theme || themes.default
);

export const isSignedInSelector = state => !!userSelector(state).username;

export const challengeSelector = state => {
  const challengeName = currentChallengeSelector(state);
  const challengeMap = entitiesSelector(state).challenge || {};
  return challengeMap[challengeName] || {};
};

export const previousSolutionSelector = state => {
  const { id } = challengeSelector(state);
  const { challengeMap = {} } = userSelector(state);
  return challengeMap[id];
};

export const firstChallengeSelector = createSelector(
  entitiesSelector,
  superBlocksSelector,
  (
    {
      challengeMap,
      blockMap,
      superBlockMap
    },
    superBlocks
  ) => {
    if (
      !challengeMap ||
      !blockMap ||
      !superBlockMap ||
      !superBlocks
    ) {
      return {};
    }
    try {
      return challengeMap[
        blockMap[
          superBlockMap[
            superBlocks[0]
          ].blocks[0]
        ].challenges[0]
      ];
    } catch (err) {
      console.error(err);
      return {};
    }
  }
);

export default handleActions(
  () => ({
    [types.updateTitle]: (state, { payload = 'Learn To Code' }) => ({
      ...state,
      title: payload + ' | freeCodeCamp'
    }),

    [types.fetchUser.complete]: (state, { payload: user }) => ({
      ...state,
      user
    }),
    [combineActions(
      types.fetchChallenge.complete,
      types.fetchChallenges.complete
    )]: (state, { payload }) => ({
      ...state,
      superBlocks: payload.result.superBlocks
    }),
    [challenges.onRouteChallenges]: (state, { payload: { dashedName } }) => ({
      ...state,
      currentChallenge: dashedName
    }),
    [
      combineActions(types.showSignIn, types.fetchUser.complete)
    ]: state => ({
      ...state,
      isSignInAttempted: true
    }),

    [types.challengeSaved]: (state, { payload: { points = 0 } }) => ({
      ...state,
      points
    }),
    [types.delayedRedirect]: (state, { payload }) => ({
      ...state,
      delayedRedirect: payload
    })
  }),
  defaultState,
  ns
);


text:
/**
 * An object for the internal representation of a cluster.
 * @param {number} x The x coordinate of the cluster.
 * @param {number} sumX The sum of x coordinates of the clustered objects.
 * @param {number} y The y coordinate of the cluster.
 * @param {number} sumY The sum of y coordinates of the clustered objects.
 * @param {!Array.<number>} indices The indices of the clustered objects.
 * @param {number} index The index of this object in array of clusters.
 * @constructor
 * @implements {KdData}
 * @struct
 */
function ClusterObject(x, sumX, y, sumY, indices, index) {
  /**
   * @type {number}
   */
  this.x = x;

  /**
   * @type {number}
   */
  this.sumX = sumX;

  /**
   * @type {number}
   */
  this.y = y;

  /**
   * @type {number}
   */
  this.sumY = sumY;

  /**
   * @type {!Array.<number>}
   */
  this.indices = indices;

  /**
   * @type {boolean}
   */
  this.valid = true;

  /**
   * @type {number}
   */
  this.index = index;
}


text:
"""Train state for passing around objects during training."""

from typing import Any, Mapping, MutableMapping, Optional, Tuple

from flax import traverse_util
import flax.core
from flax.core import scope as flax_scope
from flax.linen import partitioning as flax_partitioning
import flax.serialization
import flax.struct
import jax.numpy as jnp
from t5x import optimizers

import typing_extensions

EMPTY_DICT = flax.core.freeze({})
FrozenDict = flax_scope.FrozenDict
FrozenVariableDict = flax_scope.FrozenVariableDict
MutableVariableDict = flax_scope.MutableVariableDict
VariableDict = flax_scope.VariableDict

@typing_extensions.runtime_checkable
class TrainState(typing_extensions.Protocol):
  """TrainState interface."""

  @property
  def step(self) -> jnp.ndarray:
    """The current training step as an integer scalar."""
    ...

  @property
  def params(self) -> FrozenVariableDict:
    """The parameters of the model as a PyTree matching the Flax module."""
    ...

  @property
  def param_states(self) -> FrozenVariableDict:
    """The optimizer states of the parameters as a PyTree."""
    ...

  @property
  def flax_mutables(self) -> FrozenVariableDict:
    """Flax mutable collection."""
    ...

  def state_dict(self) -> MutableVariableDict:
    """Returns a mutable representation of the state for checkpointing."""
    ...

  def restore_state(self, state_dict: Mapping[str, Any]) -> 'TrainState':
    """Restores the object state from a state dict."""
    ...

  def replace_params(self, params: VariableDict) -> 'TrainState':
    ...

  def replace_flax_mutables(self, flax_mutables: FrozenDict) -> 'TrainState':
    ...

  def replace_step(self, step: jnp.ndarray) -> 'TrainState':
    ...

  def apply_gradient(self,
                     grads,
                     learning_rate,
                     flax_mutables=EMPTY_DICT) -> 'TrainState':
    """Applies gradient, increments step, and returns an updated TrainState."""
    ...

  def as_logical_axes(self) -> 'TrainState':
    """Replaces `param` and `param-states` with their logical axis names."""
    ...

def _validate_params_axes(params_axes, params):
  axis_names = flax_partitioning.get_axis_names(params_axes)
  missing_params_axes = (
      set(traverse_util.flatten_dict(params, sep='/')) -
      set(traverse_util.flatten_dict(axis_names, sep='/')))
  if missing_params_axes:
    raise ValueError(
        f'Missing axis names for parameters: {missing_params_axes}')

def _split_variables_and_axes(
    variables_and_axes: FrozenVariableDict
) -> Tuple[FrozenVariableDict, FrozenVariableDict]:
  """Splits `variables_and_axes` into two separate dicts with the same keys."""
  # For each `key`, `key_axes` (if any) are its axes in `variables_and_axes`.
  variables = {}
  axes = {}
  for k, v in variables_and_axes.items():
    if k.endswith('_axes'):
      axes[k[:-5]] = v  # k without "_axes".
      _validate_params_axes(v, variables_and_axes[k[:-5]])  # k without "_axes".
    else:
      variables[k] = v
  return flax.core.freeze(variables), flax.core.freeze(axes)

class FlaxOptimTrainState(flax.struct.PyTreeNode):
  """Simple train state for holding parameters, step, optimizer state."""
  _optimizer: optimizers.OptimizerType
  # Contains axis metadata (e.g., names) matching parameter tree.
  params_axes: Optional[FrozenVariableDict] = None
  # Flax mutable fields.
  flax_mutables: FrozenDict = EMPTY_DICT
  # Contains axis metadata (e.g., names) matching flax_mutables tree.
  flax_mutables_axes: Optional[FrozenVariableDict] = None

  @classmethod
  def create(cls, optimizer_def: optimizers.OptimizerDefType,
             model_variables: FrozenVariableDict) -> 'FlaxOptimTrainState':
    other_variables, params = model_variables.pop('params')
    if 'params_axes' in other_variables:
      other_variables, params_axes = other_variables.pop('params_axes')
      _validate_params_axes(params_axes, params)
    else:
      params_axes = None

    # Split other_variables into mutables and their corresponding axes.
    flax_mutables, flax_mutables_axes = _split_variables_and_axes(
        other_variables)

    # If the optimizer supports `set_param_axes`, then assume that the model
    # code is emitting these axes and use it.
    if hasattr(optimizer_def, 'set_param_axes'):
      if params_axes is None:
        raise ValueError('The optimizer supports params_axes for model-based '
                         'partitioning, but the model is not emitting them.')
      # `get_axis_names` removes "_axes" suffix in the leaf name and replaces
      # `AxisMetadata` with `PartitionSpec`.
      axis_names = flax_partitioning.get_axis_names(params_axes)
      optimizer_def.set_param_axes(axis_names)

    optimizer = optimizer_def.create(params)
    flax_mutables_axes = flax_mutables_axes or None
    return FlaxOptimTrainState(
        optimizer,
        params_axes=params_axes,
        flax_mutables=flax_mutables,
        flax_mutables_axes=flax_mutables_axes)

  @property
  def step(self) -> jnp.ndarray:
    return self._optimizer.state.step

  @property
  def params(self) -> FrozenVariableDict:
    return self._optimizer.target

  @property
  def param_states(self) -> FrozenVariableDict:
    return self._optimizer.state.param_states

  def state_dict(self) -> MutableVariableDict:
    state_dict = self._optimizer.state_dict()
    if self.flax_mutables:
      state_dict['flax_mutables'] = flax.core.unfreeze(self.flax_mutables)
    return state_dict

  def apply_gradient(self,
                     grads,
                     learning_rate,
                     flax_mutables=EMPTY_DICT) -> 'FlaxOptimTrainState':
    new_optimizer = self._optimizer.apply_gradient(
        grads, learning_rate=learning_rate)
    return self.replace(_optimizer=new_optimizer, flax_mutables=flax_mutables)

  def replace_params(self, params: VariableDict) -> 'FlaxOptimTrainState':
    return self.replace(_optimizer=self._optimizer.replace(target=params))

  def replace_flax_mutables(self,
                            flax_mutables: FrozenDict) -> 'FlaxOptimTrainState':
    return self.replace(flax_mutables=flax_mutables)

  def replace_step(self, step: jnp.ndarray) -> 'FlaxOptimTrainState':
    state_dict = self.state_dict()
    state_dict['state']['step'] = step
    return self.restore_state(state_dict)

  def restore_state(self, state_dict: VariableDict) -> 'FlaxOptimTrainState':
    new_optimizer = self._optimizer.restore_state(state_dict)
    return self.replace(
        _optimizer=new_optimizer,
        flax_mutables=flax.core.freeze(state_dict['flax_mutables'])
        if 'flax_mutables' in state_dict else EMPTY_DICT)

  def as_logical_axes(self) -> 'FlaxOptimTrainState':
    if not hasattr(self._optimizer.optimizer_def, 'derive_logical_axes'):
      raise ValueError(
          f"Optimizer '{self._optimizer.optimizer_def.__class__.__name__}' "
          'requires a `derive_logical_axes` method to be used with named axis '
          'partitioning.')
    flax_mutables_axes = self.flax_mutables_axes or EMPTY_DICT
    return FlaxOptimTrainState(
        _optimizer=self._optimizer.optimizer_def.derive_logical_axes(
            self._optimizer,
            flax_partitioning.get_axis_names(self.params_axes)),
        flax_mutables=flax_partitioning.get_axis_names(flax_mutables_axes))

class InferenceState(flax.struct.PyTreeNode):
  """State compatible with FlaxOptimTrainState without optimizer state."""

  step: jnp.ndarray
  params: flax_scope.FrozenVariableDict
  params_axes: Optional[flax_scope.FrozenVariableDict] = None
  flax_mutables: flax_scope.FrozenDict = EMPTY_DICT
  flax_mutables_axes: Optional[flax_scope.FrozenVariableDict] = None

  @classmethod
  def create(cls, model_variables: FrozenVariableDict) -> 'InferenceState':
    other_variables, params = model_variables.pop('params')
    if 'params_axes' in other_variables:
      other_variables, params_axes = other_variables.pop('params_axes')
      _validate_params_axes(params_axes, params)
    else:
      params_axes = None

    # Split other_variables into mutables and their corresponding axes.
    flax_mutables, flax_mutables_axes = _split_variables_and_axes(
        other_variables)
    flax_mutables_axes = flax_mutables_axes or None
    return InferenceState(
        step=jnp.array(0),
        params=params,
        params_axes=params_axes,
        flax_mutables=flax_mutables,
        flax_mutables_axes=flax_mutables_axes)

  @property
  def param_states(self) -> FrozenVariableDict:
    """The optimizer states of the parameters as a PyTree."""
    raise NotImplementedError('InferenceState has no optimizer states.')

  def apply_gradient(self, *args, **kwargs) -> 'InferenceState':
    raise NotImplementedError(
        'InferenceState does not support `apply_gradient`.')

  def state_dict(self) -> MutableMapping[str, Any]:
    state_dict = {
        'target': flax.core.unfreeze(self.params),
        'state': {
            'step': self.step
        }
    }
    if self.flax_mutables:
      state_dict['flax_mutables'] = flax.core.unfreeze(self.flax_mutables)
    return state_dict

  def replace_step(self, step: jnp.ndarray) -> 'InferenceState':
    return self.replace(step=step)

  def replace_params(self, params: FrozenVariableDict) -> 'InferenceState':
    return self.replace(params=params)

  def replace_flax_mutables(self,
                            flax_mutables: FrozenDict) -> 'InferenceState':
    return self.replace(flax_mutables=flax_mutables)

  def restore_state(self, state_dict: Mapping[str, Any]) -> 'InferenceState':
    return self.replace(
        params=flax.core.freeze(state_dict['target']),
        step=state_dict['state']['step'],
        flax_mutables=flax.core.freeze(state_dict['flax_mutables'])
        if 'flax_mutables' in state_dict else EMPTY_DICT)

  def as_logical_axes(self) -> 'InferenceState':
    # Set step to None so that when the logical axes are processed by the
    # flax.partitioning.logical_to_mesh_axes function, it will be skipped
    # because jax.tree_map will short circut and never call the function on the
    # step.
    flax_mutables_axes = self.flax_mutables_axes or EMPTY_DICT
    return InferenceState(
        step=None,
        params=flax_partitioning.get_axis_names(self.params_axes),
        flax_mutables=flax_partitioning.get_axis_names(flax_mutables_axes))


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
    <type>org.netbeans.modules.php.project</type>
    <configuration>
        <data xmlns="http://www.netbeans.org/ns/php-project/1">
            <name>wishlist</name>
        </data>
    </configuration>
</project>


text:
package com.lfdversluis.retrofittwitchapi;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import com.lfdversluis.retrofittwitchapi.API.TwitchAPI;

import retrofit.RequestInterceptor;
import retrofit.RestAdapter;

public class MainActivity extends Activity {

    private final String LOG_TAG = "MainActivity";
    private final String oauthToken = "";
    private final String clientId = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public void onStart(){
        super.onStart();

        RequestInterceptor requestInterceptor = new RequestInterceptor() {
            @Override
            public void intercept(RequestFacade request) {
                request.addHeader("Accept", "application/vnd.twitchtv.v3+json");
                request.addHeader("Client-ID", clientId);
            }
        };

        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint("https://api.twitch.tv/kraken")
                .setRequestInterceptor(requestInterceptor)
                .setLogLevel(RestAdapter.LogLevel.FULL).setLog(new RestAdapter.Log() {
                    public void log(String msg) {
                        Log.i("retrofit", msg);
                    }
                })
                .build();

        TwitchAPI api = restAdapter.create(TwitchAPI.class);

        /********************************************************************
         * TWITCH USER EXAMPLE
         *******************************************************************/
/*
        api.getUserByName("cookieandegg", new Callback<TwitchUser>() {
            @Override
            public void success(TwitchUser user, Response response) {
                Log.e("getUserByName ex.", user.getName()+""); //
                // Some items can be null if queried by getUserByName (not authenticated)!
                Log.e("getUserByName ex.", user.getNotifications()+""); //
            }

            @Override
            public void failure(RetrofitError error) {
                Log.e("getUserByName ex.", "FAILED: " + error.toString());
            }
        });
*/

        /********************************************************************
         * TWITCH CHANNEL EXAMPLE
         *******************************************************************/

/*
        api.getChannelByName("cookieandegg", new Callback<TwitchChannel>() {
            @Override
            public void success(TwitchChannel channel, Response response) {
                Log.e("getChannelByName ex.", channel.getStatus());

                // Some items can be null (not present) when you do an unauthenticated call:
                // Differences in the returns can be observed at https://github.com/justintv/Twitch-API/blob/master/v3_resources/channels.md
                Log.e("getChannelByName ex.", channel.getStreamKey()+"");
            }

            @Override
            public void failure(RetrofitError error) {
                Log.e("getChannelByName ex.", "FAILED: " + error.toString());
            }
        });
*/

        // update example

/*
        final JSONObject updateObject = new JSONObject();
        JSONObject channelObject = new JSONObject();
        try {
            channelObject.put("status", "Awesome Test Title");
            channelObject.put("game", "Counter-Strike: Global Offensive");
            channelObject.put("delay", 0);
            updateObject.put("channel", channelObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        api.updateChannel(oauthToken, "cookieandegg", new TypedJSONString(updateObject.toString()), new Callback<TwitchChannel>() {
            @Override
            public void success(TwitchChannel channel, Response response) {
                Log.e("Update channel ex.", "Success");
            }

            @Override
            public void failure(RetrofitError error) {
                Log.e("Update channel ex.", "FAILED: " + error.toString());
            }
        });

*/
        /********************************************************************
         * STREAM FOLLOWERS EXAMPLE
         *******************************************************************/
/*
        api.getChannelFollowers("cookieandegg", 2, 0, "desc", new Callback<TwitchChannelFollowers>() {
            @Override
            public void success(TwitchChannelFollowers followers, Response response) {
                Log.e("Channel followers ex.", followers.getTotal()+"");
                for(TwitchChannelFollowers.Follower follower : followers.getFollows()){
                    Log.e("Channel followers ex.", follower.getUser().getName());
                }
            }

            @Override
            public void failure(RetrofitError error) {
                Log.e("Channel followers ex.", error.toString());
            }
        });
*/

        /********************************************************************
         * CHANNEL VIDEOS EXAMPLE
         *******************************************************************/
/*
        api.getChannelVideos("amazhs", 2, 0, false, false, "all", new Callback<TwitchChannelVideos>() {
            @Override
            public void success(TwitchChannelVideos videos, Response response) {
                for(TwitchChannelVideos.Video video : videos.getVideos()){
                    Log.e("Channel vid ex.", video.getTitle());
                }
            }

            @Override
            public void failure(RetrofitError error) {
                Log.e("Channel vid ex.", error.toString());
            }
        });
*/

        /********************************************************************
         * FOLLOWED STREAMS EXAMPLE
         *******************************************************************/
/*
        api.getFollowedStreams(oauthToken, 2, 0, new Callback<TwitchFollowedStreams>() {
            @Override
            public void success(TwitchFollowedStreams streams, Response response) {
                for(TwitchFollowedStreams.Stream stream : streams.getStreams()){
                    Log.e("Followed streams ex.", stream.getChannel().getStatus());
                }
            }

            @Override
            public void failure(RetrofitError error) {
                Log.e("Followed streams ex.", error.toString());
            }
        });
*/

        /********************************************************************
         * FOLLOWED CHANNELS EXAMPLE
         *******************************************************************/
/*
        api.getFollowedChannels("cookieandegg", 2, 0, "desc", "created_at", new Callback<TwitchFollowedChannels>() {
            @Override
            public void success(TwitchFollowedChannels channels, Response response) {
                for(TwitchFollowedChannels.Follow follow : channels.getFollows()){
                    Log.e("Followed channel ex.", follow.getChannel().getStatus());
                }
            }

            @Override
            public void failure(RetrofitError error) {
                Log.e("Followed channel ex.", error.toString());
            }
        });
*/
        /********************************************************************
         * BLOCKED USERS EXAMPLE
         *******************************************************************/
/*
        api.getBlockedUsers(oauthToken, "cookieandegg", 2, 0, new Callback<TwitchBlockedUsers>() {
            @Override
            public void success(TwitchBlockedUsers blocks, Response response) {
                for(TwitchBlockedUsers.Block blockedUser : blocks.getBlocks()){
                    Log.e("Blocked users ex.", blockedUser.getUser().getDisplayName());
                }
            }

            @Override
            public void failure(RetrofitError error) {
                Log.e("Blocked users ex.", error.toString());
            }
        });
*/
        /********************************************************************
         * CHANNEL SUBSCRIBERS EXAMPLE - MUST BE TWITCH PARTNERED OR IT FAILS
         *******************************************************************/
/*
        api.getChannelSubscribers(oauthToken, "cookieandegg", 2, 0, "asc", new Callback<TwitchChannelSubscribers>() {
            @Override
            public void success(TwitchChannelSubscribers subscribers, Response response) {
                for(TwitchChannelSubscribers.Subscription subscription : subscribers.getSubscriptions()){
                    Log.e("Channel subscriber ex.", subscription.getUser().getDisplayName());
                }
            }

            @Override
            public void failure(RetrofitError error) {
                Log.e("Channel subscriber ex.", error.toString());
            }
        });
*/
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


text:
import numpy as np

def initialize(self,runInfoDict,inputFiles):
  self.response = 3.0
  return

def run(self,Input):
  dim = 308
  # use a to represent the sensitivity
  senVec = np.loadtxt('sensitivity.txt')
  #senVec = np.random.rand(dim)
  varBase = 'x_'
  inputVar = []
  for i in range(dim):
    varname = varBase + str(i)
    inputVar.append(Input[varname])
  inputVar = np.asarray(inputVar)
  self.response = np.dot(senVec,inputVar)


text:
<?php

use ChurchCRM\dto\SystemURLs;

//Set the page title
$sPageTitle = gettext("Change Password") .": " . $user->getFullName();
include SystemURLs::getDocumentRoot() . '/Include/Header.php';
?>

                <?= gettext('Enter new user password. Administratively set passwords are not subject to length or complexity requirements') . '
' ?>

            <form method="post" action="">

                            <?= gettext('New Password') ?>:
                        <input type="password" name="NewPassword1" id="NewPassword1" class="form-control" value="<?= $sNewPassword1 ?>">

                        <?= gettext('Confirm New Password') ?>:
                        <input type="password" name="NewPassword2" id="NewPassword2"  class="form-control" value="<?= $sNewPassword2 ?>"><?= $sNewPasswordError ?>

                    <input type="submit" class="btn btn-primary" name="Submit" value="<?= gettext('Save') ?>">

            </form>

<?php include SystemURLs::getDocumentRoot() . '/Include/Footer.php'; ?>


text:
module ConsoleCommand
  VERSION = "0.0.2"
end


text:
package com.northernwall.hadrian.handlers.ssh;

import com.google.gson.Gson;
import com.northernwall.hadrian.access.AccessHelper;
import com.northernwall.hadrian.db.DataAccess;
import com.northernwall.hadrian.domain.Team;
import com.northernwall.hadrian.handlers.BasicHandler;
import com.northernwall.hadrian.handlers.ssh.dao.PostSshData;
import com.northernwall.hadrian.sshAccess.SshAccess;
import com.northernwall.hadrian.sshAccess.SshEntry;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Request;

/**
 *
 * @author Richard
 */
public class SshUpdateHandler extends BasicHandler {
    private final SshAccess sshAccess;
    private final AccessHelper accessHelper;

    public SshUpdateHandler(DataAccess dataAccess, Gson gson, SshAccess sshAccess, AccessHelper accessHelper) {
        super(dataAccess, gson);
        this.sshAccess = sshAccess;
        this.accessHelper = accessHelper;
    }

    @Override
    public void handle(String target, Request request, HttpServletRequest httpRequest, HttpServletResponse response) throws IOException, ServletException {
        PostSshData data = fromJson(request, PostSshData.class);
        Team team = getTeam(request);
        accessHelper.canUserModify(request, team);

        List<SshEntry> sshEntries = sshAccess.getSshEntries();

        if (data.sshGrants != null && !data.sshGrants.isEmpty()) {
            team.getSshEntries().clear();
            for (SshEntry entry : data.sshGrants) {
                addEntry(entry, sshEntries, team);
            }
            getDataAccess().saveTeam(team);
        }

        response.setStatus(200);
        request.setHandled(true);
    }

    private void addEntry(SshEntry entry, List<SshEntry> sshEntries, Team team) {
        for (SshEntry sshEntry : sshEntries) {
            if (sshEntry.equals(entry)) {
                return;
            }
        }
    }

}


text:
#include "config.h"
#include "core/dom/TreeWalker.h"

#include "bindings/v8/ScriptState.h"
#include "core/dom/ContainerNode.h"
#include "core/dom/ExceptionCode.h"
#include "core/dom/NodeFilter.h"
#include "core/dom/NodeTraversal.h"
#include <wtf/PassRefPtr.h>

namespace WebCore {

TreeWalker::TreeWalker(PassRefPtr<Node> rootNode, unsigned whatToShow, PassRefPtr<NodeFilter> filter)
    : Traversal(rootNode, whatToShow, filter)
    , m_current(root())
{
    ScriptWrappable::init(this);
}

void TreeWalker::setCurrentNode(PassRefPtr<Node> node, ExceptionCode& ec)
{
    if (!node) {
        ec = NOT_SUPPORTED_ERR;
        return;
    }
    m_current = node;
}

inline Node* TreeWalker::setCurrent(PassRefPtr<Node> node)
{
    m_current = node;
    return m_current.get();
}

Node* TreeWalker::parentNode(ScriptState* state)
{
    RefPtr<Node> node = m_current;
    while (node != root()) {
        node = node->parentNode();
        if (!node)
            return 0;
        short acceptNodeResult = acceptNode(state, node.get());
        if (state && state->hadException())
            return 0;
        if (acceptNodeResult == NodeFilter::FILTER_ACCEPT)
            return setCurrent(node.release());
    }
    return 0;
}

Node* TreeWalker::firstChild(ScriptState* state)
{
    for (RefPtr<Node> node = m_current->firstChild(); node; ) {
        short acceptNodeResult = acceptNode(state, node.get());
        if (state && state->hadException())
            return 0;
        switch (acceptNodeResult) {
            case NodeFilter::FILTER_ACCEPT:
                m_current = node.release();
                return m_current.get();
            case NodeFilter::FILTER_SKIP:
                if (node->firstChild()) {
                    node = node->firstChild();
                    continue;
                }
                break;
            case NodeFilter::FILTER_REJECT:
                break;
        }
        do {
            if (node->nextSibling()) {
                node = node->nextSibling();
                break;
            }
            ContainerNode* parent = node->parentNode();
            if (!parent || parent == root() || parent == m_current)
                return 0;
            node = parent;
        } while (node);
    }
    return 0;
}

Node* TreeWalker::lastChild(ScriptState* state)
{
    for (RefPtr<Node> node = m_current->lastChild(); node; ) {
        short acceptNodeResult = acceptNode(state, node.get());
        if (state && state->hadException())
            return 0;
        switch (acceptNodeResult) {
            case NodeFilter::FILTER_ACCEPT:
                m_current = node.release();
                return m_current.get();
            case NodeFilter::FILTER_SKIP:
                if (node->lastChild()) {
                    node = node->lastChild();
                    continue;
                }
                break;
            case NodeFilter::FILTER_REJECT:
                break;
        }
        do {
            if (node->previousSibling()) {
                node = node->previousSibling();
                break;
            }
            ContainerNode* parent = node->parentNode();
            if (!parent || parent == root() || parent == m_current)
                return 0;
            node = parent;
        } while (node);
    }
    return 0;
}

Node* TreeWalker::previousSibling(ScriptState* state)
{
    RefPtr<Node> node = m_current;
    if (node == root())
        return 0;
    while (1) {
        for (RefPtr<Node> sibling = node->previousSibling(); sibling; ) {
            short acceptNodeResult = acceptNode(state, sibling.get());
            if (state && state->hadException())
                return 0;
            switch (acceptNodeResult) {
                case NodeFilter::FILTER_ACCEPT:
                    m_current = sibling.release();
                    return m_current.get();
                case NodeFilter::FILTER_SKIP:
                    if (sibling->lastChild()) {
                        sibling = sibling->lastChild();
                        node = sibling;
                        continue;
                    }
                    break;
                case NodeFilter::FILTER_REJECT:
                    break;
            }
            sibling = sibling->previousSibling();
        }
        node = node->parentNode();
        if (!node || node == root())
            return 0;
        short acceptNodeResult = acceptNode(state, node.get());
        if (state && state->hadException())
            return 0;
        if (acceptNodeResult == NodeFilter::FILTER_ACCEPT)
            return 0;
    }
}

Node* TreeWalker::nextSibling(ScriptState* state)
{
    RefPtr<Node> node = m_current;
    if (node == root())
        return 0;
    while (1) {
        for (RefPtr<Node> sibling = node->nextSibling(); sibling; ) {
            short acceptNodeResult = acceptNode(state, sibling.get());
            if (state && state->hadException())
                return 0;
            switch (acceptNodeResult) {
                case NodeFilter::FILTER_ACCEPT:
                    m_current = sibling.release();
                    return m_current.get();
                case NodeFilter::FILTER_SKIP:
                    if (sibling->firstChild()) {
                        sibling = sibling->firstChild();
                        node = sibling;
                        continue;
                    }
                    break;
                case NodeFilter::FILTER_REJECT:
                    break;
            }
            sibling = sibling->nextSibling();
        }
        node = node->parentNode();
        if (!node || node == root())
            return 0;
        short acceptNodeResult = acceptNode(state, node.get());
        if (state && state->hadException())
            return 0;
        if (acceptNodeResult == NodeFilter::FILTER_ACCEPT)
            return 0;
    }
}

Node* TreeWalker::previousNode(ScriptState* state)
{
    RefPtr<Node> node = m_current;
    while (node != root()) {
        while (Node* previousSibling = node->previousSibling()) {
            node = previousSibling;
            short acceptNodeResult = acceptNode(state, node.get());
            if (state && state->hadException())
                return 0;
            if (acceptNodeResult == NodeFilter::FILTER_REJECT)
                continue;
            while (Node* lastChild = node->lastChild()) {
                node = lastChild;
                acceptNodeResult = acceptNode(state, node.get());
                if (state && state->hadException())
                    return 0;
                if (acceptNodeResult == NodeFilter::FILTER_REJECT)
                    break;
            }
            if (acceptNodeResult == NodeFilter::FILTER_ACCEPT) {
                m_current = node.release();
                return m_current.get();
            }
        }
        if (node == root())
            return 0;
        ContainerNode* parent = node->parentNode();
        if (!parent)
            return 0;
        node = parent;
        short acceptNodeResult = acceptNode(state, node.get());
        if (state && state->hadException())
            return 0;
        if (acceptNodeResult == NodeFilter::FILTER_ACCEPT)
            return setCurrent(node.release());
    }
    return 0;
}

Node* TreeWalker::nextNode(ScriptState* state)
{
    RefPtr<Node> node = m_current;
Children:
    while (Node* firstChild = node->firstChild()) {
        node = firstChild;
        short acceptNodeResult = acceptNode(state, node.get());
        if (state && state->hadException())
            return 0;
        if (acceptNodeResult == NodeFilter::FILTER_ACCEPT)
            return setCurrent(node.release());
        if (acceptNodeResult == NodeFilter::FILTER_REJECT)
            break;
    }
    while (Node* nextSibling = NodeTraversal::nextSkippingChildren(node.get(), root())) {
        node = nextSibling;
        short acceptNodeResult = acceptNode(state, node.get());
        if (state && state->hadException())
            return 0;
        if (acceptNodeResult == NodeFilter::FILTER_ACCEPT)
            return setCurrent(node.release());
        if (acceptNodeResult == NodeFilter::FILTER_SKIP)
            goto Children;
    }
    return 0;
}

} // namespace WebCore


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/back"
    tools:context="com.example.chitchat.RegisterStepSixActivity" >

    <include layout="@layout/title" />

    <View
        android:id="@id/line1"
        android:layout_width="fill_parent"
        android:layout_height="1.0px"
        android:layout_marginTop="90.0dip"
        android:background="@color/clbg_diliver_color" />

    <RelativeLayout
        android:id="@id/rlGroup"
        android:layout_width="fill_parent"
        android:layout_height="170.0dip"
        android:layout_below="@id/line1"
        android:background="#ffffffff"
        android:paddingRight="22.0dip" >

        <FrameLayout
            android:id="@id/flPortrait"
            android:layout_width="101.0dip"
            android:layout_height="101.0dip"
            android:layout_centerVertical="true"
            android:layout_marginLeft="25.0dip"
            android:layout_marginRight="24.0dip"
            android:background="@drawable/shape_portrait_border_gray" >

            <ImageView
                android:id="@id/ivPortrait"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_margin="@dimen/portrait_padding"
                android:src="@drawable/bg_avatar" />
        </FrameLayout>

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@id/flPortrait" >

            <LinearLayout
                android:id="@id/llAlbum"
                android:layout_width="fill_parent"
                android:layout_height="48.0dip"
                android:background="@drawable/bg_group_search_buttons"
                android:clickable="true"
                android:gravity="center_vertical"
                android:orientation="horizontal" >

                <ImageView
                    android:id="@id/ivAblum"
                    android:layout_width="23.0dip"
                    android:layout_height="20.0dip"
                    android:layout_marginLeft="37.0dip"
                    android:src="@drawable/selector_select_album" />

                <TextView
                    android:id="@id/tvAblum"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="11.0dip"
                    android:paddingBottom="2.0dip"
                    android:text="@string/activity_register_sixthstep_xiangcexuanqu"
                    android:textColor="@color/selector_color_register_button"
                    android:textSize="14.0dip" />
            </LinearLayout>

            <LinearLayout
                android:id="@id/llCamera"
                android:layout_width="fill_parent"
                android:layout_height="48.0dip"
                android:layout_below="@id/llAlbum"
                android:layout_marginTop="13.0dip"
                android:background="@drawable/bg_group_search_buttons"
                android:clickable="true"
                android:gravity="center_vertical"
                android:orientation="horizontal" >

                <ImageView
                    android:id="@id/ivCamera"
                    android:layout_width="23.0dip"
                    android:layout_height="20.0dip"
                    android:layout_marginLeft="37.0dip"
                    android:src="@drawable/selector_now_shooting" />

                <TextView
                    android:id="@id/tvCamera"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="11.0dip"
                    android:paddingBottom="1.0dip"
                    android:text="@string/activity_register_sixthstep_xianzaipaise"
                    android:textColor="@color/selector_color_register_button"
                    android:textSize="14.0dip" />
            </LinearLayout>
        </RelativeLayout>
    </RelativeLayout>

    <View
        android:layout_width="fill_parent"
        android:layout_height="1.0px"
        android:layout_below="@id/rlGroup"
        android:background="@color/clbg_diliver_color" />

</RelativeLayout>


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Structure;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure.MetadataAsSource
{
    public class PropertyDeclarationStructureTests : AbstractCSharpSyntaxNodeStructureTests<PropertyDeclarationSyntax>
    {
        protected override string WorkspaceKind => CodeAnalysis.WorkspaceKind.MetadataAsSource;
        internal override AbstractSyntaxStructureProvider CreateProvider() => new PropertyDeclarationStructureProvider();

        [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
        public async Task NoCommentsOrAttributes()
        {
            const string code = @"
class Goo
{
    {|hint:public string $$Prop {|textspan:{ get; set; }|}|}
}";

            await VerifyBlockSpansAsync(code,
                Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
        }

        [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
        public async Task WithAttributes()
        {
            const string code = @"
class Goo
{
    {|hint1:{|textspan1:[Goo]
    |}{|hint2:public string $$Prop {|textspan2:{ get; set; }|}|}|}
}";

            await VerifyBlockSpansAsync(code,
                Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: true),
                Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
        }

        [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
        public async Task WithCommentsAndAttributes()
        {
            const string code = @"
class Goo
{
    {|hint1:{|textspan1:// Summary:
    //     This is a summary.
    [Goo]
    |}{|hint2:string $$Prop {|textspan2:{ get; set; }|}|}|}
}";

            await VerifyBlockSpansAsync(code,
                Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: true),
                Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
        }

        [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
        public async Task WithCommentsAttributesAndModifiers()
        {
            const string code = @"
class Goo
{
    {|hint1:{|textspan1:// Summary:
    //     This is a summary.
    [Goo]
    |}{|hint2:public string $$Prop {|textspan2:{ get; set; }|}|}|}
}";

            await VerifyBlockSpansAsync(code,
                Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: true),
                Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
        public async Task TestProperty3()
        {
            const string code = @"
class C
{
    $${|#0:public int Goo{|textspan:
    {
        get { }
        set { }
    }|#0}
|}
    public int Goo2
    {
        get { }
        set { }
    }
}";

            await VerifyBlockSpansAsync(code,
                Region("textspan", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
        public async Task TestProperty4()
        {
            const string code = @"
class C
{
    $${|#0:public int Goo{|textspan:
    {
        get { }
        set { }
    }|#0}
|}
    public int this[int value]
    {
        get { }
        set { }
    }
}";

            await VerifyBlockSpansAsync(code,
                Region("textspan", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
        }
    }
}


text:
package org.apache.derby.impl.load;

import java.io.IOException;
import java.sql.SQLException;
import org.apache.derby.shared.common.error.ExceptionSeverity;
import org.apache.derby.shared.common.reference.SQLState;
import org.apache.derby.shared.common.error.StandardException;
import org.apache.derby.shared.common.error.PublicAPI;

/**
 * These exceptions are thrown by the import and export modules.
 *
 *
	@see SQLException
 */
class LoadError {

	/**
	 Raised if, the Derby database connection is null.
	*/

	static SQLException connectionNull() {
		return PublicAPI.wrapStandardException(
			   StandardException.newException(SQLState.CONNECTION_NULL));
	}

	/**
	   Raised if, there is data found between the stop delimiter and field/record spearator.
	   @param lineNumber Found invalid data on this line number in the data file
	   @param columnNumber Found invalid data for this column number in the data file
	*/
	static SQLException dataAfterStopDelimiter(int lineNumber, int columnNumber) {
		return PublicAPI.wrapStandardException(
			   StandardException.newException(SQLState.DATA_AFTER_STOP_DELIMITER,
											  lineNumber, columnNumber));
	}

	/**
	   Raised if, the passed data file can't be found.
	   @param fileName the data file name
	   @param ex the exception that prevented us from opening the file
	*/
	static SQLException dataFileNotFound(String fileName, Exception ex) {

		return PublicAPI.wrapStandardException(
			   StandardException.newException(SQLState.DATA_FILE_NOT_FOUND, ex,
											  fileName));
	}

	/**
	   Raised if, null is passed for data file url.
	*/
	static SQLException dataFileNull() {
    return PublicAPI.wrapStandardException(
			   StandardException.newException(SQLState.DATA_FILE_NULL));
	}
        /**
	   Raised if, data file exists.
	*/
	static SQLException dataFileExists(String fileName) {
    return PublicAPI.wrapStandardException(
			   StandardException.newException(SQLState.DATA_FILE_EXISTS, fileName));
	}
	/**
           Raised if, lob file exists.
        */
        static SQLException lobsFileExists(String fileName) {
    return PublicAPI.wrapStandardException(
                           StandardException.newException(SQLState.LOB_DATA_FILE_EXISTS, fileName));
        }
	/**
	   Raised if, the entity (ie table/view) for import/export is missing in the database.
	*/

	static SQLException entityNameMissing() {
    return PublicAPI.wrapStandardException(
		   StandardException.newException(SQLState.ENTITY_NAME_MISSING));

	}

	/**
	   Raised if, field and record separators are substring of each other.
	*/
	static SQLException fieldAndRecordSeparatorsSubset() {
		return  PublicAPI.wrapStandardException(
				StandardException.newException(SQLState.FIELD_IS_RECORD_SEPERATOR_SUBSET));
	}

	/**
	   Raised if, no column by given name is found in the resultset while importing.
	   @param columnName the resultset doesn't have this column name
	*/
	static SQLException invalidColumnName(String columnName) {
		return  PublicAPI.wrapStandardException(
				StandardException.newException(SQLState.INVALID_COLUMN_NAME , columnName));

	}

	/**
	   Raised if, no column by given number is found in the resultset while importing.
	   @param numberOfColumns the resultset doesn't have this column number
	*/
	static SQLException invalidColumnNumber(int numberOfColumns) {

		return PublicAPI.wrapStandardException(
				StandardException.newException(SQLState.INVALID_COLUMN_NUMBER, numberOfColumns ));
	}

	/**
	   Raised if, trying to export/import from an entity which has non supported
	   type columns in it.
	*/
	static SQLException nonSupportedTypeColumn(String columnName, String typeName) {
		return  PublicAPI.wrapStandardException(
				StandardException.newException(SQLState.UNSUPPORTED_COLUMN_TYPE,
											   columnName,
											   typeName));
	}

	/**
	   Raised if, in case of fixed format, don't find the record separator for a row in the data file.
	   @param lineNumber the line number with the missing record separator in the data file
	*/
	static SQLException recordSeparatorMissing(int lineNumber) {

		return  PublicAPI.wrapStandardException(
				StandardException.newException(SQLState.RECORD_SEPERATOR_MISSING,
											   lineNumber));
	}

	/**
	   Raised if, in case of fixed format, reach end of file before reading data for all the columns.
	*/
	static SQLException unexpectedEndOfFile(int lineNumber) {
    return  PublicAPI.wrapStandardException(
			StandardException.newException(SQLState.UNEXPECTED_END_OF_FILE,
										   lineNumber));
	}

	/**
	   Raised if, got IOException while writing data to the file.
	*/
	static SQLException errorWritingData(IOException ioe) {
		return PublicAPI.wrapStandardException(
			StandardException.newException(SQLState.ERROR_WRITING_DATA, ioe));
	}

	/*
	 * Raised if period(.) is used a character delimiter
	 */
	static SQLException periodAsCharDelimiterNotAllowed()
	{
		return PublicAPI.wrapStandardException(
			   StandardException.newException(SQLState.PERIOD_AS_CHAR_DELIMITER_NOT_ALLOWED));
	}

	/*
	 * Raised if same delimiter character is used for more than one delimiter
	 * type . For eg using ';' for both column delimter and character delimter
	 */
	static SQLException delimitersAreNotMutuallyExclusive()
	{
		return PublicAPI.wrapStandardException(
			   StandardException.newException(SQLState.DELIMITERS_ARE_NOT_MUTUALLY_EXCLUSIVE));
	}

	static SQLException tableNotFound(String tableName)
	{

		return PublicAPI.wrapStandardException(
			   StandardException.newException(SQLState.TABLE_NOT_FOUND, tableName));
	}

	/* Wrapper to throw an unknown excepton duing Import/Export.
	 * Typically this can be some IO error which is not generic error
	 * like the above error messages.
	 */

	static SQLException unexpectedError(Throwable t )
	{
		if (!(t instanceof SQLException))
		{
			return PublicAPI.wrapStandardException(StandardException.plainWrapException(t));
		}
		else
			return (SQLException) t;
	}

}


text:
<?php

namespace App\Tests\Unit\Controller\JobConfiguration;

use App\Entity\Job\Configuration;
use App\Services\Job\ConfigurationService;
use App\Tests\Factory\MockFactory;
use App\Tests\Factory\ModelFactory;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use App\Model\Job\TaskConfiguration\Collection as TaskConfigurationCollection;

/**
 * @group Controller/JobConfiguration
 */
class JobConfigurationControllerGetActionTest extends AbstractJobConfigurationControllerTest
{
    const JOB_CONFIGURATION_ID = 1;

    public function testGetActionJobConfigurationNotFound()
    {
        $jobConfigurationController = $this->createJobConfigurationController([
            ConfigurationService::class => MockFactory::createJobConfigurationService([
                'getById' => [
                    'with' => self::JOB_CONFIGURATION_ID,
                    'return' => null,
                ],
            ]),
        ]);

        $this->expectException(NotFoundHttpException::class);

        $jobConfigurationController->getAction(self::JOB_CONFIGURATION_ID);
    }

    public function testGetActionSuccess()
    {
        $jobConfiguration = Configuration::create(
            'foo',
            ModelFactory::createUser([
                ModelFactory::USER_EMAIL => 'user@example.com',
            ]),
            ModelFactory::createWebsite([
                ModelFactory::WEBSITE_CANONICAL_URL => 'http://foo.example.com/',
            ]),
            ModelFactory::createJobType([
                ModelFactory::JOB_TYPE_NAME => 'job type name',
            ]),
            new TaskConfigurationCollection(),
            '[]'
        );

        $jobConfigurationController = $this->createJobConfigurationController([
            ConfigurationService::class => MockFactory::createJobConfigurationService([
                'getById' => [
                    'with' => self::JOB_CONFIGURATION_ID,
                    'return' => $jobConfiguration,
                ],
            ]),
        ]);

        $response = $jobConfigurationController->getAction(self::JOB_CONFIGURATION_ID);

        $this->assertTrue($response->isSuccessful());
        $this->assertEquals($response->headers->get('content-type'), 'application/json');

        $responseData = json_decode($response->getContent(), true);
        $this->assertIsArray($responseData);
    }
}


text:
'use strict';

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

var _ContextMenu = require('./ContextMenu');

Object.defineProperty(exports, 'ContextMenu', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_ContextMenu).default;
  }
});

var _ContextMenuTrigger = require('./ContextMenuTrigger');

Object.defineProperty(exports, 'ContextMenuTrigger', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_ContextMenuTrigger).default;
  }
});

var _MenuItem = require('./MenuItem');

Object.defineProperty(exports, 'MenuItem', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_MenuItem).default;
  }
});

var _SubMenu = require('./SubMenu');

Object.defineProperty(exports, 'SubMenu', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_SubMenu).default;
  }
});

var _connectMenu = require('./connectMenu');

Object.defineProperty(exports, 'connectMenu', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_connectMenu).default;
  }
});

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