text:
<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Contrato;
use App\ItemContrato;
use App\Ente;
use App\Licitacao;
use Illuminate\Http\Request;
use Session;
use \XmlParser;

class ContratosController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\View\View
     */
    public function index(Request $request)
    {
        $keyword = $request->get('search');
        $perPage = 25;

        if (!empty($keyword)) {
            $contratos = Contrato::where('unidade_gestora', 'LIKE', "%$keyword%")
				->orWhere('data_emissao', 'LIKE', "%$keyword%")
				->orWhere('instrumento_contrato', 'LIKE', "%$keyword%")
				->orWhere('numero_contrato', 'LIKE', "%$keyword%")
				->orWhere('data_expiracao', 'LIKE', "%$keyword%")
				->orWhere('tipo', 'LIKE', "%$keyword%")
				->orWhere('fornecedor', 'LIKE', "%$keyword%")
				->orWhere('cnpj_cpf', 'LIKE', "%$keyword%")
				->orWhere('teve_aditivo', 'LIKE', "%$keyword%")
				->orWhere('processo', 'LIKE', "%$keyword%")
				->orWhere('valor', 'LIKE', "%$keyword%")
				->orWhere('descricao', 'LIKE', "%$keyword%")
				->paginate($perPage);
        } else {
            $contratos = Contrato::paginate($perPage);
        }

        return view('contratos.index', compact('contratos'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {
        $entes = Ente::all();
        $licitacoes = Licitacao::all();
        return view('contratos.create', compact('entes', 'licitacoes'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'processo' => 'required',
            'cnpj_cpf' => 'required',
            'data_emissao' => 'date_format:d/m/Y',
            'data_expiracao' => 'date_format:d/m/Y',
            //'objeto' => '',
            'ente_id' => 'required',
            ]);

        $requestData = $request->all();
        //dd($requestData);
        $requestData = array_add($requestData, "colaborador_criou_id", auth()->user()->id);
        $requestData = array_add($requestData, "tipo_cadastro", "Manual");

        Contrato::create($requestData);

        \Session::flash('flash_message',[
            'msg'=>"Contrato cadastrado com sucesso!",
            'class'=>"alert-success"
        ]);

        return redirect('contratos');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     *
     * @return \Illuminate\View\View
     */
    public function show($id)
    {
        $contrato = Contrato::findOrFail($id);

        return view('contratos.show', compact('contrato'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     *
     * @return \Illuminate\View\View
     */
    public function edit($id)
    {
        $contrato = Contrato::findOrFail($id);
        $entes = Ente::all();
        $licitacoes = Licitacao::all();

        return view('contratos.edit', compact('contrato', 'entes', 'licitacoes'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function update($id, Request $request)
    {

        $requestData = $request->all();

        $contrato = Contrato::findOrFail($id);
        $contrato->update($requestData);

        \Session::flash('flash_message',[
            'msg'=>"Contrato atualizado com sucesso!",
            'class'=>"alert-success"
        ]);

        return redirect('contratos');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function destroy($id)
    {
        Contrato::destroy($id);

        \Session::flash('flash_message',[
            'msg'=>"Contrato excluído com sucesso!",
            'class'=>"alert-success"
        ]);

        return redirect('contratos');
    }

    public function formImportar()
    {
        $entes = Ente::all();
        return view('contratos.importacao', compact('entes'));
    }

    public function importar(Request $request)
    {
        $requestData = $request->all();
        // dd($requestData);
        if($requestData['formato'] == 'XML')
        {
            // $xml = XmlParser::load($requestData['arquivo']);
            $data = file_get_contents($requestData['arquivo']);
            $xml = simplexml_load_string($data);
            // dd($xml);
            // $registros = $xml->getContent();
            // dd($xml);
            $licitacoes = [];
            for($i = 0; $i<$xml->count(); $i++){
                # code...
                // if($i == 3)
                // {
                    // dd($xml->ProcessoLicitatorio[$i]->UnidadeGestora->__toString());
                // }
                $licitacoes[$i] = Licitacao::create(
                ['unidade_gestora' => $xml->ProcessoLicitatorio[$i]->UnidadeGestora->__toString(),
                 'num_proc' => $xml->ProcessoLicitatorio[$i]->NumeroProcesso->__toString(),
                 'modalidade' => $xml->ProcessoLicitatorio[$i]->Modalidade->__toString(),
                 'tipo' => $xml->ProcessoLicitatorio[$i]->Finalidade->__toString(),
                 'situacao' => $xml->ProcessoLicitatorio[$i]->SituacaoProcesso->__toString(),
                 'data_julgamento' => $xml->ProcessoLicitatorio[$i]->DataJulgamento->__toString(),
                 'data_homologacao' => $xml->ProcessoLicitatorio[$i]->DataHomologacao->__toString(),
                 'objeto' => $xml->ProcessoLicitatorio[$i]->Objeto->__toString(),
                 'valor' => $xml->ProcessoLicitatorio[$i]->ValorProcesso->__toString(),
                 'criterio' => $xml->ProcessoLicitatorio[$i]->CriterioJulgamento->__toString(),
                 'prazo_execucao' => $xml->ProcessoLicitatorio[$i]->PrazoExecucao->__toString(),
                 'ente_id' => $requestData['ente_id'],
                 'tipo_cadastro' => 'Importado',
                 'situacao_cadastro' => 'Não validado',
                 'colaborador_criou_id' => auth()->user()->id,
                 ]
                );

                if(isset($xml->ProcessoLicitatorio[$i]->InstrumentosContratuais))
                {
                    $contratos = [];
                    $contratos_xml = $xml->ProcessoLicitatorio[$i]->InstrumentosContratuais[0];
                    // dd($contratos_xml);
                    // dd($contratos_xml->InstrumentoContratual[0]->NumeroLicitatorio->__toString());
                    for($j = 0; $j<$contratos_xml->count(); $j++){
                        $contratos[$j] = Contrato::create(
                            ['unidade_gestora' => $contratos_xml->InstrumentoContratual[$j]->UnidadeGestora->__toString(),
                             'data_emissao' => $contratos_xml->InstrumentoContratual[$j]->DataEmissao->__toString(),
                             'instrumento_contrato' => $contratos_xml->InstrumentoContratual[$j]->TipoInstrumentoContratual->__toString(),
                             'numero_contrato' => $contratos_xml->InstrumentoContratual[$j]->NumeroInstrumentoContratual->__toString(),
                             'data_expiracao' => $contratos_xml->InstrumentoContratual[$j]->DataExpiracao->__toString(),
                             'tipo' => $contratos_xml->InstrumentoContratual[$j]->TipoContrato->__toString(),
                             'fornecedor' => $contratos_xml->InstrumentoContratual[$j]->NomeFornecedor->__toString(),
                             'cnpj_cpf' => $contratos_xml->InstrumentoContratual[$j]->CNPJFornecedor->__toString(),
                             'teve_aditivo' => $contratos_xml->InstrumentoContratual[$j]->PossuiAditivo->__toString() == 'SIM' ? 1 : 0,
                             'processo' => $contratos_xml->InstrumentoContratual[$j]->NumeroLicitatorio->__toString(),
                             'valor' => $contratos_xml->InstrumentoContratual[$j]->ValorInstrumentoContratual->__toString(),
                             'descricao' => $contratos_xml->InstrumentoContratual[$j]->Objeto->__toString(),
                             'ente_id' => $requestData['ente_id'],
                             'colaborador_criou_id' => auth()->user()->id,
                             'licitacao_id' => $licitacoes[$i]->id,
                             'numero_licitacao' => $contratos_xml->InstrumentoContratual[$j]->NumeroLicitatorio->__toString(),
                             'tipo_cadastro' => 'Importado',
                             ]
                        );
                        if(isset($contratos_xml->InstrumentoContratual[$j]->ItensAdquiridos))

                        {
                            $itens_contrato_xml = $contratos_xml->InstrumentoContratual[$j]->ItensAdquiridos;
                            // dd($itens_contrato_xml);
                            $itens_contrato = [];
                            for($k = 0; $k<$itens_contrato_xml->count(); $k++)
                            {
                                $itens_contrato[$k] = ItemContrato::create(
                                ['item' => $itens_contrato_xml->Item[$k]->NumeroItem->__toString(),
                                 // 'exercicio' => $itens_contrato_xml->Item[$k]->,
                                 'descricao' => $itens_contrato_xml->Item[$k]->Identificacao->__toString(),
                                 'quantidade' => $itens_contrato_xml->Item[$k]->Quantidade->__toString(),
                                 // 'unidade_medida' => $itens_contrato_xml->Item[$k]->,
                                 'valor_unitario' => $itens_contrato_xml->Item[$k]->ValorUnitario->__toString(),
                                 'valor_total' => $itens_contrato_xml->Item[$k]->ValorTotal->__toString(),
                                 'contrato_id' => $contratos[$j]->id,
                                 ]
                                );
                            }
                            $contratos[$j]->itens_contratos_array = $itens_contrato;
                        }

                    }
                    // dd($contratos);
                    $licitacoes[$i]->contratos_array = $contratos;
                }
            //}
                // protected $fillable = ['unidade_gestora', 'data_emissao', 'instrumento_contrato', 'numero_contrato', 'data_expiracao', 'tipo', 'fornecedor', 'cnpj_cpf', 'teve_aditivo', 'processo', 'valor', 'descricao', 'ente_id', 'colaborador_criou_id', 'colaborador_validou_id', 'licitacao_id', 'numero_licitacao'];
            }
            // dd($licitacoes);

            // dd($xml->parse(['processos_licitatorios' => ['uses' => 'ProcessoLicitatorio.UnidadeGestora']]));
            \Session::flash('flash_message',[
            'msg'=>"Arquivo importado com sucesso!",
            'class'=>"alert-success"
            ]);

            return redirect()->back();
        }

    }
}


text:
set -e

# You can run it from any directory.
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# shellcheck disable=SC1090
source "$DIR/prepare_build_dir.sh"

# Put Docker files to root of build dir to use build dir as working dir for Docker.
cp "$BUILD_DIR/ci/docker/Dockerfile" "$BUILD_DIR"
cp "$BUILD_DIR/ci/docker/.dockerignore" "$BUILD_DIR"

pushd "$BUILD_DIR" > /dev/null

echo "Running shellcheck against all .sh files in the project..."

# shellcheck disable=SC2016
docker run \
--interactive \
--tty \
--rm \
--volume "$(pwd)":/project:ro \
--entrypoint sh \
koalaman/shellcheck-alpine:v0.4.7 \
-c 'for file in $(find /project/ -type f -name "*.sh"); do
if ! shellcheck --format=gcc $file; then export FAILED=true; fi; done;
if [ "$FAILED" != "" ]; then exit 1; fi'

echo "Finished shellcheck."

# Override Mainframer version if needed.
"$DIR/mainframer_version.sh"

# Files created in mounted volume by container should have same owner as host machine user to prevent chmod problems.
USER_ID=$(id -u "$USER")

if [ "$USER_ID" == "0" ]; then
    echo "Warning: running as r00t."
fi

docker build -t mainframer:latest .

# Command will run inside a container.
BUILD_COMMAND="set -xe && "

# Setup ssh for tests.
BUILD_COMMAND+="mkdir -p ~/.ssh/ && "
BUILD_COMMAND+="chmod u+rwx,go= ~/.ssh/ && "
BUILD_COMMAND+="ssh-keygen -b 2048 -t rsa -f ~/.ssh/id_rsa -q -N '' && "
BUILD_COMMAND+="cp ~/.ssh/id_rsa.pub ~/.ssh/authorized_keys && "
BUILD_COMMAND+="chmod u+rw,go= ~/.ssh/authorized_keys && "
BUILD_COMMAND+="ssh-keyscan -t rsa localhost > ~/.ssh/known_hosts && "
BUILD_COMMAND+="cat ~/.ssh/known_hosts && "
BUILD_COMMAND+="chmod u+rw,go= ~/.ssh/known_hosts && "

# Configure environment variables in ~/.bashrc for current and ssh sessions.
BUILD_COMMAND+="mv ~/.bashrc ~/.bashrc_original && "
BUILD_COMMAND+="echo -e 'source \"\$HOME/.cargo/env\"\\n' >> ~/.bashrc && "
BUILD_COMMAND+="cat ~/.bashrc_original >> ~/.bashrc && "
BUILD_COMMAND+="rm ~/.bashrc_original && "
BUILD_COMMAND+="source ~/.bashrc && "

# Run unit and integration tests.
BUILD_COMMAND+="/opt/project/test/test.sh &&"

# Build release version and move binary to build/artifacts.
BUILD_COMMAND+="cd /opt/project && cargo build --release && mkdir -p artifacts && mv target/release/mainframer artifacts/mainframer-$TRAVIS_TAG-$(uname -s)"

docker run \
--interactive \
--tty \
--rm \
--volume "$(pwd)":/opt/project \
--env LOCAL_USER_ID="$USER_ID" \
mainframer:latest \
bash -c "$BUILD_COMMAND"

popd > /dev/null

redpajama_set_name: RedPajamaGithub


text:
/**
 * Checks if the NODE_ENV environment variable equals
 * the passed string.
 *
 * @param {string} env
 * @return {boolean}
 */

export function env(env: string): boolean {
    return process.env.NODE_ENV === env;
}


text:
<html>
<body>
<script>
window.open('file_browserElement_OpenNamed2.html', 'OpenNamed');
</script>
</body>
</html>


text:
#include <cstring>
#include <unistd.h>
#include <algorithm>
#include "File.hpp"
#include "TileThreadPool.hpp"
#include "Funcs.hpp"
#include "Version.hpp"
#include "Options.hpp"

namespace tc {

const int Options::MAX_THREADS          = 64;

const bool Options::DEF_SILENT          = false;
const bool Options::DEF_HALT_ON_ERROR   = true;
const bool Options::DEF_MOSC            = false;
const bool Options::DEF_SHOWINFO        = false;
const bool Options::DEF_ASSUMETIS       = false;
const bool Options::DEF_OVERWRITE_PVRZ  = false;
const int Options::DEF_QUALITY_V1       = 4;
const int Options::DEF_QUALITY_V2       = 9;
const int Options::DEF_THREADS          = 0;
const int Options::DEF_MOS_INDEX        = 1000;
const int Options::DEF_TIS_PAGE         = 0;
const int Options::DEF_CONVERSION_TYPE  = 0;

// Supported parameter names
const char Options::ParamNames[] = "esd:o:i:p:f:wzj:q:TIV";

Options::Options() noexcept
: m_isSilent(DEF_SILENT)
, m_haltOnError(DEF_HALT_ON_ERROR)
, m_mosc(DEF_MOSC)
, m_showInfo(DEF_SHOWINFO)
, m_assumeTis(DEF_ASSUMETIS)
, m_overwritePvrz(DEF_OVERWRITE_PVRZ)
, m_qualityV1(DEF_QUALITY_V1)
, m_qualityV2(DEF_QUALITY_V2)
, m_threads(DEF_THREADS)
, m_mosIndex(DEF_MOS_INDEX)
, m_tisPage(DEF_TIS_PAGE)
, m_conversionType(DEF_CONVERSION_TYPE)
, m_inFiles()
, m_searchPaths()
, m_outPath()
, m_outFile()
{
}

Options::~Options() noexcept
{
  m_inFiles.clear();
  m_searchPaths.clear();
}

bool Options::init(int argc, char *argv[]) noexcept
{
  if (argc <= 1) {
    showHelp();
    return false;
  }

  int c = 0;
  opterr = 0;
  while ((c = getopt(argc, argv, ParamNames)) != -1) {
    switch (c) {
      case 'e':
        setHaltOnError(false);
        break;
      case 's':
        setSilent(true);
        break;
      case 'd':
        if (optarg != nullptr) {
          std::string path(optarg);
          if (!addSearchPath(path)) {
            std::printf("Warning: Search path does not exist: %s\n", path.c_str());
          }
        } else {
          std::printf("Missing search path for -d\n");
          showHelp();
          return false;
        }
        break;
      case 'o':
        if (optarg != nullptr) {
          setOutput(std::string(optarg));
        } else {
          std::printf("Missing output file or folder for -o\n");
          showHelp();
          return false;
        }
        break;
      case 'i':
        if (optarg != nullptr) {
          int idx = std::atoi(optarg);
          if (idx < 0 || idx > 99999) {
            std::printf("Start index out of range for -i: %d\n", idx);
            showHelp();
            return false;
          }
          setMosIndex(idx);
        } else {
          std::printf("Missing index value for -i\n");
          showHelp();
          return false;
        }
        break;
      case 'p':
        if (optarg != nullptr) {
          int idx = std::atoi(optarg);
          if (idx < 0 || idx > 99) {
            std::printf("PVRZ page is out of range for -p: %d\n", idx);
            showHelp();
            return false;
          }
          setTisPage(idx);
        } else {
          std::printf("Missing page value for -p\n");
          showHelp();
          return false;
        }
        break;
      case 'f':
        if (optarg != nullptr) {
          int ver = std::atoi(optarg);
          if (ver < 0 || ver > 2) {
            std::printf("Invalid type specified for -f\n");
            showHelp();
            return false;
          }
          setConversionType(ver);
        } else {
          std::printf("Missing type value for -f\n");
          showHelp();
          return false;
        }
      case 'w':
        setOverwritePvrz(true);
        break;
      case 'z':
        setMosc(true);
        break;
      case 'j':
        if (optarg != nullptr) {
          int jobs = std::atoi(optarg);
          if (jobs < 0 || jobs > MAX_THREADS) {
            std::printf("Warning: Number of parallel jobs out of range: %d. Using default value.\n", jobs);
            jobs = 0;
          }
          setThreads(jobs);
        } else {
          showHelp();
          return false;
        }
        break;
      case 'q':
        if (optarg != nullptr) {
          int levelV1 = DEF_QUALITY_V1;
          int levelV2 = DEF_QUALITY_V2;
          if (optarg[0] >= '0' && optarg[0] <= '9') {
            levelV1 = optarg[0] - '0';
          } else if (optarg[0] != '-') {
            std::printf("Error: Unrecognized quality level or placeholder for MOS/TIS V1.\n");
            showHelp();
            return false;
          }
          if (optarg[1] >= '0' && optarg[1] <= '9') {
            levelV2 = optarg[1] - '0';
          } else if (optarg[1] != '-' && optarg[1] != 0) {
            std::printf("Error: Unrecognized quality level or placeholder for MOS/TIS V2.\n");
            showHelp();
            return false;
          }
          setQuality(levelV1, levelV2);
        } else {
          showHelp();
          return false;
        }
        break;
      case 'T':
        setAssumeTis(true);
        break;
      case 'I':
        setShowInfo(true);
        break;
      case 'V':
        if (std::strlen(vers_suffix)) {
          std::printf("%s %d.%d.%d (%s) by %s\n", prog_name, vers_major, vers_minor, vers_patch, vers_suffix, author);
        } else {
          if (vers_patch != 0) {
            std::printf("%s %d.%d.%d by %s\n", prog_name, vers_major, vers_minor, vers_patch, author);
          } else {
            std::printf("%s %d.%d by %s\n", prog_name, vers_major, vers_minor, author);
          }
        }
        return false;
      default:
        std::printf("Unrecognized parameter \"-%c\"\n", optopt);
        showHelp();
        return false;
    }
  }

  // remaining arguments are assumed to be input files
  for (; optind < argc; optind++) {
    if (argv[optind][0] == '-') {
      showHelp();
      return false;
    } else if (!addInput(std::string(argv[optind]))) {
      std::printf("Error opening file: %s\n", argv[optind]);
      return false;
    }
  }

  // checking special conditions
  if (getInputCount() == 0) {
    std::printf("No input filename specified\n");
    showHelp();
    return false;
  } else if (getInputCount() > 1 && isOutFile()) {
    std::printf("You cannot specify output file with multiple input files\n");
    showHelp();
    return false;
  }

  return true;
}

void Options::showHelp() const noexcept
{
  std::printf("\nUsage: %s [options] infile [infile2 [...]]\n", prog_name);
  std::printf("\nOptions:\n");
  std::printf("  -e            Do not halt on errors.\n");
  std::printf("  -s            Be silent.\n");
  std::printf("  -d searchdir  Look for referenced PVRZ files in this directory.\n");
  std::printf("                You can specify this option multiple times to add more\n");
  std::printf("                search directories. (Default: Same directory as input file)\n");
  std::printf("  -o output     Select output file or folder.\n");
  std::printf("                (Note: Output file works only with single input file!)\n");
  std::printf("  -i index      (MOS only) Start index for PVRZ files. (Default: 1000)\n");
  std::printf("                (Note: Existing PVRZ files will be detected and skipped\n");
  std::printf("                       unless option -w has been specified.)\n");
  std::printf("  -p page       (TIS only) Starting page number for PVRZ files. (Default: 0)\n");
  std::printf("                (Caution: Total range of this value is limited to 0..99!)\n");
  std::printf("  -f type       Force type of file conversion. Skips files that are already\n");
  std::printf("                in the desired target format.\n");
  std::printf("                Supported values:\n");
  std::printf("                    0: Don't force conversion (default)\n");
  std::printf("                    1: Convert to palette-based MOS/TIS only\n");
  std::printf("                    2: Convert to pvrz-based MOS/TIS only\n");
  std::printf("  -w            (MOS only) Force overwriting of existing PVRZ files.\n");
  std::printf("  -z            (MOS only) Create compressed MOS V1 files (MOSC).\n");
  std::printf("  -j num        Number of parallel threads to speed up the conversion process.\n");
  std::printf("                Valid numbers: 0 (autodetect), 1..256 (Default: 0)\n");
  std::printf("  -q V1[V2]     Set quality levels for encoding V1 and, optionally, V2 files.\n");
  std::printf("                Use '-' as placeholder for default levels.\n");
  std::printf("                Example 1: -q 27 (level 2 for V1 and level 7 for V2)\n");
  std::printf("                Example 2: -q -7 (default level for V1 and level 7 for V2)\n");
  std::printf("                Example 3: -q 2  (level 2 for V1 and default level for V2)\n");
  std::printf("                When creating palette-based MOS/TIS V1 files (Default: 4):\n");
  std::printf("                    Dithering:               levels 5 to 9\n");
  std::printf("                    Posterization:           levels 0 to 2\n");
  std::printf("                    Additional techniques:   levels 4 to 9\n");
  std::printf("                When creating PVRZ-based MOS/TIS V2 files (Default: 9):\n");
  std::printf("                    Iterative cluster fit:   levels 7 to 9\n");
  std::printf("                    Single cluster fit:      levels 3 to 6\n");
  std::printf("                    Range fit:               levels 0 to 2\n");
  std::printf("                    Weight color by alpha:   levels 5 to 9\n");
  std::printf("  -T            (TIS only) Treat unrecognized input files as headerless TIS.\n");
  std::printf("  -I            Show file information and exit.\n");
  std::printf("  -V            Print version number and exit.\n");
  std::printf("\n");
  std::printf("Supported input file types: MOS V1, MOS V2, TIS V1, TIS V2.\n");
  std::printf("Note: You can mix and match input files of each supported type.\n");
}

bool Options::addInput(const std::string &inFile) noexcept
{
  if (!inFile.empty()) {
    m_inFiles.emplace_back(std::string(inFile));
    return true;
  }
  return false;
}

void Options::removeInput(int idx) noexcept
{
  if (idx >= 0 && (size_t)idx < m_inFiles.size()) {
    m_inFiles.erase(m_inFiles.begin() + idx);
  }
}

const std::string& Options::getInput(int idx) const noexcept
{
  static const std::string defString;   // empty default string

  if (idx >= 0 && (size_t)idx < m_inFiles.size()) {
    return *(m_inFiles.begin() + idx);
  }
  return defString;
}

bool Options::addSearchPath(const std::string &path) noexcept
{
  std::string search;

  if (!path.empty()) {
    search.assign(path);

    // removing trailing path separators
    while (!search.empty() && (File::IsPathSeparator(search.at(search.length() - 1)))) {
      search.erase(search.end() - 1);
    }

    if (File::IsDirectory(search.c_str())) {
      for (auto iter = m_searchPaths.cbegin(); iter != m_searchPaths.cend(); ++iter) {
        if (search.compare(*iter) == 0) {
          return true;
        }
      }
      m_searchPaths.push_back(search);
      return true;
    }
  }
  return false;
}

void Options::removeSearchPath(int idx) noexcept
{
  if (idx >= 0 && (size_t)idx < m_searchPaths.size()) {
    m_searchPaths.erase(m_searchPaths.begin() + idx);
  }
}

std::string Options::getSearchPath(int idx) const noexcept
{
  static const std::string defString;   // empty default string

  if (idx >= 0 && (size_t)idx < m_searchPaths.size()) {
    return *(m_searchPaths.begin() + idx);
  }
  return defString;
}

std::string Options::searchFile(const std::string &fileName) const noexcept
{
  return searchFile(fileName, std::string());
}

std::string Options::searchFile(const std::string &fileName, const std:: string &path) const noexcept
{
  if (!fileName.empty()) {
    std::string file = File::ExtractFileName(fileName);
    if (!file.empty()) {
      // use search paths first
      for (int i = 0; i < getSearchPathCount(); i++) {
        std::string tmpFile = File::CreateFileName(getSearchPath(i), file);
        if (File::Exists(tmpFile.c_str()) && !File::IsDirectory(tmpFile.c_str())) {
          return tmpFile;
        }
      }

      // search in input file path last
      std::string tmpFile = File::CreateFileName(path, file);
      if (File::Exists(tmpFile.c_str()) && !File::IsDirectory(tmpFile.c_str())) {
        return tmpFile;
      }
    }
  }
  return std::string();
}

void Options::setMosIndex(int index) noexcept
{
  if (index >= 0 && index <= 99999) {
    m_mosIndex = index;
  }
}

void Options::setTisPage(int page) noexcept
{
  if (page >= 0 && page <= 99) {
    m_tisPage = page;
  }
}

void Options::setConversionType(int type) noexcept
{
  if (type < 0) type = 0;
  if (type > 2) type = 2;
  m_conversionType = type;
}

bool Options::setOutput(const std::string &outFile) noexcept
{
  if (!outFile.empty()) {
    if (File::IsDirectory(outFile.c_str())) {
      m_outPath.assign(outFile);
      m_outFile.clear();
    } else {
      m_outPath.assign(File::ExtractFilePath(outFile));
      m_outFile.assign(File::ExtractFileName(outFile));
    }
    return true;
  }
  return false;
}

void Options::setQuality(int v1, int v2) noexcept
{
  setQualityV1(v1);
  setQualityV2(v2);
}

void Options::setQualityV1(int v) noexcept
{
  m_qualityV1 = std::max(0, std::min(9, v));
}

void Options::setQualityV2(int v) noexcept
{
  m_qualityV2 = std::max(0, std::min(9, v));
}

void Options::setThreads(int v) noexcept
{
  // limiting threads to a sane number
  m_threads = std::max(0, std::min((int)TileThreadPool::MAX_THREADS, v));
}

int Options::getThreads() const noexcept
{
  return getThreads(true);
}

int Options::getThreads(bool evaluateAuto) const noexcept
{
  if (evaluateAuto) {
    return m_threads ? m_threads : getThreadPoolAutoThreads();
  } else {
    return m_threads;
  }
}

std::string Options::getOptionsSummary(bool complete) const noexcept
{
  std::string sum;

  if (complete || isHaltOnError() != DEF_HALT_ON_ERROR) {
    if (!sum.empty()) sum += ", ";
    sum += "halt on errors = ";
    sum += isHaltOnError() ? "enabled" : "disabled";
  }

  if (getConversionType() != DEF_CONVERSION_TYPE) {
    std::string msg;
    switch (getConversionType()) {
      case 1: msg = "convert to V1 only"; break;
      case 2: msg = "convert to V2 only"; break;
    }
    if (!msg.empty()) {
      if (!sum.empty()) sum += ", ";
      sum += msg;
    }
  }

  if (complete || getQualityV1() != DEF_QUALITY_V1) {
    if (!sum.empty()) sum += ", ";
    sum += "TIS/MOS V1 quality = " + std::to_string(getQualityV1());
  }

  if (complete || getQualityV2() != DEF_QUALITY_V2) {
    if (!sum.empty()) sum += ", ";
    sum += "TIS/MOS V2 quality = " + std::to_string(getQualityV2());
  }

  if (complete || isMosc() != DEF_MOSC) {
    if (!sum.empty()) sum += ", ";
    if (isMosc()) sum += "generate MOSC";
    else sum += "generate MOS";
  }

  if (complete || assumeTis() != DEF_ASSUMETIS) {
    if (!sum.empty()) sum += ", ";
    if (assumeTis()) sum += "headerless TIS allowed";
    else sum += "headerless TIS not allowed";
  }

  if (complete || getMosIndex() != DEF_MOS_INDEX) {
    if (!sum.empty()) sum += ", ";
    sum += "PVRZ start index = " + std::to_string(getMosIndex());
  }

  if (complete || getThreads(false) != DEF_THREADS) {
    if (!sum.empty()) sum += ", ";
    sum += "threads = ";
    if (getThreads(false) == 0) {
      sum += "autodetected (" + std::to_string(getThreadPoolAutoThreads()) + ")";
    } else {
      sum += std::to_string(getThreads());
    }
  }

  return sum;
}

// ----------------------- STATIC METHODS -----------------------

FileType Options::GetFileType(const std::string &fileName, bool assumeTis) noexcept
{
  if (!fileName.empty()) {
    File f(fileName.c_str(), "rb");
    if (f.error()) {
      return FileType::UNKNOWN;
    }

    char sig[4];
    if (f.read(sig, 1, 4) != 4) {
      return FileType::UNKNOWN;
    }

    FileType retVal = FileType::UNKNOWN;
    if (std::strncmp(sig, "TIS ", 4) == 0) {
      char ver[4];
      if (f.read(ver, 1, 4) != 4) {
        return FileType::UNKNOWN;
      }
      uint32_t size;
      if (!f.seek(12L, SEEK_SET) || f.read(&size, 1, 4) != 4) {
        return FileType::UNKNOWN;
      }
      size = get32u_le(&size);
      if (size == 0x1400) {
        retVal = FileType::TISV1;
      } else if (size == 12) {
        retVal = FileType::TISV2;
      }
    } else if (std::strncmp(sig, "MOS ", 4) == 0) {
      char ver[4];
      if (f.read(ver, 1, 4) != 4) {
        return FileType::UNKNOWN;
      }
      if (std::strncmp(ver, "V1  ", 4) == 0) {
        retVal = FileType::MOSV1;
      } else if (std::strncmp(ver, "V2  ", 4) == 0) {
        retVal = FileType::MOSV2;
      }
    } else if (std::strncmp(sig, "MOSC", 4) == 0) {
      retVal = FileType::MOSV1;
    } else {
      if (assumeTis) {
        long size = f.getsize();
        if ((size % 0x1400) == 0) {
          retVal = FileType::TISV1;
        } else if ((size % 0x000c) == 0) {
          retVal = FileType::TISV2;
        }
      }
    }

    return retVal;
  }
  return FileType::UNKNOWN;
}

std::string Options::GetOutputFileName(const std::string &path, const std::string inputFile,
                                       FileType type, bool overwrite) noexcept
{
  static const std::string defString;   // empty default string

  if (!inputFile.empty() && type != FileType::UNKNOWN) {
    std::string outFileBase, outFileExt, outPath;

    // getting path
    if (path.empty()) {
      // using input file and path
      outPath = File::ExtractFilePath(inputFile);
    } else {
      // using separate path with input file
      outPath = path;
    }

    // getting filename
    outFileBase = File::ExtractFileBase(inputFile);
    outFileExt = File::ExtractFileExt(inputFile);

    // making output file unique if necessary
    return File::CreateFileName(outPath, outFileBase + outFileExt);
  }
  return defString;
}

std::string Options::GenerateTisPvrzName(const std::string &tisName, int index) noexcept
{
  std::string retVal;
  if (!tisName.empty() && index >= 0 && index < 100) {
    std::string path = File::ExtractFilePath(tisName);
    std::string fileBase = File::ExtractFileBase(tisName);
    if (!fileBase.empty()) {
      retVal = fileBase.at(0);
      if (fileBase.length() > 2) {
        retVal += fileBase.substr(2);
      }
      if (index < 10) {
        retVal += "0";
      }
      retVal = File::CreateFileName(path, retVal + std::to_string(index) + ".pvrz");
    }
  }
  return retVal;
}

std::string Options::GenerateMosPvrzName(const std::string &mosName, int index) noexcept
{
  std::string retVal;
  if (!mosName.empty() && index >= 0 && index <= 99999) {
    std::string path = File::ExtractFilePath(mosName);
    std::string fileBase = "mos";
    if (index < 10) {
      fileBase += "000";
    } else if (index < 100) {
      fileBase += "00";
    } else if (index < 1000) {
      fileBase += "0";
    }
    fileBase += std::to_string(index);
    retVal = File::CreateFileName(path, retVal + fileBase + ".pvrz");
  }
  return retVal;
}

}   // namespace tc


text:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html>

      <title>NHS England Reference Data - Commissioning Reference Mapping</title>
      <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
      <link href="../../Template/css/bootstrap/bootstrap.min.css" rel="stylesheet"
            media="screen"/>
      <link href="../../Template/css/base.css" rel="stylesheet" media="screen"/>
      <link href="../../Template/css/google-code-prettify/prettify.css" rel="stylesheet"
            media="screen"/>

NHS England Reference Data

                     <button type="button" class="btn btn-navbar" data-toggle="collapse"
                             data-target=".nav-collapse">

                     </button>

                           Version: 0.1; Status: Draft

                              Overview

                                    About

                                    Change History

                                    Glossary

                              Reference Data

                              Mappings

Commissioning Reference Mapping

                           Vocabulary Name
                           Version
                           Member Count
                           HTML
                           XML

                           First Attendance
                           1.0
                           6

                              HTML

                              XML

                     Contact Us

                     Release Date: 14-July-2016


text:
package com.cilogi.shiro.guice;

import com.cilogi.shiro.web.FreemarkerServlet;
import com.cilogi.shiro.web.MailQueueServlet;
import com.cilogi.shiro.web.MailReceiveServlet;
import com.cilogi.shiro.web.WakeServlet;
import com.cilogi.shiro.web.oauth.GoogleLoginServlet;
import com.cilogi.shiro.web.oauth.OAuthLoginServlet;
import com.cilogi.shiro.web.user.*;
import com.cilogi.shiro.web.user.dev.AddUsersServlet;
import com.google.appengine.tools.appstats.AppstatsFilter;
import com.google.appengine.tools.appstats.AppstatsServlet;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.google.inject.servlet.ServletModule;
import com.googlecode.objectify.cache.AsyncCacheFilter;
import org.apache.shiro.web.servlet.ShiroFilter;

import java.util.Map;
import java.util.logging.Logger;

public class ServeModule extends ServletModule {
    static final Logger LOG = Logger.getLogger(ServeModule.class.getName());

    private final String userBaseUrl;

    public ServeModule(String userBaseUrl) {
        Preconditions.checkArgument(userBaseUrl != null && !userBaseUrl.endsWith("/"));
        this.userBaseUrl = userBaseUrl;
    }

    @Override
    protected void configureServlets() {
        filter("/*").through(ShiroFilter.class);
        filter("/*").through(AsyncCacheFilter.class);
        filter("/*").through(AppstatsFilter.class, map("calculateRpcCosts", "true"));

        serve("*.ftl").with(FreemarkerServlet.class);

        serve(userBaseUrl + "/ajaxLogin").with(LoginServlet.class);
        serve(userBaseUrl + "/socialLogin").with(OAuthLoginServlet.class);
        serve(userBaseUrl + "/googleLogin").with(GoogleLoginServlet.class);
        serve(userBaseUrl + "/register").with(RegisterServlet.class);
        serve(userBaseUrl + "/registermail").with(MailQueueServlet.class);
        serve(userBaseUrl + "/confirm").with(ConfirmServlet.class);
        serve(userBaseUrl + "/status").with(StatusServlet.class);
        serve(userBaseUrl + "/list").with(UserListServlet.class);
        serve(userBaseUrl + "/suspend").with(UserSuspendServlet.class);
        serve(userBaseUrl + "/delete").with(UserDeleteServlet.class);
        serve(userBaseUrl + "/settings").with(SettingsServlet.class);
            // this one is here so that the default login filter works
        serve("/login").with(LoginServlet.class);
            // Lets check mail to see when stuff bounces
        serve("/_ah/mail/*").with(MailReceiveServlet.class);
        serve("/appstats/*").with(AppstatsServlet.class);
        serve("/cron/wake").with(WakeServlet.class);

        if (ServeLogic.isDevelopmentServer()) {
            serve("/testAdd").with(AddUsersServlet.class);
        }
    }

    private static Map<String,String> map(String... params) {
        Preconditions.checkArgument(params.length % 2 == 0, "You have to have a n even number of map params");
        Map<String,String> map = Maps.newHashMap();
        for (int i = 0; i < params.length; i+=2) {
            map.put(params[i], params[i+1]);
        }
        return map;
    }
}


text:
package com.algorithm.distance;

import static org.junit.Assert.*;

import org.junit.Test;

public class FareCalculatorTest {

    /* ********************************************************************************************
     * TRIP COST TESTS
     *********************************************************************************************/

    @Test
    public void testCalculateTaxiFareCost() {

        assertEquals("A fare below 155 meters should cost $4.00", 400, FareCalculator.calculateTaxiFareCost(150));
        assertEquals("A 305 meter fare should cost $4.25", 425, FareCalculator.calculateTaxiFareCost(305));
        assertEquals("A 310 meter fare should cost $4.50", 450, FareCalculator.calculateTaxiFareCost(310));
        assertEquals("A 315 meter fare should cost $4.50", 450, FareCalculator.calculateTaxiFareCost(315));
    }
}


text:
namespace metaforce {

class CLineRenderer {
public:
  enum class EPrimitiveMode { Lines, LineStrip, LineLoop };

  struct SDrawVertTex {
    zeus::CVector4f pos;
    zeus::CColor color;
    zeus::CVector2f uv;
  };

  struct SDrawVertNoTex {
    zeus::CVector4f pos;
    zeus::CColor color;
  };

  struct SDrawUniform {
    zeus::CColor moduColor;
    CGraphics::CFogState fog;
  };

private:
  EPrimitiveMode m_mode;
  u32 m_maxVerts;
  u32 m_nextVert = 0;
  bool m_final = false;
  bool m_textured;

  zeus::CVector3f m_firstPos;
  zeus::CVector3f m_secondPos;
  zeus::CVector2f m_firstUV;
  zeus::CColor m_firstColor;
  float m_firstWidth;
  float m_firstW;

  zeus::CVector3f m_lastPos;
  zeus::CVector3f m_lastPos2;
  zeus::CVector2f m_lastUV;
  zeus::CColor m_lastColor;
  float m_lastWidth;
  float m_lastW;

  static rstl::reserved_vector<SDrawVertTex, 1024> g_StaticLineVertsTex;
  static rstl::reserved_vector<SDrawVertNoTex, 1024> g_StaticLineVertsNoTex;

  static hecl::VertexBufferPool<SDrawVertTex> s_vertPoolTex;
  static hecl::VertexBufferPool<SDrawVertNoTex> s_vertPoolNoTex;
  static hecl::UniformBufferPool<SDrawUniform> s_uniformPool;

public:
  hecl::VertexBufferPool<SDrawVertTex>::Token m_vertBufTex;
  hecl::VertexBufferPool<SDrawVertNoTex>::Token m_vertBufNoTex;
  hecl::UniformBufferPool<SDrawUniform>::Token m_uniformBuf;
  std::array<boo::ObjToken<boo::IShaderDataBinding>, 2> m_shaderBind;

  CLineRenderer(boo::IGraphicsDataFactory::Context& ctx, EPrimitiveMode mode, u32 maxVerts,
                const boo::ObjToken<boo::ITexture>& texture, bool additive, bool zTest = false, bool zGEqual = false);
  CLineRenderer(EPrimitiveMode mode, u32 maxVerts, const boo::ObjToken<boo::ITexture>& texture, bool additive,
                bool zTest = false, bool zGEqual = false);
  CLineRenderer(CLineRenderer&&) = default;

  void Reset();
  void AddVertex(const zeus::CVector3f& position, const zeus::CColor& color, float width,
                 const zeus::CVector2f& uv = zeus::skZero2f);
  void Render(bool alphaWrite = false, const zeus::CColor& moduColor = zeus::skWhite);

  static void UpdateBuffers() {
    s_vertPoolTex.updateBuffers();
    s_vertPoolNoTex.updateBuffers();
    s_uniformPool.updateBuffers();
  }

  static void Initialize();
  static void Shutdown();
};

} // namespace metaforce


text:
package org.embulk.filter.concat;

public class TestConcatFilterPlugin
{
}


text:
var express = require('express');
var configurations = module.exports;
var app = express();
var server = require('http').createServer(app);
var nconf = require('nconf');
var Meatspace = require('meatspace');
var settings = require('./settings')(app, configurations, express);
var whitelist = require('./whitelist');

nconf.argv().env().file({ file: 'local.json' });

/* Filters for routes */

var isAdmin = function (req, res, next) {
  if (req.session.email && whitelist.indexOf(req.session.email) > -1) {
    next();
  } else {
    res.redirect('/logout');
  }
};

/* Initialize meat */

var meat = new Meatspace({
  fullName: nconf.get('full_name'),
  username: nconf.get('username'),
  postUrl: nconf.get('url'),
  db: nconf.get('db'),
  limit: 12
});

require('express-persona')(app, {
  audience: nconf.get('domain') + ':' + nconf.get('authPort')
});

// routes
require('./routes')(app, meat, nconf, isAdmin);
require('./routes/posts')(app, meat, nconf, isAdmin);
require('./routes/subscriptions')(app, meat, nconf, isAdmin);

app.listen(process.env.PORT || nconf.get('port'));


text:
*
Plus One

 *
Problem from LeetCode.

Description

Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

You may assume the integer do not contain any leading zero, except the number 0 itself.

The digits are stored such that the most significant digit is at the head of the list.

TLDR

You've got an integer split into an int array.

Increment the int array and output to console

@since 06-08-2017

@version 1.0

@author RMatos

@see Problem Description


text:
<!DOCTYPE html>

  <meta charset='utf-8'>
  <meta http-equiv="X-UA-Compatible" content="chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <link href='https://fonts.googleapis.com/css?family=Architects+Daughter' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" type="text/css" href="stylesheets/stylesheet.css" media="screen">
  <link rel="stylesheet" type="text/css" href="stylesheets/github-light.css" media="screen">
  <link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print">

  <title>React native Style key list</title>

Hasan Setiawan

Write, write, write give your wings on code!

      Follow me on GitHub

React native Style key list

Valid keys: [
  "display",
  "width",
  "height",
  "top",
  "left",
  "right",
  "bottom",
  "minWidth",
  "maxWidth",
  "minHeight",
  "maxHeight",
  "margin",
  "marginVertical",
  "marginHorizontal",
  "marginTop",
  "marginBottom",
  "marginLeft",
  "marginRight",
  "padding",
  "paddingVertical",
  "paddingHorizontal",
  "paddingTop",
  "paddingBottom",
  "paddingLeft",
  "paddingRight",
  "borderWidth",
  "borderTopWidth",
  "borderRightWidth",
  "borderBottomWidth",
  "borderLeftWidth",
  "position",
  "flexDirection",
  "flexWrap",
  "justifyContent",
  "alignItems",
  "alignSelf",
  "alignContent",
  "overflow",
  "flex",
  "flexGrow",
  "flexShrink",
  "flexBasis",
  "aspectRatio",
  "zIndex",
  "direction",
  "shadowColor",
  "shadowOffset",
  "shadowOpacity",
  "shadowRadius",
  "transform",
  "transformMatrix",
  "decomposedMatrix",
  "scaleX",
  "scaleY",
  "rotation",
  "translateX",
  "translateY",
  "backfaceVisibility",
  "backgroundColor",
  "borderColor",
  "borderTopColor",
  "borderRightColor",
  "borderBottomColor",
  "borderLeftColor",
  "borderRadius",
  "borderTopLeftRadius",
  "borderTopRightRadius",
  "borderBottomLeftRadius",
  "borderBottomRightRadius",
  "borderStyle",
  "opacity",
  "elevation"
]

This page was generated by GitHub Pages using the Architect theme by Jason Long.

Back


text:
/*
 * MinIO Cloud Storage, (C) 2019 MinIO, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package pubsub

import (
	"sync"
)

// Sub - subscriber entity.
type Sub struct {
	ch     chan interface{}
	filter func(entry interface{}) bool
}

// PubSub holds publishers and subscribers
type PubSub struct {
	subs []*Sub
	sync.RWMutex
}

// Publish message to the subscribers.
// Note that publish is always nob-blocking send so that we don't block on slow receivers.
// Hence receivers should use buffered channel so as not to miss the published events.
func (ps *PubSub) Publish(item interface{}) {
	ps.RLock()
	defer ps.RUnlock()

	for _, sub := range ps.subs {
		if sub.filter == nil || sub.filter(item) {
			select {
			case sub.ch <- item:
			default:
			}
		}
	}
}

// Subscribe - Adds a subscriber to pubsub system
func (ps *PubSub) Subscribe(subCh chan interface{}, doneCh <-chan struct{}, filter func(entry interface{}) bool) {
	ps.Lock()
	defer ps.Unlock()

	sub := &Sub{subCh, filter}
	ps.subs = append(ps.subs, sub)

	go func() {
		<-doneCh

		ps.Lock()
		defer ps.Unlock()

		for i, s := range ps.subs {
			if s == sub {
				ps.subs = append(ps.subs[:i], ps.subs[i+1:]...)
			}
		}
	}()
}

// HasSubscribers returns true if pubsub system has subscribers
func (ps *PubSub) HasSubscribers() bool {
	ps.RLock()
	defer ps.RUnlock()
	return len(ps.subs) > 0
}

// New inits a PubSub system
func New() *PubSub {
	return &PubSub{}
}


text:
<?php

namespace phpbb\db\migration\data\v31x;

class v311 extends \phpbb\db\migration\migration
{
	static public function depends_on()
	{
		return array(
			'\phpbb\db\migration\data\v310\gold',
			'\phpbb\db\migration\data\v31x\style_update',
		);
	}

	public function update_data()
	{
		return array(
			array('config.update', array('version', '3.1.1')),
		);
	}
}


text: Click me to animate


text:
import template from './drsInputPlayer.template.html';

function InputPlayerCtrl($rootScope, Constants, InputPlayerService, SettingsService) {
  'ngInject';

  const vm = this;

  vm.keyup = keyup;
  vm.platform = getPlatformFromSettings();
  vm.player = "";
  vm.run = run;
  vm.toggle = toggle;

  function getPlatformFromSettings() {
    // map XBox/PlayStation to true/false. Defaults to PlayStation.
    return SettingsService.platform === Constants.platforms[1];
  }

  function keyup(event) {
    if (event.keyCode === 13) {
      vm.run();
    }
  }

  function run() {
    const player = vm.player;
    const platform = vm.platform ? Constants.platforms[1] : Constants.platforms[0];

    InputPlayerService.add(player, platform);
    vm.player = "";
  }

  function toggle(platform) {
    // map true/false to XBox/PlayStation.
    const active = platform ? Constants.platforms[1] : Constants.platforms[0];
    SettingsService.platform = active;
    SettingsService.save();
  }

  $rootScope.$on("drs-settings-loaded", function() {
    vm.platform = getPlatformFromSettings();
  });
}

export const InputPlayerComponent = {
  controller: InputPlayerCtrl,
  template: template
};


text:
<?php

namespace Omnipay\Adyen\Message;

use Omnipay\Tests\TestCase;
use Omnipay\Adyen\Message\CreditCard;

/**
 * Class PaymentRequestTest
 * @package Omnipay\Adyen\Message
 */
class BaseRequestTest extends TestCase
{
    public function setUp($type = null)
    {
        $this->request = new BaseRequest(
            $this->getHttpClient(),
            $this->getHttpRequest()
        );

        $this->request->initialize([
            'currency' => 'EUR'
        ]);
    }

    public function testGetData()
    {
        $this->assertEquals($this->request->getData(), []);
    }

    public function adapterUnitsDataProvider()
    {
        return [
            [
                '11.11',
                '1111'
            ],
            [
                '1111.11',
                '111111'
            ],
            [
                '100.00',
                '10000'
            ]
        ];
    }

    /**
     * @dataProvider adapterUnitsDataProvider
     */
    public function testFormatCurrency($amount, $expected)
    {
        $this->assertEquals($this->request->formatCurrency($amount), $expected);
    }

    /**
     * @dataProvider adapterUnitsDataProvider
     */
    public function testSetCardCreatesAdyenSpecificCreditCardObject($amount, $expected)
    {
        $this->request->setCard(['shopper_reference' => 'shopper']);

        $this->assertInstanceOf(CreditCard::class, $this->request->getCard());
        $this->assertEquals('shopper', $this->request->getCard()->getShopperReference());
    }
}


text:
{% load gravatar %}

    {{ article }}

        {{ article.date|date:"DATETIME_FORMAT" }}
        by

            {{ article.author.profile }}

    {{ article.render|striptags|truncatewords:60 }}


text:
. ${FLB_RUNTIME_SHELL_PATH}/common.sh

input_generator() {
    result=$(wait_for_fluent_bit ${SIGNAL_FILE_PATH})

    if test "$result" -eq "0"
    then
        echo '<13>Jan  1 00:00:00 testuser:  Hello!' | nc -w 1 -U -u $SOCKET_PATH
    fi
}

test_in_syslog_uds_stream_plaintext_filter_expect() {
    platform=$(uname)

    if test "$platform" != "Darwin"
        then
        export SIGNAL_FILE_PATH="/tmp/fb_signal_$$"
        export SOCKET_PATH=/tmp/fluent_bit_syslog_uds_dgram.sock

        input_generator &

        $FLB_BIN -c $FLB_RUNTIME_SHELL_CONF/in_syslog_uds_dgram_plaintext_expect.conf
    fi
}

# The following command launch the unit test
. $FLB_RUNTIME_SHELL_PATH/runtime_shell.env


text:
App.info({
	name: 'Workout timer',
	description: 'Workout reps and break timer.',
	version: '0.0.1'
});

App.icons({
	'android_ldpi': 'resources/icons/timer.png',
	'android_mdpi': 'resources/icons/timer.png',
	'android_hdpi': 'resources/icons/timer.png',
	'android_xhdpi': 'resources/icons/timer.png'
});


text:
/*
   Veronda & Westmann proposed a function with exponential
  nonlinearity, leaving the exact I3 dependency unspecified.

  This function is based on the paper "An implicit FE method for
  elastic solids in contact by Gentaro Hirota et.al."

  However, it is not consistent with the linear model.

  W(I1,I2, I3) = 0.5 (mu/gamma (exp (gamma(I1 -3)) - 1) - mu/2 (I2 - 3) +
    lambda (I3 - ln (I3)))

  S =  [mu exp(gamma (I1-3)) I - mu/2 (I1 I - C) + lambda [I3 - 1] C^-1]

  force = - F S X^-T

  For the derivative we get

  Dforce = - (DF S  + F DS) X^-T

  where

  DS = mu exp(gamma (I1-3)) gamma tr(DC) Id - mu/2 (tr(DC) Id. - DH)
       + lambda (I3 C^-1 : DC) C^-1 - lambda (I3-1) C^-1 DC C^-1

     = (exp (..) gamma - 1/2) mu tr(DC) Id.+ mu/2 DH
       + lambda ( I3 C^-1 : DC - (I3-1) C^-1 DC) C^-1

 */

#include <math.h>

#include "element-state.hh"
#include "matrix.hh"
#include "mechanics.hh"

#include "vector.hh"

#define ELEMENT_STATE Element_state2
#define elastic_energy veronda_elastic_energy2
#define elastic_force veronda_elastic_force2
#define elastic_force_derivative veronda_elastic_force_derivative2
#define MATRIX Matrix2
#define DIM 2

#include "veronda-material.icc"

#undef ELEMENT_STATE
#undef elastic_force
#undef elastic_force_derivative
#undef elastic_energy
#undef DIM
#undef MATRIX

#define ELEMENT_STATE Element_state3
#define elastic_energy veronda_elastic_energy3
#define elastic_force veronda_elastic_force3
#define elastic_force_derivative veronda_elastic_force_derivative3
#define MATRIX Matrix3
#define DIM 3

#include "veronda-material.icc"

IMPLEMENT_GET_ELASTICITY(veronda);


text:
import re

SPACE_NORMALIZER = re.compile(r"\s+")

def tokenize_line(line):
    line = SPACE_NORMALIZER.sub(" ", line)
    line = line.strip()
    return line.split()


text:
int main(int argc, char **argv) {
  int result;
  NSString *str = [NSString new];
  result = [str length];
  [str release];
  return result;
}


text:
#ifndef KPRMATCHER_h
#define KPRMATCHER_h

#include "damatcher.h"
#include "problem.h"
#include "rcp.h"
#include <deque>
using std::deque;

class KPRmatcher : public DAmatcher {
public:
 KPRmatcher(): maxNapps {0} {}
  virtual ~KPRmatcher() {}

protected:
  bool match_(Problem&);
  void initData(Problem &);
  void processBumped(Rid);
  void matchSingles(bool frmLast);
  void matchCouples(bool frmLast);
  bool chkMatch(Problem &);
  void unmatch(Rid);

  //couples are dealt with indexing the data using the first resident of the couple

  deque<Rid> resProcessQ;
  deque<Rid> cplProcessQ;
  vector<int> resNxtP;         //resident has applied to all programs in their ROL up to but not including resNxtP[r]
  vector<vector<int>> resNApps; //Number of proposals to each program
  int maxNapps;
};

#endif


text:
package com.getperka.flatpack.domain;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import com.getperka.flatpack.PersistenceAware;

public class PersistentEmployee extends Employee implements PersistenceAware {
  private Set<String> dirtyPropertyNames = new HashSet<String>();
  private boolean persistent;
  private String trackedProperty;

  PersistentEmployee() {}

  @Override
  public Set<String> dirtyPropertyNames() {
    return Collections.unmodifiableSet(dirtyPropertyNames);
  }

  public String getTrackedProperty() {
    return trackedProperty;
  }

  @Override
  public void markPersistent() {
    persistent = true;
    dirtyPropertyNames.clear();
  }

  public void setTrackedProperty(String trackedProperty) {
    dirtyPropertyNames.add("trackedProperty");
    this.trackedProperty = trackedProperty;
  }

  @Override
  public boolean wasPersistent() {
    return persistent;
  }

}


text:
BOOST_AUTO_TEST_SUITE(bencode_test)

BOOST_AUTO_TEST_CASE(test_big_number) {
	caney::memory::shared_const_buf source(std::string("i-11498749138591659872394815462934713428e"));
	caney::memory::shared_const_buf buf{source};
	caney::optional<caney::bencode::big_number> i = caney::bencode::parse<caney::bencode::big_number>(buf);
	BOOST_REQUIRE(i);
	BOOST_CHECK(buf.empty());
	BOOST_CHECK_EQUAL(i->raw().data(), source.data() + 1);
	BOOST_CHECK_EQUAL(reinterpret_cast<uintptr_t>(i->raw().data()), reinterpret_cast<uintptr_t>(source.data()) + 1);
	BOOST_CHECK_EQUAL(i->raw().size() + 2, source.size());
}

BOOST_AUTO_TEST_CASE(test_int8_t) {
	caney::memory::shared_const_buf buf(std::string("i-128e"));
	caney::optional<int8_t> i = caney::bencode::parse<int8_t>(buf);
	BOOST_REQUIRE(i);
	BOOST_CHECK(buf.empty());
	BOOST_CHECK_EQUAL(i.value(), -128);
}

BOOST_AUTO_TEST_CASE(test_int_vector) {
	caney::memory::shared_const_buf buf(std::string("li0ei-1ei1ei-128ei127ee"));
	caney::optional<std::vector<int8_t>> l = caney::bencode::parse<std::vector<int8_t>>(buf);
	BOOST_REQUIRE(l);
	BOOST_CHECK(buf.empty());
	BOOST_REQUIRE_EQUAL(l->size(), 5);
	BOOST_CHECK_EQUAL(l->at(0), 0);
	BOOST_CHECK_EQUAL(l->at(1), -1);
	BOOST_CHECK_EQUAL(l->at(2), 1);
	BOOST_CHECK_EQUAL(l->at(3), -128);
	BOOST_CHECK_EQUAL(l->at(4), 127);
}

BOOST_AUTO_TEST_SUITE_END()


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">

  <title>Qt 4.3: Using Drag and Drop with Item Views</title>
  <link rel="prev" href="model-view-convenience.html" />
  <link rel="contents" href="model-view-programming.html" />
  <link rel="next" href="model-view-proxy-models.html" />
  <link href="classic.css" rel="stylesheet" type="text/css" />

  	Home · All Classes · Main Classes · Grouped Classes · Modules · Functions

[Previous: Item View Convenience Classes]
[Contents]
[Next: Proxy Models]

Using Drag and Drop with Item Views

Overview

Using Convenience Views

Using Model/View Classes

Enabling Drag and Drop for Items

Encoding Exported Data

Inserting Dropped Data into a Model

Decoding Imported Data

Overview

Qt's drag and drop infrastructure is fully supported by the model/view framework. Items in lists, tables, and trees can be dragged within the views, and data can be imported and exported as MIME-encoded data.

The standard views automatically support internal drag and drop, where items are moved around to change the order in which they are displayed. By default, drag and drop is not enabled for these views because they are configured for the simplest, most common uses. To allow items to be dragged around, certain properties of the view need to be enabled, and the items themselves must also allow dragging to occur.

The requirements for a model that only allows items to be exported from a view, and which does not allow data to be dropped into it, are fewer than those for a fully-enabled drag and drop model.

See also the Model Subclassing Reference for more information about enabling drag and drop support in new models.

Using Convenience Views

Each of the types of item used with QListWidget, QTableWidget, and QTreeWidget is configured to use a different set of flags by default. For example, each QListWidgetItem or QTreeWidgetItem is initially enabled, checkable, selectable, and can be used as the source of a drag and drop operation; each QTableWidgetItem can also be edited and used as the target of a drag and drop operation.

Although all of the standard items have one or both flags set for drag and drop, you generally need to set various properties in the view itself to take advantage of the built-in support for drag and drop:

To enable item dragging, set the view's dragEnabled property to <tt>true</tt>.

To allow the user to drop either internal or external items within the view, set the view's viewport()'s acceptDrops property to <tt>true</tt>.

To show the user where the item currently being dragged will be placed if dropped, set the view's showDropIndicator property. This provides the user with continuously updating information about item placement within the view.

For example, we can enable drag and drop in a list widget with the following lines of code:

 QListWidget *listWidget = new QListWidget(this);
 listWidget->setSelectionMode(QAbstractItemView::SingleSelection);
 listWidget->setDragEnabled(true);
 listWidget->viewport()->setAcceptDrops(true);
 listWidget->setDropIndicatorShown(true);

The result is a list widget which allows the items to be copied around within the view, and even lets the user drag items between views containing the same type of data. In both situations, the items are copied rather than moved.

To enable the user to move the items around within the view, we must set the list widget's dragDropMode:

 listWidget->setDragDropMode(QAbstractItemView::InternalMove);

Using Model/View Classes

Setting up a view for drag and drop follows the same pattern used with the convenience views. For example, a QListView can be set up in the same way as a QListWidget:

 QListView *listView = new QListView(this);
 listView->setSelectionMode(QAbstractItemView::ExtendedSelection);
 listView->setDragEnabled(true);
 listView->setAcceptDrops(true);
 listView->setDropIndicatorShown(true);

Since access to the data displayed by the view is controlled by a model, the model used also has to provide support for drag and drop operations. The actions supported by a model can be specified by reimplementing the QAbstractItemModel::supportedDropActions() function. For example, copy and move operations are enabled with the following code:

 Qt::DropActions DragDropListModel::supportedDropActions() const
 {
     return Qt::CopyAction | Qt::MoveAction;
 }

Although any combination of values from Qt::DropActions can be given, the model needs to be written to support them. For example, to allow Qt::MoveAction to be used properly with a list model, the model must provide an implementation of QAbstractItemModel::removeRows(), either directly or by inheriting the implementation from its base class.

Enabling Drag and Drop for Items

Models indicate to views which items can be dragged, and which will accept drops, by reimplementing the QAbstractItemModel::flags() function to provide suitable flags.

For example, a model which provides a simple list based on QAbstractListModel can enable drag and drop for each of the items by ensuring that the flags returned contain the Qt::ItemIsDragEnabled and Qt::ItemIsDropEnabled values:

 Qt::ItemFlags DragDropListModel::flags(const QModelIndex &index) const
 {
     Qt::ItemFlags defaultFlags = QStringListModel::flags(index);

     if (index.isValid())
         return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | defaultFlags;
     else
         return Qt::ItemIsDropEnabled | defaultFlags;
 }

Note that items can be dropped into the top level of the model, but dragging is only enabled for valid items.

In the above code, since the model is derived from QStringListModel, we obtain a default set of flags by calling its implementation of the flags() function.

Encoding Exported Data

When items of data are exported from a model in a drag and drop operation, they are encoded into an appropriate format corresponding to one or more MIME types. Models declare the MIME types that they can use to supply items by reimplementing the QAbstractItemModel::mimeTypes() function, returning a list of standard MIME types.

For example, a model that only provides plain text would provide the following implementation:

 QStringList DragDropListModel::mimeTypes() const
 {
     QStringList types;
     types << "application/vnd.text.list";
     return types;
 }

The model must also provide code to encode data in the advertised format. This is achieved by reimplementing the QAbstractItemModel::mimeData() function to provide a QMimeData object, just as in any other drag and drop operation.

The following code shows how each item of data, corresponding to a given list of indexes, is encoded as plain text and stored in a QMimeData object.

 QMimeData *DragDropListModel::mimeData(const QModelIndexList &indexes) const
 {
     QMimeData *mimeData = new QMimeData();
     QByteArray encodedData;

     QDataStream stream(&encodedData, QIODevice::WriteOnly);

     foreach (QModelIndex index, indexes) {
         if (index.isValid()) {
             QString text = data(index, Qt::DisplayRole).toString();
             stream << text;
         }
     }

     mimeData->setData("application/vnd.text.list", encodedData);
     return mimeData;
 }

Since a list of model indexes is supplied to the function, this approach is general enough to be used in both hierarchical and non-heirarchical models.

Inserting Dropped Data into a Model

The way that any given model handles dropped data depends on both its type (list, table, or tree) and the way its contents is likely to be presented to the user. Generally, the approach taken to accommodate dropped data should be the one that most suits the model's underlying data store.

Different types of model tend to handle dropped data in different ways. List and table models only provide a flat structure in which items of data are stored. As a result, they may insert new rows (and columns) when data is dropped on an existing item in a view, or they may overwrite the item's contents in the model using some of the data supplied. Tree models are often able to add child items containing new data to their underlying data stores, and will therefore behave more predictably as far as the user is concerned.

Dropped data is handled by a model's reimplementation of QAbstractItemModel::dropMimeData(). For example, a model that handles a simple list of strings can provide an implementation that handles data dropped onto existing items separately to data dropped into the top level of the model (i.e., onto an invalid item).

The model first has to make sure that the operation should be acted on, the data supplied is in a format that can be used, and that its destination within the model is valid:

 bool DragDropListModel::dropMimeData(const QMimeData *data,
     Qt::DropAction action, int row, int column, const QModelIndex &parent)
 {
     if (action == Qt::IgnoreAction)
         return true;

     if (!data->hasFormat("application/vnd.text.list"))
         return false;

     if (column > 0)
         return false;

A simple one column string list model can indicate failure if the data supplied is not plain text, or if the column number given for the drop is invalid.

The data to be inserted into the model is treated differently depending on whether it is dropped onto an existing item or not. In this simple example, we want to allow drops between existing items, before the first item in the list, and after the last item.

When a drop occurs, the model index corresponding to the parent item will either be valid, indicating that the drop occurred on an item, or it will be invalid, indicating that the drop occurred somewhere in the view that corresponds to top level of the model.

     int beginRow;

     if (row != -1)
         beginRow = row;

We initially examine the row number supplied to see if we can use it to insert items into the model, regardless of whether the parent index is valid or not.

     else if (parent.isValid())
         beginRow = parent.row();

If the parent model index is valid, the drop occurred on an item. In this simple list model, we find out the row number of the item and use that value to insert dropped items into the top level of the model.

     else
         beginRow = rowCount(QModelIndex());

When a drop occurs elsewhere in the view, and the row number is unusable, we append items to the top level of the model.

In hierarchical models, when a drop occurs on an item, it would be better to insert new items into the model as children of that item. In the simple example shown here, the model only has one level, so this approach is not appropriate.

Decoding Imported Data

Each implementation of dropMimeData() must also decode the data and insert it into the model's underlying data structure.

For a simple string list model, the encoded items can be decoded and streamed into a QStringList:

     QByteArray encodedData = data->data("application/vnd.text.list");
     QDataStream stream(&encodedData, QIODevice::ReadOnly);
     QStringList newItems;
     int rows = 0;

     while (!stream.atEnd()) {
         QString text;
         stream >> text;
         newItems << text;
         ++rows;
     }

The strings can then be inserted into the underlying data store. For consistency, this can be done through the model's own interface:

     insertRows(beginRow, rows, QModelIndex());
     foreach (QString text, newItems) {
         QModelIndex idx = index(beginRow, 0, QModelIndex());
         setData(idx, text);
         beginRow++;
     }

     return true;
 }

Note that the model will typically need to provide implementations of the QAbstractItemModel::insertRows() and QAbstractItemModel::setData() functions.

See also Item Views Puzzle Example.

[Previous: Item View Convenience Classes]
[Contents]
[Next: Proxy Models]

<address>

Copyright © 2008 Trolltech
Trademarks

Qt 4.3.5

</address>


text:
smadmin provides a set of easy tools to manage a sourcemod server with.
smadmin connects to your server over either FTP or SSH. It can remotely install plugins, disable them, automatically setup MetaMod:Source and SourceMod on a new server, and more.

smadmin is MIT Licenced. That means, it's free as in freedom, free as in free beer and free as in Dota 2. It also doesn't use a restrictive licence, such as the GPLv3.

## Dependencies
smadmin is written in Python 3, using the libraries BeautifulSoup and requests. For SSH support, Paramiko is also required.

To install these, run:
```pip install BeautifulSoup4 requests paramiko```

Once these are installed, you must edit config.py, adding your server hostname, server user, and (if using) FTP password. SSH passwords are not and will not be supported - learn to use SSH keys.
Valid commands are listed as follows:
```
help: Displays this help message
exit: Exits smadmintool
installt: Installs from the specified threads
installdir: Installs all files from the specified directory.
	This directory must be laid out like an addons/ directory, with a sourcemod directory in it and such.
edit: Edits the specified file.
setup metamod: Downloads and installs Metamod:Source.
setup sourcemod: Downloads and installs SourceMod.
installf: Installs from a file or direct link.
	This command goes in the format: installf file <file_to_install_name> <filetype>
ls: Lists a remote directory.
enable: Enables a plugin.
lsplugine: Lists the enabled plugins.
disable: Disables a plugin.
lsplugind: Lists all the disabled plugins.
```


text:
class AseguraronlineComPipeline(object):
    def process_item(self, item, spider):
        return item


text:
<?php

// MyAppAssociationBundle:Contact:find.html.twig
return array (
);


text:
using Riganti.Utils.Infrastructure.Core;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace DataLayer.Entities
{
    public class UserAlbum : IEntity<int>
    {
        [Key]
        public int Id { get; set; }

        public int AlbumId { get; set; }

        public int UserId { get; set; }

        [ForeignKey(nameof(AlbumId))]
        public virtual Album Album { get; set; }

        [ForeignKey(nameof(UserId))]
        public virtual User User { get; set; }
    }
}


text:
/*
Generate a HTTP Content-Disposition field-value.

'disposition' should be one of "inline" or "attachment".

'filename' should be a unicode string.

'filename_fallback' should be a string containing only ASCII characters that
is semantically equivalent to 'filename'. If the filename is already ASCII,
it can be omitted, or just copied from 'filename'.

Returns a string suitable for use as a Content-Disposition field-value.

Returns null upon an error.
*/

function make_disposition(disposition, filename, filename_fallback) {
  if (! filename_fallback) {
    filename_fallback = filename;
  }

  if (! (/^[\u0020-\u007e]*$/).test(filename_fallback)) {
    return null; // filename_fallback is not ASCII.
  }

  if (/%/.test(filename_fallback)) {
    return null; // percent characters aren't safe in fallback.
  }

  if (! validate_filename(filename) ||
      ! validate_filename(filename_fallback)) {
        return null; // path separators aren't allowed in either.
      }

  var output = disposition +
    '; filename="' +
    escape_filename(filename_fallback) +
    '"';

  if (filename != filename_fallback) {
    output += "; filename*=utf-8''" + encode_filename(filename);
  }
  return output;
}

function validate_filename(filename) {
  return ! (/[\/\\]/.test(filename));
}

function escape_filename(filename) {
  return filename
    .replace(/\\/g, "\\\\")
    .replace(/"/g, '\\"');
}

function encode_filename(filename) {
  return encodeURIComponent(filename)
    .replace(/'/g, '%27')
    .replace(/\(/g, '%28')
    .replace(/\)/g, '%29')
    .replace(/\*/g, '%2A');
}

exports.make_disposition = make_disposition;


text:
/*
 * Author: cfsego
 */

#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>

typedef struct {
    size_t                    limit_rate;
    size_t                    limit_rate_after;
    ngx_uint_t                log_level;
} ngx_http_limit_upload_conf_t;

typedef struct {
    off_t                     received;
    size_t                    limit_rate;
    ngx_http_event_handler_pt read_event_handler;
    ngx_http_event_handler_pt write_event_handler;
} ngx_http_limit_upload_ctx_t;

static ngx_int_t ngx_http_limit_upload_add_variable(ngx_conf_t *cf);
static ngx_int_t ngx_http_limit_upload_init(ngx_conf_t *cf);
static void *ngx_http_limit_upload_create_loc_conf(ngx_conf_t *cf);
static char *ngx_http_limit_upload_merge_loc_conf(ngx_conf_t *cf, void *parent,
    void *child);

static ngx_int_t ngx_http_variable_limit_upload_get_size(ngx_http_request_t *r,
    ngx_http_variable_value_t *v, uintptr_t data);
static void ngx_http_variable_limit_upload_set_size(ngx_http_request_t *r,
    ngx_http_variable_value_t *v, uintptr_t data);

static ngx_int_t ngx_http_limit_upload_handler(ngx_http_request_t *r);
static ngx_int_t ngx_http_limit_upload_input_body_filter(ngx_http_request_t *r,
    ngx_buf_t *buf);

static void ngx_http_limit_upload_delay(ngx_http_request_t *r);

static ngx_conf_enum_t ngx_http_limit_upload_log_levels[] = {
    { ngx_string("info"), NGX_LOG_INFO },
    { ngx_string("notice"), NGX_LOG_NOTICE },
    { ngx_string("warn"), NGX_LOG_WARN },
    { ngx_string("error"), NGX_LOG_ERR },
    { ngx_null_string, 0 }
};

static ngx_command_t ngx_http_limit_upload_commands[] = {

    { ngx_string("limit_upload_rate"),
      NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF
                        |NGX_CONF_TAKE1,
      ngx_conf_set_size_slot,
      NGX_HTTP_LOC_CONF_OFFSET,
      offsetof(ngx_http_limit_upload_conf_t, limit_rate),
      NULL },

    { ngx_string("limit_upload_rate_after"),
      NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF
                        |NGX_CONF_TAKE1,
      ngx_conf_set_size_slot,
      NGX_HTTP_LOC_CONF_OFFSET,
      offsetof(ngx_http_limit_upload_conf_t, limit_rate_after),
      NULL },

    { ngx_string("limit_upload_rate_log_level"),
      NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1,
      ngx_conf_set_enum_slot,
      NGX_HTTP_LOC_CONF_OFFSET,
      offsetof(ngx_http_limit_upload_conf_t, log_level),
      &ngx_http_limit_upload_log_levels },

      ngx_null_command
};

static ngx_http_module_t ngx_http_limit_upload_module_ctx = {
    ngx_http_limit_upload_add_variable,       /* preconfiguration */
    ngx_http_limit_upload_init,               /* postconfiguration */

    NULL,                                     /* create main configuration */
    NULL,                                     /* init main configuration */

    NULL,                                     /* create server configuration */
    NULL,                                     /* merge server configuration */

    ngx_http_limit_upload_create_loc_conf,    /* create location configration */
    ngx_http_limit_upload_merge_loc_conf      /* merge location configration */
};

ngx_module_t ngx_http_limit_upload_module = {
    NGX_MODULE_V1,
    &ngx_http_limit_upload_module_ctx,        /* module context */
    ngx_http_limit_upload_commands,           /* module directives */
    NGX_HTTP_MODULE,                          /* module type */
    NULL,                                     /* init master */
    NULL,                                     /* init module */
    NULL,                                     /* init process */
    NULL,                                     /* init thread */
    NULL,                                     /* exit thread */
    NULL,                                     /* exit process */
    NULL,                                     /* exit master */
    NGX_MODULE_V1_PADDING
};

static ngx_str_t  ngx_http_limit_upload_var_name
                                            = ngx_string("limit_upload_rate");

static ngx_http_input_body_filter_pt  ngx_http_next_input_body_filter;

static ngx_int_t
ngx_http_limit_upload_input_body_filter(ngx_http_request_t *r, ngx_buf_t *buf)
{
    off_t                          excess;
    ngx_int_t                      rc;
    ngx_msec_t                     delay;
    ngx_http_core_loc_conf_t      *clcf;
    ngx_http_limit_upload_ctx_t   *ctx;
    ngx_http_limit_upload_conf_t  *llcf;

    rc = ngx_http_next_input_body_filter(r, buf);
    if (rc != NGX_OK) {
        return rc;
    }

    ctx = ngx_http_get_module_ctx(r, ngx_http_limit_upload_module);

    llcf = ngx_http_get_module_loc_conf(r, ngx_http_limit_upload_module);

    if (ctx->limit_rate == 0) {
        ctx->limit_rate = llcf->limit_rate;
    }

    if (ctx->limit_rate) {
        ctx->received += ngx_buf_size(buf);

        excess = ctx->received - llcf->limit_rate_after
               - ctx->limit_rate * (ngx_time() - r->start_sec + 1);

        ngx_log_debug5(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                       "limit upload: ctx=%p, received=%O, "
                       "excess=%O, limit_rate=%z, period=%M",
                       ctx, ctx->received, excess, ctx->limit_rate,
                       ngx_time() - r->start_sec + 1);

        if (excess > 0) {
            if (ngx_handle_read_event(r->connection->read, 0) != NGX_OK) {
                return NGX_HTTP_INTERNAL_SERVER_ERROR;
            }

            delay = excess * 1000 / ctx->limit_rate;

            ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                           "limit upload: delay=%M", delay);

            ctx->read_event_handler = r->read_event_handler;
            ctx->write_event_handler = r->write_event_handler;
            r->read_event_handler = ngx_http_test_reading;
            r->write_event_handler = ngx_http_limit_upload_delay;
            ngx_add_timer(r->connection->write, delay);

            if (!r->connection->read->ready) {
                clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);
                ngx_add_timer(r->connection->read, clcf->client_body_timeout);

                if (ngx_handle_read_event(r->connection->read, 0) != NGX_OK) {
                    return NGX_HTTP_INTERNAL_SERVER_ERROR;
                }

            } else if (r->connection->read->timer_set) {
                    ngx_del_timer(r->connection->read);
            }

            return NGX_AGAIN;
        }
    }

    return NGX_OK;
}

static void *
ngx_http_limit_upload_create_loc_conf(ngx_conf_t *cf)
{
    ngx_http_limit_upload_conf_t  *conf;

    conf = ngx_palloc(cf->pool, sizeof(ngx_http_limit_upload_conf_t));
    if (conf == NULL) {
        return NULL;
    }

    conf->limit_rate = NGX_CONF_UNSET_SIZE;
    conf->limit_rate_after = NGX_CONF_UNSET_SIZE;
    conf->log_level = NGX_CONF_UNSET_UINT;

    return conf;
}

static char *
ngx_http_limit_upload_merge_loc_conf(ngx_conf_t *cf, void *parent, void *child)
{
    ngx_http_limit_upload_conf_t  *conf = child;
    ngx_http_limit_upload_conf_t  *prev = parent;

    ngx_conf_merge_size_value(conf->limit_rate, prev->limit_rate, 0);
    ngx_conf_merge_size_value(conf->limit_rate_after, prev->limit_rate_after,
                              0);
    ngx_conf_merge_uint_value(conf->log_level,
                              prev->log_level, NGX_LOG_ERR);

    return NGX_CONF_OK;
}

static ngx_int_t
ngx_http_limit_upload_add_variable(ngx_conf_t *cf)
{
    ngx_http_variable_t           *var;

    var = ngx_http_add_variable(cf, &ngx_http_limit_upload_var_name,
                                NGX_HTTP_VAR_CHANGEABLE
                                |NGX_HTTP_VAR_NOCACHEABLE
                                |NGX_HTTP_VAR_INDEXED);
    if (var == NULL) {
        return NGX_ERROR;
    }

    var->set_handler = ngx_http_variable_limit_upload_set_size;
    var->get_handler = ngx_http_variable_limit_upload_get_size;
    var->data = offsetof(ngx_http_limit_upload_ctx_t, limit_rate);

    if (ngx_http_get_variable_index(cf, &ngx_http_limit_upload_var_name)
        == NGX_ERROR)
    {
        return NGX_ERROR;
    }

    return NGX_OK;
}

static ngx_int_t
ngx_http_limit_upload_init(ngx_conf_t *cf)
{
    ngx_http_handler_pt           *h;
    ngx_http_core_main_conf_t     *cmcf;

    cmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module);

    h = ngx_array_push(&cmcf->phases[NGX_HTTP_POST_READ_PHASE].handlers);
    if (h == NULL) {
        return NGX_ERROR;
    }

    *h = ngx_http_limit_upload_handler;

    ngx_http_next_input_body_filter = ngx_http_top_input_body_filter;
    ngx_http_top_input_body_filter = ngx_http_limit_upload_input_body_filter;

    return NGX_OK;
}

static ngx_int_t
ngx_http_limit_upload_handler(ngx_http_request_t *r)
{
    ngx_http_limit_upload_ctx_t   *ctx;

    ctx = ngx_pcalloc(r->pool, sizeof(ngx_http_limit_upload_ctx_t));
    if (ctx == NULL) {
        return NGX_HTTP_INTERNAL_SERVER_ERROR;
    }

    ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                   "limit upload: ctx=%p", ctx);

    ngx_http_set_ctx(r, ctx, ngx_http_limit_upload_module);

    return NGX_OK;
}

static ngx_int_t
ngx_http_variable_limit_upload_get_size(ngx_http_request_t *r,
    ngx_http_variable_value_t *v, uintptr_t data)
{
    size_t                        *sp;
    ngx_http_limit_upload_ctx_t   *ctx;

    ctx = ngx_http_get_module_ctx(r, ngx_http_limit_upload_module);
    sp = (size_t *) ((char *) ctx + data);

    v->data = ngx_pnalloc(r->pool, NGX_SIZE_T_LEN);
    if (v->data == NULL) {
        return NGX_ERROR;
    }

    v->len = ngx_sprintf(v->data, "%uz", *sp) - v->data;
    v->valid = 1;
    v->no_cacheable = 0;
    v->not_found = 0;

    return NGX_OK;
}

static void
ngx_http_variable_limit_upload_set_size(ngx_http_request_t *r,
    ngx_http_variable_value_t *v, uintptr_t data)
{
    ssize_t                        s, *sp;
    ngx_str_t                      val;
    ngx_http_limit_upload_ctx_t   *ctx;

    val.len = v->len;
    val.data = v->data;

    s = ngx_parse_size(&val);

    if (s == NGX_ERROR) {
        ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
                      "invalid size \"%V\"", &val);
        return;
    }

    ctx = ngx_http_get_module_ctx(r, ngx_http_limit_upload_module);
    sp = (ssize_t *) ((char *) ctx + data);

    *sp = s;

    return;
}

static void
ngx_http_limit_upload_delay(ngx_http_request_t *r)
{
    ngx_event_t                   *wev;
    ngx_http_limit_upload_ctx_t   *ctx;

    ctx = ngx_http_get_module_ctx(r, ngx_http_limit_upload_module);

    ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                   "limit upload delay");

    wev = r->connection->write;

    if (!wev->timedout) {

        if (ngx_handle_write_event(wev, 0) != NGX_OK) {
            ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
        }

        return;
    }

    wev->timedout = 0;

    if (ngx_handle_read_event(r->connection->read, 0) != NGX_OK) {
        ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
        return;
    }

    r->read_event_handler = ctx->read_event_handler;
    r->write_event_handler = ctx->write_event_handler;

    r->read_event_handler(r);
}


text:
using namespace eddic;

std::string ast::to_string(const ast::Type& type){
    if(auto* ptr = boost::smart_get<ast::SimpleType>(&type)){
        return ptr->type;
    } else if(auto* ptr = boost::smart_get<ast::ArrayType>(&type)){
        return to_string(ptr->type) + "[]";
    } else if(auto* ptr = boost::smart_get<ast::PointerType>(&type)){
        return to_string(ptr->type) + "*";
    } else if(auto* ptr = boost::smart_get<ast::TemplateType>(&type)){
        std::stringstream printed;

        printed << ptr->type << "<";

        for(auto& tmp_type : ptr->template_types){
            printed << to_string(tmp_type) << ",";
        }

        printed << ">";

        return printed.str();
    } else {
        cpp_unreachable("Unhandled type");
    }
}


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'exacto'

require 'minitest/autorun'