text:
require File.expand_path('../client_application', __FILE__)

module Automatic
  module Models
    class ClientApplications
      include Enumerable

      # Build an instance of the Automatic ClientApplications domain model
      #
      # @param collection [Array]
      #
      # @return [Automatic::Models::ClientApplications]
      def initialize(collection)
        @collection = Array(collection)
      end

      # Implement Enumerable
      def each(&block)
        internal_collection.each(&block)
      end

      private
      def internal_collection
        @collection.map { |record| ClientApplication.new(record) }
      end
    end
  end
end


text:
"""Setup the budget application"""

import logging

from budget.config.environment import load_environment

__all__ = ['setup_app']

log = logging.getLogger(__name__)

from schema import setup_schema
import bootstrap

def setup_app(command, conf, vars):
    """Place any commands to setup budget here"""
    load_environment(conf.global_conf, conf.local_conf)
    setup_schema(command, conf, vars)
    bootstrap.bootstrap(command, conf, vars)

redpajama_set_name: RedPajamaGithub


text:
package de.bund.bva.isyfact.task.autoconfigure;

import de.bund.bva.isyfact.task.TaskScheduler;
import de.bund.bva.isyfact.task.TaskSchedulerStarter;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;

/*Testet, ob der TaskSchedulerStarter autostart=false wirklich nicht erstellt wird */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = IsyTaskAutoConfiguration.class,
    webEnvironment = SpringBootTest.WebEnvironment.NONE,
    properties = { "isy.task.autostart=false" })
public class TaskSchedulerStarterAutoConfigOffTest {

    @Autowired(required = false)
    private TaskSchedulerStarter taskSchedulerStarter;

    @Autowired(required = false)
    private IsyTaskAutoConfiguration isyTaskAutoConfiguration;

    @MockBean
    private TaskScheduler taskScheduler;

    @Test
    public void testTaskSchedulerStarterNichtVorhanden() {
        assertNotNull(isyTaskAutoConfiguration);
        assertNull(taskSchedulerStarter);
        verify(taskScheduler, never()).starteKonfigurierteTasks();
    }

}


text:
bert_decoder_t *decoder;

void test_read()
{
	bert_data_t *data;
	int result;

	if ((result = bert_decoder_pull(decoder,&data)) != 1)
	{
		test_fail(bert_strerror(result));
	}

	if (data->type != bert_data_int)
	{
		test_fail("bert_decoder_next did not decode an int");
	}

	if (data->integer != EXPECTED)
	{
		test_fail("bert_decoder_next decoded %lld, expected %lld",data->integer,EXPECTED);
	}
}

int main()
{
	int fd;

	decoder = bert_decoder_create();
	fd = test_open_file("files/small_bignum.bert");
	bert_decoder_stream(decoder,fd);

	test_read();

	bert_decoder_destroy(decoder);
	close(fd);
	return 0;
}


text:
package jp.ne.sakura.kkkon.test.android.backup;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.UUID;
import jp.ne.sakura.kkkon.test.android.backup.lib.KKBackupHelper;
import jp.ne.sakura.kkkon.test.android.backup.lib.SharedPref;

public class MainActivity extends Activity implements View.OnClickListener
{
    private static final String TAG = "kk-Backup-Apk";

    private LinearLayout        mLayout;

    private TextView            mTextViewUUID;
    private Button              mButtonBackupRequestBackup;
    private Button              mButtonBackupRequestRestore;
    private Button              mButtonCreateSharedPreferences;

    public static final String NAME_SHAREDPREF_PREF = "pref";
    public static final String BACKUP_SHAREDPREF = "backupSharedKeys";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        Log.d( TAG, "MainActivity#onCreate:");
        super.onCreate(savedInstanceState);

        {
            final String prefName = this.getClass().getName();
            final Context contextApp = this.getApplicationContext();
            KKBackupHelper.initialize( contextApp );
        }

        mLayout = new LinearLayout( this );
        mLayout.setOrientation( LinearLayout.VERTICAL );

        {
            mTextViewUUID = new TextView(this);
            mTextViewUUID.setText( "uuid=" );

            final SharedPref pref = KKBackupHelper.getSharedPreferences( NAME_SHAREDPREF_PREF, Activity.MODE_PRIVATE );
            if ( null != pref )
            {
                if ( pref.contains("uuid") )
                {
                    final String uuid = pref.getString( "uuid" );
                    mTextViewUUID.setText( "uuid=" + uuid );
                }
            }

            mLayout.addView( mTextViewUUID );
        }
        mButtonBackupRequestBackup = new Button( this );
        mButtonBackupRequestBackup.setText( "Backup: request backup" );
        mButtonBackupRequestBackup.setOnClickListener( this );
        mLayout.addView( mButtonBackupRequestBackup );

        mButtonBackupRequestRestore  = new Button( this );
        mButtonBackupRequestRestore.setText( "Backup: request restore" );
        mButtonBackupRequestRestore.setOnClickListener( this );
        mLayout.addView( mButtonBackupRequestRestore );

        mButtonCreateSharedPreferences = new Button( this );
        mButtonCreateSharedPreferences.setText( "Create SharedPreferences" );
        mButtonCreateSharedPreferences.setOnClickListener( this );
        mLayout.addView( mButtonCreateSharedPreferences );

        this.setContentView( mLayout );
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private void createSharedPreferences()
    {
        final SharedPref pref = KKBackupHelper.getSharedPreferences( NAME_SHAREDPREF_PREF, Activity.MODE_PRIVATE );
        if ( null != pref )
        {
            if ( pref.contains("uuid") )
            {
            }
            else
            {
                final SharedPreferences.Editor editor = pref.modifyStart();
                final UUID uuid = UUID.randomUUID();
                if ( null != uuid )
                {
                    final String strUUID = uuid.toString();
                    editor.putString( "uuid", strUUID );
                }
                final boolean writeOK = editor.commit(); // syncronous
                if ( false == writeOK )
                {
                    Log.e( TAG, "SharedPreferences.Editor#commit failed!!" );
                }
                pref.modifyFinish();
            }

            {
                final String uuid = pref.getString("uuid");
                mTextViewUUID.setText( "uuid=" + uuid );
            }

        }
    }

    public void onClick(View view)
    {
        if ( this.mButtonCreateSharedPreferences == view )
        {
            this.createSharedPreferences();
        }
        else if ( this.mButtonBackupRequestBackup == view )
        {
            KKBackupHelper.requestBackup();
        }
        else if ( this.mButtonBackupRequestRestore == view )
        {
            KKBackupHelper.requestRestore();
        }
    }

}


text:
(function() {
  'use strict';

  angular
    .module('footballStats')

})();


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

#include "base/basictypes.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/message_loop/message_loop_proxy.h"
#include "base/run_loop.h"
#include "content/public/test/async_file_test_helper.h"
#include "content/public/test/test_file_system_context.h"
#include "content/public/test/test_file_system_options.h"
#include "storage/browser/fileapi/file_system_context.h"
#include "storage/browser/fileapi/isolated_context.h"
#include "storage/browser/fileapi/obfuscated_file_util.h"
#include "storage/browser/fileapi/plugin_private_file_system_backend.h"
#include "storage/common/fileapi/file_system_util.h"
#include "testing/gtest/include/gtest/gtest.h"

using content::AsyncFileTestHelper;
using storage::FileSystemContext;
using storage::FileSystemURL;
using storage::IsolatedContext;

namespace content {

namespace {

const GURL kOrigin1("http://www.example.com");
const GURL kOrigin2("https://www.example.com");
const std::string kPlugin1("plugin1");
const std::string kPlugin2("plugin2");
const storage::FileSystemType kType = storage::kFileSystemTypePluginPrivate;
const std::string kRootName = "pluginprivate";

void DidOpenFileSystem(base::File::Error* error_out,
                       base::File::Error error) {
  *error_out = error;
}

std::string RegisterFileSystem() {
  return IsolatedContext::GetInstance()->RegisterFileSystemForVirtualPath(
      kType, kRootName, base::FilePath());
}

}  // namespace

class PluginPrivateFileSystemBackendTest : public testing::Test {
 protected:
  void SetUp() override {
    ASSERT_TRUE(data_dir_.CreateUniqueTempDir());
    context_ = CreateFileSystemContextForTesting(
        NULL /* quota_manager_proxy */,
        data_dir_.path());
  }

  FileSystemURL CreateURL(const GURL& root_url, const std::string& relative) {
    FileSystemURL root = context_->CrackURL(root_url);
    return context_->CreateCrackedFileSystemURL(
        root.origin(),
        root.mount_type(),
        root.virtual_path().AppendASCII(relative));
  }

  storage::PluginPrivateFileSystemBackend* backend() const {
    return context_->plugin_private_backend();
  }

  const base::FilePath& base_path() const { return backend()->base_path(); }

  base::ScopedTempDir data_dir_;
  base::MessageLoop message_loop_;
  scoped_refptr<FileSystemContext> context_;
};

// TODO(kinuko,nhiroki): There are a lot of duplicate code in these tests. Write
// helper functions to simplify the tests.

TEST_F(PluginPrivateFileSystemBackendTest, OpenFileSystemBasic) {
  const std::string filesystem_id1 = RegisterFileSystem();
  base::File::Error error = base::File::FILE_ERROR_FAILED;
  backend()->OpenPrivateFileSystem(
      kOrigin1,
      kType,
      filesystem_id1,
      kPlugin1,
      storage::OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT,
      base::Bind(&DidOpenFileSystem, &error));
  base::RunLoop().RunUntilIdle();
  ASSERT_EQ(base::File::FILE_OK, error);

  // Run this again with FAIL_IF_NONEXISTENT to see if it succeeds.
  const std::string filesystem_id2 = RegisterFileSystem();
  error = base::File::FILE_ERROR_FAILED;
  backend()->OpenPrivateFileSystem(
      kOrigin1,
      kType,
      filesystem_id2,
      kPlugin1,
      storage::OPEN_FILE_SYSTEM_FAIL_IF_NONEXISTENT,
      base::Bind(&DidOpenFileSystem, &error));
  base::RunLoop().RunUntilIdle();
  ASSERT_EQ(base::File::FILE_OK, error);

  const GURL root_url(storage::GetIsolatedFileSystemRootURIString(
      kOrigin1, filesystem_id1, kRootName));
  FileSystemURL file = CreateURL(root_url, "foo");
  base::FilePath platform_path;
  EXPECT_EQ(base::File::FILE_OK,
            AsyncFileTestHelper::CreateFile(context_.get(), file));
  EXPECT_EQ(base::File::FILE_OK,
            AsyncFileTestHelper::GetPlatformPath(context_.get(), file,
                                                 &platform_path));
  EXPECT_TRUE(base_path().AppendASCII("000").AppendASCII(kPlugin1).IsParent(
      platform_path));
}

TEST_F(PluginPrivateFileSystemBackendTest, PluginIsolation) {
  // Open filesystem for kPlugin1 and kPlugin2.
  const std::string filesystem_id1 = RegisterFileSystem();
  base::File::Error error = base::File::FILE_ERROR_FAILED;
  backend()->OpenPrivateFileSystem(
      kOrigin1,
      kType,
      filesystem_id1,
      kPlugin1,
      storage::OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT,
      base::Bind(&DidOpenFileSystem, &error));
  base::RunLoop().RunUntilIdle();
  ASSERT_EQ(base::File::FILE_OK, error);

  const std::string filesystem_id2 = RegisterFileSystem();
  error = base::File::FILE_ERROR_FAILED;
  backend()->OpenPrivateFileSystem(
      kOrigin1,
      kType,
      filesystem_id2,
      kPlugin2,
      storage::OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT,
      base::Bind(&DidOpenFileSystem, &error));
  base::RunLoop().RunUntilIdle();
  ASSERT_EQ(base::File::FILE_OK, error);

  // Create 'foo' in kPlugin1.
  const GURL root_url1(storage::GetIsolatedFileSystemRootURIString(
      kOrigin1, filesystem_id1, kRootName));
  FileSystemURL file1 = CreateURL(root_url1, "foo");
  EXPECT_EQ(base::File::FILE_OK,
            AsyncFileTestHelper::CreateFile(context_.get(), file1));
  EXPECT_TRUE(AsyncFileTestHelper::FileExists(
      context_.get(), file1, AsyncFileTestHelper::kDontCheckSize));

  // See the same path is not available in kPlugin2.
  const GURL root_url2(storage::GetIsolatedFileSystemRootURIString(
      kOrigin1, filesystem_id2, kRootName));
  FileSystemURL file2 = CreateURL(root_url2, "foo");
  EXPECT_FALSE(AsyncFileTestHelper::FileExists(
      context_.get(), file2, AsyncFileTestHelper::kDontCheckSize));
}

TEST_F(PluginPrivateFileSystemBackendTest, OriginIsolation) {
  // Open filesystem for kOrigin1 and kOrigin2.
  const std::string filesystem_id1 = RegisterFileSystem();
  base::File::Error error = base::File::FILE_ERROR_FAILED;
  backend()->OpenPrivateFileSystem(
      kOrigin1,
      kType,
      filesystem_id1,
      kPlugin1,
      storage::OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT,
      base::Bind(&DidOpenFileSystem, &error));
  base::RunLoop().RunUntilIdle();
  ASSERT_EQ(base::File::FILE_OK, error);

  const std::string filesystem_id2 = RegisterFileSystem();
  error = base::File::FILE_ERROR_FAILED;
  backend()->OpenPrivateFileSystem(
      kOrigin2,
      kType,
      filesystem_id2,
      kPlugin1,
      storage::OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT,
      base::Bind(&DidOpenFileSystem, &error));
  base::RunLoop().RunUntilIdle();
  ASSERT_EQ(base::File::FILE_OK, error);

  // Create 'foo' in kOrigin1.
  const GURL root_url1(storage::GetIsolatedFileSystemRootURIString(
      kOrigin1, filesystem_id1, kRootName));
  FileSystemURL file1 = CreateURL(root_url1, "foo");
  EXPECT_EQ(base::File::FILE_OK,
            AsyncFileTestHelper::CreateFile(context_.get(), file1));
  EXPECT_TRUE(AsyncFileTestHelper::FileExists(
      context_.get(), file1, AsyncFileTestHelper::kDontCheckSize));

  // See the same path is not available in kOrigin2.
  const GURL root_url2(storage::GetIsolatedFileSystemRootURIString(
      kOrigin2, filesystem_id2, kRootName));
  FileSystemURL file2 = CreateURL(root_url2, "foo");
  EXPECT_FALSE(AsyncFileTestHelper::FileExists(
      context_.get(), file2, AsyncFileTestHelper::kDontCheckSize));
}

TEST_F(PluginPrivateFileSystemBackendTest, DeleteOriginDirectory) {
  // Open filesystem for kOrigin1 and kOrigin2.
  const std::string filesystem_id1 = RegisterFileSystem();
  base::File::Error error = base::File::FILE_ERROR_FAILED;
  backend()->OpenPrivateFileSystem(
      kOrigin1,
      kType,
      filesystem_id1,
      kPlugin1,
      storage::OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT,
      base::Bind(&DidOpenFileSystem, &error));
  base::RunLoop().RunUntilIdle();
  ASSERT_EQ(base::File::FILE_OK, error);

  const std::string filesystem_id2 = RegisterFileSystem();
  error = base::File::FILE_ERROR_FAILED;
  backend()->OpenPrivateFileSystem(
      kOrigin2,
      kType,
      filesystem_id2,
      kPlugin1,
      storage::OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT,
      base::Bind(&DidOpenFileSystem, &error));
  base::RunLoop().RunUntilIdle();
  ASSERT_EQ(base::File::FILE_OK, error);

  // Create 'foo' in kOrigin1.
  const GURL root_url1(storage::GetIsolatedFileSystemRootURIString(
      kOrigin1, filesystem_id1, kRootName));
  FileSystemURL file1 = CreateURL(root_url1, "foo");
  EXPECT_EQ(base::File::FILE_OK,
            AsyncFileTestHelper::CreateFile(context_.get(), file1));
  EXPECT_TRUE(AsyncFileTestHelper::FileExists(
      context_.get(), file1, AsyncFileTestHelper::kDontCheckSize));

  // Create 'foo' in kOrigin2.
  const GURL root_url2(storage::GetIsolatedFileSystemRootURIString(
      kOrigin2, filesystem_id2, kRootName));
  FileSystemURL file2 = CreateURL(root_url2, "foo");
  EXPECT_EQ(base::File::FILE_OK,
            AsyncFileTestHelper::CreateFile(context_.get(), file2));
  EXPECT_TRUE(AsyncFileTestHelper::FileExists(
      context_.get(), file2, AsyncFileTestHelper::kDontCheckSize));

  // Delete data for kOrigin1.
  error = backend()->DeleteOriginDataOnFileTaskRunner(
      context_.get(), NULL, kOrigin1, kType);
  EXPECT_EQ(base::File::FILE_OK, error);

  // Confirm 'foo' in kOrigin1 is deleted.
  EXPECT_FALSE(AsyncFileTestHelper::FileExists(
      context_.get(), file1, AsyncFileTestHelper::kDontCheckSize));

  // Confirm 'foo' in kOrigin2 is NOT deleted.
  EXPECT_TRUE(AsyncFileTestHelper::FileExists(
      context_.get(), file2, AsyncFileTestHelper::kDontCheckSize));

  // Re-open filesystem for kOrigin1.
  const std::string filesystem_id3 = RegisterFileSystem();
  error = base::File::FILE_ERROR_FAILED;
  backend()->OpenPrivateFileSystem(
      kOrigin1,
      kType,
      filesystem_id3,
      kPlugin1,
      storage::OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT,
      base::Bind(&DidOpenFileSystem, &error));
  base::RunLoop().RunUntilIdle();
  ASSERT_EQ(base::File::FILE_OK, error);

  // Re-create 'foo' in kOrigin1.
  const GURL root_url3(storage::GetIsolatedFileSystemRootURIString(
      kOrigin1, filesystem_id3, kRootName));
  FileSystemURL file3 = CreateURL(root_url3, "foo");
  EXPECT_EQ(base::File::FILE_OK,
            AsyncFileTestHelper::CreateFile(context_.get(), file3));
  EXPECT_TRUE(AsyncFileTestHelper::FileExists(
      context_.get(), file3, AsyncFileTestHelper::kDontCheckSize));

  // Confirm 'foo' in kOrigin1 is re-created.
  EXPECT_TRUE(AsyncFileTestHelper::FileExists(
      context_.get(), file3, AsyncFileTestHelper::kDontCheckSize));
}

}  // namespace content


text:
//
//  VR-Studies
//  Created by miuccie miurror on 11/04/2016.
//  Copyright 2016 Yumemi.Inc / miuccie miurror
//

using UnityEngine;
using System.Collections;

public class Escarator : MonoBehaviour {

	public Vector3 direction = Vector3.up;
	public float   velocity = 0.002f;
	public float   duration = 2.0f;

	Vector3 startPos = Vector3.zero;

	void Start () {
		startPos = transform.position;
	}

	void Update () {

		// 設定に従って自身を移動する
		transform.position += direction * velocity;

		// 特定距離を移動したら引き返す
		var distance = Vector3.Distance ( startPos, transform.position );
		if( distance >= duration ){
			direction *= -1.0f;
			startPos = transform.position;
		}
	}
}


text:
FROM debian:jessie
MAINTAINER Julien Giovaresco <dev@giovaresco.fr>

RUN apt-get update && DEBIAN_FRONTEND=noninteractive \
	apt-get install -y ruby-full make git g++ --no-install-recommends \
	&& rm -rf /var/lib/apt/lists/*

RUN gem install --no-rdoc --no-ri  -v2.3.8 addressable \
	&& gem install --no-rdoc --no-ri travis

RUN mkdir /project
WORKDIR /project

ENTRYPOINT ["/usr/local/bin/travis"]


text:
                 Editar Cadastro

                <form method="POST" action="<?php echo base_url('cadastro/professor/GravarDadosProfessor'); ?>">

                             E-mail
                            <input class="form-control" type="email" value='<?php echo $Email; ?>' alt="E-mail" placeholder="email@email.com.br" aria-describedby="basic-addon2" disabled="true" />
                            <input type="hidden" id="IdHiddenEmail" value='<?php echo $Email; ?>' />

                             Senha
                            <input class="form-control" type="password" ng-model="cadastro.usuario.senha" alt="Senha" placeholder="******" ng-required="true" />

                             Confirmar senha
                            <input class="form-control" type="password" ng-model="cadastro.conf.confirSenha" alt="Confirmar senha" placeholder="******" ng-required="true" />

                            Título
                            <select class="form-control" ng-model="cadastro.dados.titulo" required="true" ng-options="titulo.IdTitulosProfessor as titulo.Descricao for titulo in Titulos" ng-required="true">
                                <option value="">Selecione o título</option>
                            </select>

                             Nome
                            <input class="form-control" type="text" ng-model="cadastro.dados.nome" alt="insira o nome" placeholder="Insira seu nome" required="true" />

                            Nascimento
                            <input class="form-control" type="text" ng-model="cadastro.data.dtnasc" onchange="VerificaData(this);" alt="Data Nascimento" placeholder="01/01/1990" ng-required="true" maxlength="10" ui-data />

                             Sexo
                            <select class="form-control" ng-model="cadastro.dados.sexo" ng-required="true">
                                <option value="">Selecione o sexo</option>
                                <option value="1">Feminino</option>
                                <option value="2">Masculino</option>
                            </select>

                             Telefone
                            <input class="form-control" type="text" ng-model="cadastro.dados.fone" alt="insira o telefone" placeholder="(00)00000-0000" maxlength="14" ng-required="true" ui-cel />

                            <input type="button" name="btnGravar" value="Gravar" class="btn btn-default" alt="botão de enviar" ng-click="gravar(cadastro)">

                </form>


text:
#include <FishEngine/Mathf.hpp>
#include <FishEngine/Time.hpp>

float FishEngine::Mathf::SmoothDamp(float current, float target, float & /*ref*/ currentVelocity, float smoothTime, float maxSpeed /*= Mathf::Infinity*/)
{
	float deltaTime = Time::deltaTime();
	return Mathf::SmoothDamp(current, target, currentVelocity, smoothTime, maxSpeed, deltaTime);
}

float FishEngine::Mathf::SmoothDampAngle(float current, float target, float& currentVelocity, float smoothTime, float maxSpeed /*= Mathf::Infinity*/)
{
	float deltaTime = Time::deltaTime();
	return Mathf::SmoothDampAngle(current, target, currentVelocity, smoothTime, maxSpeed, deltaTime);
}


text:
//////////////////////////////////////////////////////////////////
// (c) Copyright 2003- by Jeongnim Kim
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//   Jeongnim Kim
//   National Center for Supercomputing Applications &
//   Materials Computation Center
//   University of Illinois, Urbana-Champaign
//   Urbana, IL 61801
//   e-mail: jnkim@ncsa.uiuc.edu
//
// Supported by
//   National Center for Supercomputing Applications, UIUC
//   Materials Computation Center, UIUC
//////////////////////////////////////////////////////////////////
// -*- C++ -*-
#include "QMCDrivers/DMC/RNDMCOMP.h"
#include "QMCDrivers/DMC/DMCUpdatePbyP.h"
#include "QMCDrivers/DMC/DMCUpdateAll.h"
#include "QMCApp/HamiltonianPool.h"
#include "Message/Communicate.h"
#include "Message/OpenMP.h"
#include "Utilities/Timer.h"
#include "OhmmsApp/RandomNumberControl.h"
#include "Utilities/ProgressReportEngine.h"

namespace qmcplusplus
{

/// Constructor.
RNDMCOMP::RNDMCOMP(MCWalkerConfiguration& w, TrialWaveFunction& psi, TrialWaveFunction& guide, QMCHamiltonian& h, HamiltonianPool& hpool,WaveFunctionPool& ppool)
  : QMCDriver(w,psi,h,ppool), CloneManager(hpool), Guide(guide)
  , BranchInterval(-1),mover_MaxAge(-1), myRNWarmupSteps(0)
{
  RootName = "dmc";
  QMCType ="RNDMCOMP";
  QMCDriverMode.set(QMC_UPDATE_MODE,1);
  m_param.add(KillWalker,"killnode","string");
  m_param.add(BranchInterval,"branchInterval","string");
  m_param.add(mover_MaxAge,"MaxAge","double");
  m_param.add(myRNWarmupSteps,"rnwarmupsteps", "int");
}

void RNDMCOMP::resetComponents(xmlNodePtr cur)
{
  bool klw=(KillWalker=="yes");
  m_param.put(cur);
  put(cur);
  branchEngine->setRN(true);
  branchEngine->resetRun(cur);
  Estimators->reset();
  #pragma omp parallel for
  for(int ip=0; ip<NumThreads; ++ip)
  {
    delete Movers[ip];
    delete estimatorClones[ip];
    delete branchClones[ip];
    estimatorClones[ip]= new EstimatorManager(*Estimators);
    estimatorClones[ip]->setCollectionMode(false);
    branchClones[ip] = new BranchEngineType(*branchEngine);
    Movers[ip] = new RNDMCUpdatePbyPFast(*wClones[ip],*wgClones[ip],*psiClones[ip],*guideClones[ip],*hClones[ip],*Rng[ip]);
    Movers[ip]->put(qmcNode);
    Movers[ip]->resetRun(branchClones[ip],estimatorClones[ip]);
  }
}

void RNDMCOMP::resetUpdateEngines()
{
  ReportEngine PRE("RNDMCOMP","resetUpdateEngines");
  Timer init_timer;
  makeClones(W,Psi,H);
  makeClones(W,Guide);
  if(Movers.empty())
  {
    W.loadEnsemble(wClones);
    branchEngine->initWalkerController(W,false,true);
    branchEngine->setRN(true);
    //if(QMCDriverMode[QMC_UPDATE_MODE]) W.clearAuxDataSet();
    Movers.resize(NumThreads,0);
    branchClones.resize(NumThreads,0);
    Rng.resize(NumThreads,0);
    estimatorClones.resize(NumThreads,0);
    FairDivideLow(W.getActiveWalkers(),NumThreads,wPerNode);
    bool klw=(KillWalker=="yes");
    {
      //log file
      ostringstream o;
      o << "  Initial partition of walkers on a node: ";
      std::copy(wPerNode.begin(),wPerNode.end(),ostream_iterator<int>(o," "));
      o << "\n";
      o << "Killing Walkers at nodes " << (useAlternate!="yes") <<endl;
      o << "Running the released node driver."<<endl;
      app_log() << o.str();
    }
    #pragma omp parallel for
    for(int ip=0; ip<NumThreads; ++ip)
    {
      estimatorClones[ip]= new EstimatorManager(*Estimators);
      estimatorClones[ip]->setCollectionMode(false);
      Rng[ip]=new RandomGenerator_t(*RandomNumberControl::Children[ip]);
      hClones[ip]->setRandomGenerator(Rng[ip]);
      branchClones[ip] = new BranchEngineType(*branchEngine);
//         Movers[ip] = new RNDMCUpdatePbyPWithRejectionFast(*wClones[ip],*psiClones[ip],*hClones[ip],*Rng[ip]);
      Movers[ip] = new RNDMCUpdatePbyPFast(*wClones[ip],*wgClones[ip],*psiClones[ip],*guideClones[ip],*hClones[ip],*Rng[ip]);
      Movers[ip]->put(qmcNode);
      Movers[ip]->resetRun(branchClones[ip],estimatorClones[ip]);
      MCWalkerConfiguration::iterator wit(W.begin()+wPerNode[ip]), wit_end(W.begin()+wPerNode[ip+1]);
      Movers[ip]->initWalkersForPbyP(wit, wit_end);
    }
  }
//     branchEngine->checkParameters(W);
  if(BranchInterval<0)
    BranchInterval=1;
  {
    ostringstream o;
//       if (useAlternate=="yes") o << "  Using Alternate Mover"<<endl;
//       else o << "  Using Ceperley Mover"<<endl;
    o << "  BranchInterval = " << BranchInterval << "\n";
    o << "  Steps per block = " << nSteps << "\n";
    o << "  Number of blocks = " << nBlocks << "\n";
    app_log() << endl << o.str() << endl;
  }
//     RealType avg_w(0);
//     RealType n_w(0);
//     RealType logepsilon(0);
// #pragma omp parallel
//       {
//         int ip=omp_get_thread_num();
//
//         for (int step=0; step<nWarmupSteps; ++step)
//         {
//           avg_w=0;
//           n_w=0;
//           for (int prestep=0; prestep<myRNWarmupSteps; ++prestep)
//           {
//             Movers[ip]->advanceWalkers(W.begin()+wPerNode[ip],W.begin()+wPerNode[ip+1],true);
//             #pragma omp single
//             {
//               MCWalkerConfiguration::iterator wit(W.begin()), wit_end(W.end());
//               while (wit!=wit_end)
//               {
//                 avg_w += (*wit)->Weight;
//                 n_w +=1;
//                 wit++;
//               }
//             }
//             #pragma omp barrier
//            }
//            #pragma omp single
//            {
//              avg_w *= 1.0/n_w;
//              RealType w_m = avg_w/(1.0-avg_w);
//              w_m = std::log(0.5+0.5*w_m);
//              if (std::abs(w_m)>0.01)
//                logepsilon += w_m;
//            }
//            #pragma omp barrier
//            Movers[ip]->setLogEpsilon(logepsilon);
//         }
//
//       }
  app_log() << " RNDMC Engine Initialization = " << init_timer.elapsed() << " secs " << endl;
}

bool RNDMCOMP::run()
{
  resetUpdateEngines();
  //estimator does not need to collect data
  Estimators->setCollectionMode(true);
  Estimators->start(nBlocks);
  for(int ip=0; ip<NumThreads; ip++)
    Movers[ip]->startRun(nBlocks,false);
  Timer myclock;
  IndexType block = 0;
  IndexType updatePeriod=(QMCDriverMode[QMC_UPDATE_MODE])?Period4CheckProperties:(nBlocks+1)*nSteps;
  do // block
  {
    Estimators->startBlock(nSteps);
    for(int ip=0; ip<NumThreads; ip++)
      Movers[ip]->startBlock(nSteps);
    IndexType step = 0;
    for(IndexType step=0; step< nSteps; ++step, CurrentStep+=BranchInterval)
    {
      #pragma omp parallel for
      for(int ip=0; ip<NumThreads; ++ip)
      {
        int now=CurrentStep;
        MCWalkerConfiguration::iterator
        wit(W.begin()+wPerNode[ip]), wit_end(W.begin()+wPerNode[ip+1]);
        for(int interval = 0; interval<BranchInterval-1; ++interval,++now)
          Movers[ip]->advanceWalkers(wit,wit_end,false);
        wClones[ip]->resetCollectables();
        Movers[ip]->advanceWalkers(wit,wit_end,false);
        Movers[ip]->setReleasedNodeMultiplicity(wit,wit_end);
        if(QMCDriverMode[QMC_UPDATE_MODE] && now%updatePeriod == 0)
          Movers[ip]->updateWalkers(wit, wit_end);
      }//#pragma omp parallel
      for(int ip=1; ip<NumThreads; ++ip)
      {
        for(int j=0; j<W.Collectables.size(); ++j)
          W.Collectables[j]+=wClones[ip]->Collectables[j];
      }
      branchEngine->branch(CurrentStep,W, branchClones);
      FairDivideLow(W.getActiveWalkers(),NumThreads,wPerNode);
    }
//       #pragma omp parallel for
//       for(int ip=0; ip<NumThreads; ++ip)
//       {
//         MCWalkerConfiguration::iterator wit(W.begin()+wPerNode[ip]), wit_end(W.begin()+wPerNode[ip+1]);
//         Movers[ip]->resetbuffers(wit, wit_end);
//       }
    Estimators->stopBlock(acceptRatio());
    block++;
    recordBlock(block);
  }
  while(block<nBlocks && myclock.elapsed()<MaxCPUSecs);
  //for(int ip=0; ip<NumThreads; ip++) Movers[ip]->stopRun();
  for(int ip=0; ip<NumThreads; ip++)
    *(RandomNumberControl::Children[ip])=*(Rng[ip]);
  Estimators->stop();
  return finalize(block);
}
bool
RNDMCOMP::put(xmlNodePtr q)
{
  //nothing to do
  return true;
}
}

/***************************************************************************
 * $RCSfile: RNDMCOMP.cpp,v $   $Author: jnkim $
 * $Revision: 1620 $   $Date: 2007-01-14 18:12:23 -0600 (Sun, 14 Jan 2007) $
 * $Id: RNDMCOMP.cpp 1620 2007-01-15 00:12:23Z jnkim $
 ***************************************************************************/


text:
layout: doc
title: liaison - A data binding library that aims for emerging web standards compatibility
---

liaison has many features that helps you write your application with good separation-of-concern, on top of emerging standards.

## Declarative/imperative bindings

* [Declarative two-way bindings based on `<template>` with mustache syntax](./declarative.html)
  * [Advanced topics to work with `<template>`](./template.html)
* [Imperative two-way bindings to DOM and Custom Elements](./NodeBind.html)

## Change observation

* [Low-level observable objects](./Observable.html), shims of ES7 [`Object.observe()` and `Array.observe()`](http://wiki.ecmascript.org/doku.php?id=harmony:observe) based on "value-holder object" approach
* High-level observation API ([BindingSource](./BindingSource.html))


text:
require_relative '../../../spec_helper'
require_relative '../../../../app/controllers/carto/api/records_controller'
require_relative '../../../../spec/requests/api/json/records_controller_shared_examples'

describe Carto::Api::RecordsController do

  it_behaves_like 'records controllers' do
  end

  before(:all) do

    # Spec the routes so that it uses the new controller. Needed for alternative routes testing
    Rails.application.routes.draw do

      # new controller
      scope :module => 'carto/api', :format => :json do
        get    '(/user/:user_domain)(/u/:user_domain)/api/v1/tables/:table_id/records'     => 'records#index',   as: :api_v1_tables_records_index,  constraints: { table_id: /[^\/]+/ }
        get '(/user/:user_domain)(/u/:user_domain)/api/v1/tables/:table_id/records/:id'       => 'records#show',      as: :api_v1_tables_records_show,   constraints: { table_id: /[^\/]+/ }
      end

      # old controller
      scope :module => 'api/json', :format => :json do
        post '(/user/:user_domain)(/u/:user_domain)/api/v1/tables'     => 'tables#create', as: :api_v1_tables_create

        post '(/user/:user_domain)(/u/:user_domain)/api/v1/tables/:table_id/records'     => 'records#create',  as: :api_v1_tables_records_create, constraints: { table_id: /[^\/]+/ }
        put  '(/user/:user_domain)(/u/:user_domain)/api/v1/tables/:table_id/records/:id' => 'records#update',  as: :api_v1_tables_record_update,  constraints: { table_id: /[^\/]+/ }
        delete '(/user/:user_domain)(/u/:user_domain)/api/v1/tables/:table_id/records/:id' => 'records#destroy', as: :api_v1_tables_record_destroy, constraints: { table_id: /[^\/]+/ }
      end

    end

  end

  after(:all) do
    Rails.application.reload_routes!
  end

end


text:
<?php

	/**
	 * @package toolkit
	 */

	require_once FACE . '/interface.exportablefield.php';

	/**
	 * The Author field allows Symphony Authors to be selected in your entries.
	 * It is a read only field, new Authors cannot be added from the Frontend using
	 * events.
	 *
	 * The Author field allows filtering by Author ID or Username.
	 * Sorting is done based on the Author's first name and last name.
	 */
	class FieldAuthor extends Field implements ExportableField {
		public function __construct(){
			parent::__construct();
			$this->_name = __('Author');
			$this->_required = true;

			$this->set('author_types', array());
		}

	/*-------------------------------------------------------------------------
		Definition:
	-------------------------------------------------------------------------*/

		public function canToggle() {
			return ($this->get('allow_multiple_selection') == 'yes' ? false : true);
		}

		public function getToggleStates(){
			$authors = AuthorManager::fetch();

			$states = array();
			foreach($authors as $a) {
				$states[$a->get('id')] = $a->getFullName();
			}

			return $states;
		}

		public function toggleFieldData(array $data, $newState, $entry_id=null){
			$data['author_id'] = $newState;
			return $data;
		}

		public function canFilter(){
			return true;
		}

		public function isSortable(){
			return $this->canToggle();
		}

		public function allowDatasourceOutputGrouping(){
			// Grouping follows the same rule as toggling.
			return $this->canToggle();
		}

		public function allowDatasourceParamOutput() {
			return true;
		}

	/*-------------------------------------------------------------------------
		Setup:
	-------------------------------------------------------------------------*/

		public function createTable(){
			return Symphony::Database()->query(
				"CREATE TABLE IF NOT EXISTS `tbl_entries_data_" . $this->get('id') ."` (
				  `id` int(11) unsigned NOT NULL auto_increment,
				  `entry_id` int(11) unsigned NOT NULL,
				  `author_id` int(11) unsigned NULL,
				  PRIMARY KEY  (`id`),
				  UNIQUE KEY `author` (`entry_id`, `author_id`),
				  KEY `author_id` (`author_id`)
				) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;"
			);
		}

	/*-------------------------------------------------------------------------
		Utilities:
	-------------------------------------------------------------------------*/

		public function set($field, $value){
			if($field === 'author_types' && !is_array($value)){
				$value = explode(',', $value);
			}
			$this->_fields[$field] = $value;
		}

		/**
		 * Determines based on the input value whether we want to filter the Author
		 * field by ID or by the Author's Username
		 *
		 * @since Symphony 2.2
		 * @param string $value
		 * @return string
		 *  Either `author_id` or `username`
		 */
		private static function __parseFilter($value) {
			return is_numeric($value) ? 'author_id' : 'username';
		}

	/*-------------------------------------------------------------------------
		Settings:
	-------------------------------------------------------------------------*/

		public function findDefaults(array &$settings){
			if(!isset($settings['allow_multiple_selection'])) $settings['allow_multiple_selection'] = 'no';
			if(!isset($settings['author_types'])) $settings['author_types'] = array('developer', 'manager', 'author');
		}

		public function displaySettingsPanel(XMLElement &$wrapper, $errors = null) {
			parent::displaySettingsPanel($wrapper, $errors);
			$div = new XMLElement('div', NULL, array('class' => 'two columns'));

			// Choose between Authors/Developers or both
			$label = Widget::Label(__('Author types'));
			$label->setAttribute('class', 'column');
			$types = $this->get('author_types');
			$options = array(
				array('author', empty($types) ? true : in_array('author', $types), __('Author')),
                array('manager', empty($types) ? true : in_array('manager', $types), __('Manager')),
				array('developer', empty($types) ? true : in_array('developer', $types), __('Developer'))
			);
			$label->appendChild(
				Widget::Select('fields['.$this->get('sortorder').'][author_types][]', $options, array(
					'multiple' => 'multiple'
				))
			);
			$div->appendChild($label);

			if(isset($errors['author_types'])) {
				$wrapper->appendChild(Widget::Error($div, $errors['author_types']));
			}
			else $wrapper->appendChild($div);

			$div = new XMLElement('div', NULL, array('class' => 'two columns'));
			// Allow multiple selection
			$label = Widget::Label();
			$label->setAttribute('class', 'column');
			$input = Widget::Input('fields['.$this->get('sortorder').'][allow_multiple_selection]', 'yes', 'checkbox');
			if($this->get('allow_multiple_selection') == 'yes') $input->setAttribute('checked', 'checked');
			$label->setValue(__('%s Allow selection of multiple authors', array($input->generate())));
			$div->appendChild($label);

			// Default to current logged in user
			$label = Widget::Label();
			$label->setAttribute('class', 'column');
			$input = Widget::Input('fields['.$this->get('sortorder').'][default_to_current_user]', 'yes', 'checkbox');
			if($this->get('default_to_current_user') == 'yes') $input->setAttribute('checked', 'checked');
			$label->setValue(__('%s Select current user by default', array($input->generate())));
			$div->appendChild($label);
			$wrapper->appendChild($div);

			$div = new XMLElement('div', NULL, array('class' => 'two columns'));
			$this->appendRequiredCheckbox($div);
			$this->appendShowColumnCheckbox($div);
			$wrapper->appendChild($div);
		}

		public function checkFields(array &$errors, $checkForDuplicates = true) {
			parent::checkFields($errors, $checkForDuplicates);

			$types = $this->get('author_types');
			if(empty($types)){
				$errors['author_types'] = __('This is a required field.');
			}

			return (is_array($errors) && !empty($errors) ? self::__ERROR__ : self::__OK__);
		}

		public function commit(){
			if(!parent::commit()) return false;

			$id = $this->get('id');

			if($id === false) return false;

			$fields = array();

			$fields['allow_multiple_selection'] = ($this->get('allow_multiple_selection') ? $this->get('allow_multiple_selection') : 'no');
			$fields['default_to_current_user'] = ($this->get('default_to_current_user') ? $this->get('default_to_current_user') : 'no');
			if($this->get('author_types') != '') $fields['author_types'] = implode(',', $this->get('author_types'));

			return FieldManager::saveSettings($id, $fields);
		}

	/*-------------------------------------------------------------------------
		Publish:
	-------------------------------------------------------------------------*/

		public function displayPublishPanel(XMLElement &$wrapper, $data = null, $flagWithError = null, $fieldnamePrefix = null, $fieldnamePostfix = null, $entry_id = null){
			$value = isset($data['author_id']) ? $data['author_id'] : NULL;

			if ($this->get('default_to_current_user') == 'yes' && empty($data) && empty($_POST)) {
				$value = array(Administration::instance()->Author->get('id'));
			}

			if(!is_array($value)) $value = array($value);

			$options = array();

			if ($this->get('required') != 'yes') $options[] = array(NULL, false, NULL);

			// Custom where to only show Authors based off the Author Types setting
			$types = $this->get('author_types');
			if(!empty($types)) {
				$types = implode('","', $this->get('author_types'));
				$where = 'user_type IN ("' . $types . '")';
			}

			$authors = AuthorManager::fetch('id', 'ASC', null, null, $where);
			$found = false;
			foreach($authors as $a){
				if(in_array($a->get('id'), $value)) $found = true;

				$options[] = array($a->get('id'), in_array($a->get('id'), $value), $a->getFullName());
			}

			// Ensure the selected Author is included in the options (incase
			// the settings change after the original entry was created)
			if(!$found && !is_null($value)) {
				$authors = AuthorManager::fetchByID($value);
				foreach($authors as $a){
					$options[] = array($a->get('id'), in_array($a->get('id'), $value), $a->getFullName());
				}
			}

			$fieldname = 'fields'.$fieldnamePrefix.'['.$this->get('element_name').']'.$fieldnamePostfix;
			if($this->get('allow_multiple_selection') == 'yes') $fieldname .= '[]';

			$label = Widget::Label($this->get('label'));
			$label->appendChild(Widget::Select($fieldname, $options, ($this->get('allow_multiple_selection') == 'yes' ? array('multiple' => 'multiple') : NULL)));

			if($flagWithError != NULL) $wrapper->appendChild(Widget::Error($label, $flagWithError));
			else $wrapper->appendChild($label);
		}

		public function processRawFieldData($data, &$status, &$message=null, $simulate=false, $entry_id=NULL){
			$status = self::__OK__;

			if(!is_array($data) && !is_null($data)) return array('author_id' => $data);

			if(empty($data)) return NULL;

			$result = array();
			foreach($data as $id) $result['author_id'][] = $id;

			return $result;
		}

	/*-------------------------------------------------------------------------
		Output:
	-------------------------------------------------------------------------*/

		public function appendFormattedElement(XMLElement &$wrapper, $data, $encode = false, $mode = null, $entry_id = null){
			if(!is_array($data['author_id'])) $data['author_id'] = array($data['author_id']);

			$list = new XMLElement($this->get('element_name'));
			$authors = AuthorManager::fetchByID($data['author_id']);

			foreach($authors as $author) {
				if(is_null($author)) continue;

				$list->appendChild(new XMLElement(
					'item',
					$author->getFullName(),
					array(
						'id' => (string)$author->get('id'),
						'username' => General::sanitize($author->get('username'))
					)
				));
			}
			$wrapper->appendChild($list);
		}

		public function prepareTableValue($data, XMLElement $link = null, $entry_id = null){
			$value = $this->prepareExportValue($data, ExportableField::LIST_OF + ExportableField::VALUE, $entry_id);

			if(is_null($value)) return null;

			return parent::prepareTableValue(array('value' => General::sanitize(implode(', ', $value))), $link, $entry_id);
		}

		public function getParameterPoolValue(array $data, $entry_id = null) {
			return $this->prepareExportValue($data, ExportableField::LIST_OF + ExportableField::AUTHOR, $entry_id);
		}

	/*-------------------------------------------------------------------------
		Export:
	-------------------------------------------------------------------------*/

		/**
		 * Return a list of supported export modes for use with `prepareExportValue`.
		 *
		 * @return array
		 */
		public function getExportModes() {
			return array(
				'listAuthor' =>			ExportableField::LIST_OF
										+ ExportableField::AUTHOR,
				'listAuthorObject' =>	ExportableField::LIST_OF
										+ ExportableField::AUTHOR
										+ ExportableField::OBJECT,
				'listAuthorToValue'	=>	ExportableField::LIST_OF
										+ ExportableField::AUTHOR
										+ ExportableField::VALUE,
				'listValue' =>			ExportableField::LIST_OF
										+ ExportableField::VALUE,
				'getPostdata' =>		ExportableField::POSTDATA
			);
		}

		/**
		 * Give the field some data and ask it to return a value using one of many
		 * possible modes.
		 *
		 * @param mixed $data
		 * @param integer $mode
		 * @param integer $entry_id
		 * @return array|null
		 */
		public function prepareExportValue($data, $mode, $entry_id = null) {
			$modes = (object)$this->getExportModes();

			// Make sure we have an array to work with:
			if (isset($data['author_id']) && is_array($data['author_id']) === false) {
				$data['author_id'] = array(
					$data['author_id']
				);
			}

			// Return the author IDs:
			if ($mode === $modes->listAuthor || $mode === $modes->getPostdata) {
				return isset($data['author_id'])
					? $data['author_id']
					: array();
			}

			// All other modes require full data:
			$authors = isset($data['author_id'])
				? AuthorManager::fetchByID($data['author_id'])
				: array();
			$items = array();

			foreach ($authors as $author) {
				if (is_null($author)) continue;

				if ($mode === $modes->listAuthorObject) {
					$items[] = $author;
				}

				else if ($mode === $modes->listValue) {
					$items[] = $author->getFullName();
				}

				else if ($mode === $modes->listAuthorToValue) {
					$items[$data['author_id']] = $author->getFullName();
				}
			}

			return $items;
		}

	/*-------------------------------------------------------------------------
		Filtering:
	-------------------------------------------------------------------------*/

		public function buildDSRetrievalSQL($data, &$joins, &$where, $andOperation = false) {
			$field_id = $this->get('id');

			if (self::isFilterRegex($data[0])) {
				$this->_key++;

				if (preg_match('/^regexp:/i', $data[0])) {
					$pattern = preg_replace('/^regexp:\s*/i', null, $this->cleanValue($data[0]));
					$regex = 'REGEXP';
				} else {
					$pattern = preg_replace('/^not-?regexp:\s*/i', null, $this->cleanValue($data[0]));
					$regex = 'NOT REGEXP';
				}

				if(strlen($pattern) == 0) return;

				$joins .= "
					LEFT JOIN
						`tbl_entries_data_{$field_id}` AS t{$field_id}_{$this->_key}
						ON (e.id = t{$field_id}_{$this->_key}.entry_id)
					JOIN
						`tbl_authors` AS t{$field_id}_{$this->_key}_authors
						ON (t{$field_id}_{$this->_key}.author_id = t{$field_id}_{$this->_key}_authors.id)
				";
				$where .= "
					AND (
						t{$field_id}_{$this->_key}.author_id {$regex} '{$pattern}'
						OR t{$field_id}_{$this->_key}_authors.username {$regex} '{$pattern}'
					)
				";

			}
			elseif ($andOperation) {
				foreach ($data as $value) {
					$this->_key++;
					$value = $this->cleanValue($value);

					if(fieldAuthor::__parseFilter($value) == "author_id") {
						$where .= "
							AND t{$field_id}_{$this->_key}.author_id = '{$value}'
						";
						$joins .= "
							LEFT JOIN
								`tbl_entries_data_{$field_id}` AS t{$field_id}_{$this->_key}
								ON (e.id = t{$field_id}_{$this->_key}.entry_id)
						";
					}
					else {
						$joins .= "
							LEFT JOIN
								`tbl_entries_data_{$field_id}` AS t{$field_id}_{$this->_key}
								ON (e.id = t{$field_id}_{$this->_key}.entry_id)
							JOIN
								`tbl_authors` AS t{$field_id}_{$this->_key}_authors
								ON (t{$field_id}_{$this->_key}.author_id = t{$field_id}_{$this->_key}_authors.id)
						";
						$where .= "
							AND t{$field_id}_{$this->_key}_authors.username = '{$value}'
						";
					}
				}

			}
			else {
				if (!is_array($data)) $data = array($data);

				foreach ($data as &$value) {
					$value = $this->cleanValue($value);
				}

				$this->_key++;
				$data = implode("', '", $data);
				$joins .= "
					LEFT JOIN
						`tbl_entries_data_{$field_id}` AS t{$field_id}_{$this->_key}
						ON (e.id = t{$field_id}_{$this->_key}.entry_id)
					JOIN
						`tbl_authors` AS t{$field_id}_{$this->_key}_authors
						ON (t{$field_id}_{$this->_key}.author_id = t{$field_id}_{$this->_key}_authors.id)
				";
				$where .= "
					AND (
						t{$field_id}_{$this->_key}.author_id IN ('{$data}')
						OR
						t{$field_id}_{$this->_key}_authors.username IN ('{$data}')
						)
				";
			}

			return true;
		}

	/*-------------------------------------------------------------------------
		Sorting:
	-------------------------------------------------------------------------*/

		public function buildSortingSQL(&$joins, &$where, &$sort, $order='ASC'){
			if(in_array(strtolower($order), array('random', 'rand'))) {
				$sort = 'ORDER BY RAND()';
			}
			else {
				$joins .= "
					LEFT OUTER JOIN `tbl_entries_data_".$this->get('id')."` AS `ed` ON (`e`.`id` = `ed`.`entry_id`)
					JOIN `tbl_authors` AS `a` ON (ed.author_id = a.id)
				";
				$sort = "ORDER BY `a`.`first_name` " . $order . ", `a`.`last_name` " . $order;
			}
		}

	/*-------------------------------------------------------------------------
		Events:
	-------------------------------------------------------------------------*/

		public function getExampleFormMarkup(){

			$authors = AuthorManager::fetch();

			$options = array();

			foreach($authors as $a){
				$options[] = array($a->get('id'), NULL, $a->getFullName());
			}

			$fieldname = 'fields['.$this->get('element_name').']';
			if($this->get('allow_multiple_selection') == 'yes') $fieldname .= '[]';

			$attr = array();

			if($this->get('allow_multiple_selection') == 'yes') $attr['multiple'] = 'multiple';

			$label = Widget::Label($this->get('label'));
			$label->appendChild(Widget::Select($fieldname, $options, $attr));

			return $label;
		}

	/*-------------------------------------------------------------------------
		Grouping:
	-------------------------------------------------------------------------*/

		public function groupRecords($records){
			if(!is_array($records) || empty($records)) return;

			$groups = array($this->get('element_name') => array());

			foreach($records as $r) {
				$data = $r->getData($this->get('id'));

				if(!isset($data['author_id'])) {
					continue;
				}

				if(!isset($groups[$this->get('element_name')][$data['author_id']])) {
					$author = AuthorManager::fetchByID($data['author_id']);

					$groups[$this->get('element_name')][$data['author_id']] = array(
						'attr' => array('author-id' => $data['author_id'], 'username' => $author->get('username'), 'full-name' => $author->getFullName()),
						'records' => array(),
						'groups' => array()
					);
				}

				$groups[$this->get('element_name')][$data['author_id']]['records'][] = $r;
			}

			return $groups;
		}

	}


text:
<?php
include "lightncandy.php";

class Blitz {

    /**
     * Load a template file.
     */
    function __construct ($filename = NULL) {
        if (isset ($filename))
            $this->load (file_get_contents ($filename));
    }

    /**
     * Load a template.
     *
     * @param string $body Blitz template body
     *
     * @return void
     */
    public function load ($body) {
        $preparedBody = $this->prepare ($body);

        $this->code = LightnCandy::compile ($preparedBody, ["flags" =>
            LightnCandy::FLAG_BLITZ |
            LightnCandy::FLAG_BARE |        // compile to function, that don't print rendered data to screen, but return it as a string
            LightnCandy::FLAG_MUSTACHESP |  // remove spaces and linebreaks around context tags
            LightnCandy::FLAG_SPVARS |      // _num, _first, _last
            LightnCandy::FLAG_PARENT |      // _parent
            LightnCandy::FLAG_ELSE |        // enables else tag
            LightnCandy::FLAG_NOESCAPE |    // no html-escaping
            LightnCandy::FLAG_GLOBALS |
            LightnCandy::FLAG_ERROR_EXCEPTION
        ]);
//            LightnCandy::FLAG_ERROR_LOG
        $this->renderer = eval ($this->code);
    }

    /**
     * Render loaded template with data from $vars and print it.
     *
     * @param array() $vars Data to render the template.
     *
     * @return void
     */
    public function display ($vars = null) {
        echo $this->parse ($vars);
    }

    /**
     * Render loaded template with data from $vars and return it.
     *
     * @param array() $vars Data to render the template.
     *
     * @return void
     */
    public function parse ($vars = null) {
        if ($vars !== null)
            $this->set ($vars);
        $renderer = $this->renderer;    //PHP bug
        return $renderer($this->vars, null, $this, $this->globals);
    }

    /**
     * @param array() $vars Data to render the template.
     */
    public function set ($vars) {
        $this->vars = array_merge($this->vars, $vars);
    }

    /**
     * @param array() $vars Global data to render the template.
     */
    public function setGlobals ($vars) {
        $this->globals = $vars;
    }

    /**
     * Alias for setGlobals()
     */
    public function setGlobal ($vars) {
        $this->setGlobals ($vars);
    }

    public function clean () {
        $this->vars = [];
    }

    public function getIterations () {
        return [$this->vars];
    }

    public function fetch ($path, $vars) {
        $path = trim ($path, '/');
        $lastSection = strrchr ($path, '/');
        $lastSection = empty ($lastSection) ? $path : substr ($lastSection, 1);
        $lightncandyPath = '\[' . str_replace('/', '\]\[', $path) . '\]';

        $blockStart = "\\/\\* BLITZBLOCK_{$lightncandyPath} \\*\\/";
        $blockEnd  = "\\/\\* !BLITZBLOCK_{$lightncandyPath} \\*\\/";
        $codeRegex = "/^(.*?return )'.*?{$blockStart}(.*){$blockEnd}/s";

        if (!preg_match ($codeRegex, $this->code, $matches)) {
            /*ERROR*/;
            return;
        }

        $code = $matches [1] . $matches [2] . ';};';
        $vars = [$lastSection => $vars];

        $renderer = eval ($code);
        //Возможно, понадобится array_merge
        return $renderer ($vars, null, $this, $this->globals);
    }

    /**
     * Method, that converts Blitz templates to LightnCanduy.
     *
     * @param $template string Blitz template
     * @return string Handlebars template
     */
    protected function prepare ($template) {
        // before 5.6 PHP didn't allow to store arrays in consts
        if (Blitz::$tokensInitialized === false)
            Blitz::initializeBlitzHandlebarsTokens ();

        // Replace all <!-- --> tags with {{}}, and trim spaces inside tags
        $template = preg_replace (Blitz::$blitzTags, Blitz::$handlebarsTags, $template);

        // Throw the $s away. Throws away them even from strings.
        $template = preg_replace_callback (
            '/{{.*?}}/',
            function ($matches) {return str_replace('$', '', $matches [0]);},
            $template);

        // BEGIN, END, IF, block vars
        $template = preg_replace (Blitz::$blitzTokens, Blitz::$handlebarsTokens, $template);

        // Callbacks
        $template = preg_replace_callback (
            '/{{[^}]*?\\(.*?}}/',
            function ($matches) {
                $quoteCallback = preg_replace (
                    ['`{{([^ (]*?) *(\\( *(".*") *\\))}}`',
                     '`{{([^ (]*?) *(\\( *(\'.*\') *\\))}}`'],
                    ['{{<$1($3)}}',
                     '{{<$1($3)}}'],
                    $matches [0]);  // {{ foo ( "<smth>") }} -> {{<foo( "<smth>")}}
                if ($quoteCallback != $matches[0])
                    return $quoteCallback;

                preg_match ('/{{([^}]*?) *\\(([^)]*)\\)}}/', $matches [0], $callback);
                return "{{({$callback[1]} " . str_replace (',', ' ', $callback[2]) . '}}'; // {{ foo ( a ,b) }} -> {{(foo  a  b}}
            },
            $template);

        return $template;
    }

    private static function initializeBlitzHandlebarsTokens () {
        $id = '[a-zA-Z0-9_\.]+';    //ids + paths + numbers
        $expr = '[=><!]+';

        // contains pairs: Blitz token and matching Handlebars token
        $blitzHandlebarsTags = [
            ['`<!-- (.*?) -->`',        '{{$1}}'],
            ['`{{[ ]*(.*?)[ ]*}}`',     '{{$1}}'],
            ['`<!--[^-]*-->`',          '']    // Blitz treats "<!--" without space in the end as comments and doesn't show them
        ];

        $blitzHandlebarsTokens = [
            ['`{{(BEGIN|begin) +(.*?)}}`',      '{{#$2}}'],
            ['`{{(END|end)(| +(.*?))}}`',       '{{/$3}}'],

            ["`{{(IF|if) +($id)(| *($expr) *($id))}}`",             '{{#if $2 $4 $5}}'],
            ["`{{(UNLESS|unless) +($id)(| *($expr) *($id))}}`",     '{{#unless $2 $4 $5}}'],
            ["`{{ELSE}}`",       '{{else}}'],

            ['`{{(|[^}]* )_first(| [^}]*)}}`',      '{{$1@first$2}}'], // This regexps won't find block variables in function calls.
            ['`{{(|[^}]* )_last(| [^}]*)}}`',       '{{$1@last$2}}'],
            ['`{{(|[^}]* )_num(| [^}]*)}}`',        '{{$1@index$2}}'],
            ['`{{(|[^}]* )_parent\.(.*?)}}`',       '{{$1../$2}}']  // This will remove only the first occurrence of '_parent', which is fine for everything except callbacks
        ];

        Blitz::$blitzTags = array_map (function ($x) {return $x[0];}, $blitzHandlebarsTags);
        Blitz::$handlebarsTags = array_map (function ($x) {return $x[1];}, $blitzHandlebarsTags);
        Blitz::$blitzTokens = array_map (function ($x) {return $x[0];}, $blitzHandlebarsTokens);
        Blitz::$handlebarsTokens = array_map (function ($x) {return $x[1];}, $blitzHandlebarsTokens);
        Blitz::$tokensInitialized = true;
    }

    protected $code;
    protected $renderer;
    protected $vars = [];
    protected $globals = [];
    private static $tokensInitialized = false;
    private static $blitzTags = null;
    private static $handlebarsTags = null;
    private static $blitzTokens = null;
    private static $handlebarsTokens = null;
}


text:
import argparse
import MySQLdb
import os, os.path
from HTMLParser import HTMLParser
import codecs
from nltk import RegexpTokenizer
from nltk.corpus import stopwords

__author__ = 'guglielmo'

"""
This script helps generating a Categorized corpus (like the Reuters NLTK corpus)
that can be used for machine learning algorithms to assign tags to Openparlamento'c acts.

See Chapter 6 of Natural Language Processing With Python
and Chapter 7 of Python Text Processing With NLTK 2.0 Cookbook

usage::

    python generate_corpus.py --help

examples::
    python generate_corpus.py --db=op_openparlamento --act-types=3,4,5,6 --delete --limit=5000 ../corpora/opp_interrogazioni
    python generate_corpus.py --db=op_openparlamento --macro --act-types=2,3,4,5,6 --delete --limit=5000 ../corpora/opp_interrogazioni_macro

TODO: the acts and contents are directly fetched from a Mysql DB.
Accessing them through an API would decouple the script, avoiding the necessity
of having it run on Openparlamento's server.

"""

##
# HTML tag stripping through standard library's HTMLParser
##

class MLStripper(HTMLParser):
    def __init__(self):
        self.reset()
        self.fed = []
    def handle_data(self, d):
        self.fed.append(d)
    def get_data(self):
        return ''.join(self.fed)

def strip_tags(html):
    s = MLStripper()
    s.feed(html)
    return s.get_data()

##
# MySQL extraction functions
##

def get_acts(**kwargs):
    """
    Returns list of act_ids of given act types,
    sorted by presentation date.
    """
    db_conn = kwargs['db']
    limit = kwargs['limit']
    offset = kwargs['offset']
    act_types_ids = kwargs['act_types_ids']

    # sql is built this way because the ids list must be inserted
    # normally the placehoslders should be evaluated safely inside cursor.execute(sql, string parameters)
    sql = """
        select id as act_id
         from opp_atto
         where tipo_atto_id in (%s) order by data_pres
    """ % (act_types_ids, )

    cursor = db_conn.cursor(MySQLdb.cursors.DictCursor)

    if limit is not 0:
        if offset is not 0:
            sql += " limit {0}, {1}".format(offset, limit)
        else:
            sql += " limit {0}".format(limit)

    cursor.execute(sql)
    rows = cursor.fetchall()
    cursor.close()

    return [row['act_id'] for row in rows]

def get_tags(act_id, **kwargs):
    """
    Returns the list of tags associated with acts of the given act
    """
    db_conn = kwargs['db']

    cursor = db_conn.cursor(MySQLdb.cursors.DictCursor)
    sql = """
        select t.id as tag_id, t.triple_value as tag_name, t.triple_namespace as tag_namespace
         from sf_tag t, sf_tagging g
         where g.taggable_model='OppAtto'
          and t.triple_namespace not like '%%geo%%'
          and g.tag_id=t.id and g.taggable_id=%s
    """
    cursor.execute(sql, act_id)
    rows = cursor.fetchall()
    cursor.close()

    return [str(row['tag_id']) for row in rows]

def get_macro_tags(act_id, **kwargs):
    """
    Returns the list of unnique top-tags associated with acts of the given act
    """
    db_conn = kwargs['db']

    cursor = db_conn.cursor(MySQLdb.cursors.DictCursor)
    sql = """
        select distinct tt.teseott_id as tag_id, ttt.denominazione as tag_name
         from sf_tag t, sf_tagging g, opp_tag_has_tt tt, opp_teseott ttt
         where g.taggable_model='OppAtto' and
          g.tag_id=t.id and tt.tag_id=t.id and ttt.id=tt.teseott_id and
          g.taggable_id=%s;
    """
    cursor.execute(sql, act_id)
    rows = cursor.fetchall()
    cursor.close()

    return [str(row['tag_id']) for row in rows]

def get_documents_text(act_id, **kwargs):
    """
    Returns the concatenated, tag-stripped text of all documents related to act_id
    """
    db_conn = kwargs['db']

    italian_stops = set(stopwords.words('italian'))

    cursor = db_conn.cursor(MySQLdb.cursors.DictCursor)
    sql = """
        select d.testo
         from opp_documento as d
         where d.atto_id=%s
    """
    cursor.execute(sql, act_id)
    rows = cursor.fetchall()
    cursor.close()

    testo = u''
    for row in rows:
        # strip html tags from texts, if present
        testo += unicode(
            strip_tags(
                row['testo']
            )
        )

    # remove stopwords
    tokenizer = RegexpTokenizer("[\w]+")
    words = tokenizer.tokenize(testo)
    filtered_testo = " ".join([word for word in words if word.lower() not in italian_stops])

    return filtered_testo

##
# generating function
##

def generate(**kwargs):
    """
    Extract texts from acts' documents in db and produces files in the specified prefixed path
    Write a cats.txt categories file
    PATH
    |- ID1
    |- ID2
    |- ...
    |- cats.txt
    """
    path = kwargs['path']
    macro = kwargs['macro']

    if not os.path.exists(path):
        os.mkdir(path)

    # delete all files under path, if required
    if kwargs['delete']:
        for the_file in os.listdir(path):
            file_path = os.path.join(path, the_file)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
            except Exception, e:
                print e

    # write tags on cats.txt file
    cat_file = os.path.join(path, "cats.txt")
    f = codecs.open(cat_file, "w", "utf-8")

    for c, act_id in enumerate(get_acts(**kwargs)):
        print "{0}) {1}".format(c, act_id)

        # extract tags ids list
        if macro:
            tags_ids_list = ",".join(get_macro_tags(act_id, **kwargs))
        else:
            tags_ids_list = ",".join(get_tags(act_id, **kwargs))

        # only writes acts tags in cats file if there are some
        if tags_ids_list:

            # extract all texts from documents' acts
            testo = get_documents_text(act_id, **kwargs)

            # write to files only if there is a testo
            if testo:
                # write act's tags in file
                f.write(u"{0},{1}\n".format(act_id, tags_ids_list))

                # build text file name
                text_file_path = os.path.join(path, str(act_id))

                # open text file in append mode, append content to it, close the file
                tf = codecs.open(text_file_path, "a", "utf-8")
                tf.write(testo)
                tf.close()
    f.close()

##
# Main function, called when directly calling the script
##
def main():

    # setup command-line args parser
    parser = argparse.ArgumentParser()

    parser.add_argument("-q", "--quiet", dest="quiet",
                        help="do not print to stdout", action="store_true")

    parser.add_argument("--db", dest="db",
                        help="the openparlamento database to extract data from, defaults to op_openparlamento",
                        default='op_openparlamento')

    parser.add_argument("--act-types-ids", dest="act_types_ids",
                        help="a comma separated list of acts types ids",
                        default='1')

    parser.add_argument("--limit", dest="limit",
                        help="limit the number of acts analyzed (0 = no limit)", type=int,
                        default=0)

    parser.add_argument("--offset", dest="offset",
                        help="offset of acts analyzed (0 = no offset)", type=int,
                        default=0)

    parser.add_argument("--delete", dest="delete",
                        help="remove previously created file in path and prefix", action='store_true',
                        default=False)

    parser.add_argument("--macro", dest="macro",
                        help="indicates that macro (top) categories should be extracted", action='store_true',
                        default=False)

    parser.add_argument("path",
                        help="where produced files and categories will be written, an absolute path")

    args = parser.parse_args()

    # connect to RDBMS server
    db = MySQLdb.connect(
        host="localhost",
        user="root",
        passwd="",
        db=args.db,
        charset='utf8',
        use_unicode=True
    )

    # build kwargs list for functions
    kwargs = {
        'act_types_ids': args.act_types_ids,
        'path': args.path,
        'delete': args.delete,
        'macro': args.macro,
        'limit': args.limit, 'offset': args.offset,
        'db': db,
    }

    # call generating function
    generate(**kwargs)

    # disconnect from server
    db.close()

if __name__ == "__main__":
  main()


text:
This test case asserts that a simple `py_test` is generated as expected when a
`conftest.py` is present.


text:
PLEASE NOTE: This document applies to the HEAD of the source tree

If you are using a released version of Kubernetes, you should
refer to the docs that go with that version.

Documentation for other releases can be found at
[releases.k8s.io](http://releases.k8s.io).

--

# Example: Multiple Job Objects from Template Expansion

In this example, we will run multiple Kubernetes Jobs created from
a common template.  You may want to be familiar with the basic,
non-parallel, use of [Job](../../../docs/user-guide/jobs.md) first.

## Basic Template Expansion

First, create a template of a Job object:

```
apiVersion: extensions/v1beta1
kind: Job
metadata:
  name: process-item-$ITEM
spec:
  selector:
    matchLabels:
      app: jobexample
      item: $ITEM
  template:
    metadata:
      name: jobexample
      labels:
        app: jobexample
        item: $ITEM
    spec:
      containers:
      - name: c
        image: busybox
        command: ["sh", "-c", "echo Processing item $ITEM && sleep 5"]
      restartPolicy: Never
```

[Download example](job.yaml.txt?raw=true)

Unlike a *pod template*, our *job template* is not a Kubernetes API type.  It is just
a yaml representation of a Job object that has some placeholders that need to be filled
in before it can be used.  The `$ITEM` syntax is not meaningful to Kubernetes.

In this example, the only processing the container does is to `echo` a string and sleep for a bit.
In a real use case, the processing would be some substantial computation, such as rendering a frame
of a movie, or processing a range of rows in a database.  The "$ITEM" parameter would specify for
example, the frame number or the row range.

This Job has two labels. The first label, `app=jobexample`, distinguishes this group of jobs from
other groups of jobs (these are not shown, but there might be other ones).  This label
makes it convenient to operate on all the jobs in the group at once.  The second label, with
key `item`, distinguishes individual jobs in the group.  Each Job object needs to have
a unique label that no other job has.  This is it.
Neither of these label keys are special to kubernetes -- you can pick your own label scheme.

Next, expand the template into multiple files, one for each item to be processed.

```console
# Expand files into a temporary directory
$ mkdir ./jobs
$ for i in apple banana cherry
do
  cat job.yaml.txt | sed "s/\$ITEM/$i/" > ./jobs/job-$i.yaml
done
$ ls jobs/
job-apple.yaml
job-banana.yaml
job-cherry.yaml
```

Here, we used `sed` to replace the string `$ITEM` with the the loop variable.
You could use any type of template language (jinja2, erb) or write a program
to generate the Job objects.

Next, create all the jobs with one kubectl command:

```console
$ kubectl create -f ./jobs
job "process-item-apple" created
job "process-item-banana" created
job "process-item-cherry" created
```

Now, check on the jobs:

```console
$ kubectl get jobs -l app=jobexample -L item
JOB                   CONTAINER(S)   IMAGE(S)   SELECTOR                               SUCCESSFUL ITEM
process-item-apple    c              busybox    app in (jobexample),item in (apple)    1          apple
process-item-banana   c              busybox    app in (jobexample),item in (banana)   1          banana
process-item-cherry   c              busybox    app in (jobexample),item in (cherry)   1          cherry
```

Here we use the `-l` option to select all jobs that are part of this
group of jobs.  (There might be other unrelated jobs in the system that we
do not care to see.)

The `-L` option adds an extra column with just the `item` label value.

We can check on the pods as well using the same label selector:

```console
$ kubectl get pods -l app=jobexample -L item
NAME                        READY     STATUS      RESTARTS   AGE       ITEM
process-item-apple-kixwv    0/1       Completed   0          4m        apple
process-item-banana-wrsf7   0/1       Completed   0          4m        banana
process-item-cherry-dnfu9   0/1       Completed   0          4m        cherry
```

There is not a single command to check on the output of all jobs at once,
but looping over all the pods is pretty easy:

```console
$ for p in $(kubectl get pods -l app=jobexample -o name)
do
  kubectl logs $p
done
Processing item apple
Processing item banana
Processing item cherry
```

## Multiple Template Parameters

In the first example, each instance of the template had one parameter, and that parameter was also
used as a label.  However label keys are limited in [what characters they can
contain](labels.md#syntax-and-character-set).

This slightly more complex example uses a the jinja2 template language to generate our objects.
We will use a one-line python script to convert the template to a file.

First, download or paste the following template file to a file called `job.yaml.jinja2`:

```
{%- set params = [{ "name": "apple", "url": "http://www.orangepippin.com/apples", },
                  { "name": "banana", "url": "https://en.wikipedia.org/wiki/Banana", },
                  { "name": "raspberry", "url": "https://www.raspberrypi.org/" }]
%}
{%- for p in params %}
{%- set name = p["name"] %}
{%- set url = p["url"] %}
apiVersion: extensions/v1beta1
kind: Job
metadata:
  name: jobexample-{{ name }}
spec:
  selector:
    matchLabels:
      app: jobexample
      item: {{ name }}
  template:
    metadata:
      name: jobexample
      labels:
        app: jobexample
        item: {{ name }}
    spec:
      containers:
      - name: c
        image: busybox
        command: ["sh", "-c", "echo Processing URL {{ url }} && sleep 5"]
      restartPolicy: Never
---
{%- endfor %}
```

[Download example](job.yaml.jinja2?raw=true)

The above template defines parameters for each job object using a list of
python dicts (lines 1-4).  Then a for loop emits one job yaml object
for each set of parameters (remaining lines).
We take advantage of the fact that multiple yaml documents can be concatenated
with the `---` separator (second to last line).
.)  We can pipe the output directly to kubectl to
create the objects.

You will need the jinja2 package if you do not already have it: `pip install --user jinja2`.
Now, use this one-line python program to expand the template:

```
$ alias render_template='python -c "from jinja2 import Template; import sys; print(Template(sys.stdin.read()).render());"'
```

The output can be saved to a file, like this:

```
$ cat job.yaml.jinja2 | render_template > jobs.yaml
```

or sent directly to kubectl, like this:

```
$ cat job.yaml.jinja2 | render_template | kubectl create -f -
```

## Alternatives

If you have a large number of job objects, you may find that:

- even using labels, managing so many Job objects is cumbersome.
- you exceed resource quota when creating all the Jobs at once,
  and do not want to wait to create them incrementally.
- you need a way to easily scale the number of pods running
  concurrently.  One reason would be to avoid using too many
  compute resources.  Another would be to limit the number of
  concurrent requests to a shared resource, such as a database,
  used by all the pods in the job.
- very large numbers of jobs created at once overload the
  kubernetes apiserver, controller, or scheduler.

In this case, you can consider one of the
other [job patterns](../../../docs/user-guide/jobs.md#job-patterns).

[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/examples/job/expansions/README.md?pixel)]()


text:
static bool editor_hidpi=false;

void editor_set_hidpi(bool p_hidpi) {

	editor_hidpi=p_hidpi;
}

bool editor_is_hidpi() {

	return editor_hidpi;
}


text:
package com.jflyfox.dudu.component.beetl;

import com.jflyfox.util.DateUtils;
import com.jflyfox.util.StrUtils;
import com.jflyfox.util.extend.HtmlUtils;

public class BeetlFunctions {

    public static String getNow() {
        return DateUtils.getNow();
    }

    public static String getNow(String regex) {
        return DateUtils.getNow(regex);
    }

    public static String suojin(String str, int length) {
        return StrUtils.suojin(str, length);
    }

    /**
     * html预览
     * <p>
     * 2015年2月2日 下午3:40:34 flyfox 369191470@qq.com
     *
     * @param htmlStr
     * @return
     */
    public static String showHTML(String htmlStr, int num, String endStr) {
        String tmpStr = HtmlUtils.delHTMLTag(htmlStr);
        tmpStr = StrUtils.suojin(tmpStr, num + endStr.length(), endStr);
        return tmpStr;
    }
}


text:
package org.apache.flink.runtime.operators.lifecycle.command;

/**
 * A command to be executed by a test operator. Upon execution, it must be acked by sending an
 * {@link org.apache.flink.runtime.operators.lifecycle.event.TestCommandAckEvent Ack} event.
 */
public interface TestCommand {
    TestCommand DELAY_SNAPSHOT =
            new TestCommand() {
                @Override
                public boolean isTerminal() {
                    return false;
                }

                @Override
                public String toString() {
                    return "DELAY_SNAPSHOT";
                }
            };
    TestCommand FAIL_SNAPSHOT =
            new TestCommand() {
                @Override
                public boolean isTerminal() {
                    return true;
                }

                @Override
                public String toString() {
                    return "FAIL_SNAPSHOT";
                }
            };
    TestCommand FAIL =
            new TestCommand() {
                @Override
                public boolean isTerminal() {
                    return true;
                }

                @Override
                public String toString() {
                    return "FAIL";
                }
            };
    TestCommand FINISH_SOURCES =
            new TestCommand() {
                @Override
                public boolean isTerminal() {
                    return true;
                }

                @Override
                public String toString() {
                    return "FINISH_SOURCES";
                }
            };

    boolean isTerminal();
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Acer
 * Date: 1/19/2015
 * Time: 4:05 PM
 */

class LLessonsController {
    public function progress($userid, $lessonid){
        //Configure::write('debug',0);
        //$this->layout = 'ajax';
        $this->autoRender = false;
        //if(isset($userid) && !empty($userid) && isset($lessonid) && !empty($lessonid)){
        //$progress = $this->Lesson->find('first', array('recursive'=>2,'conditions'=>array('Lesson.id ='=>$lessonid ,'User.id ='=>$userid) ));
//  $this->Lesson->unbindModel(
//   array('hasMany' => array('Content','Condition','Period'), 'hasAndBelongsToMany' => array('Course'))
//  );
        $total_completed_contents = $this->Lesson->query('SELECT total_completed_content FROM lesson_users AS LessonUser WHERE lesson_id ='.$lessonid .' AND user_id ='.$userid);
        //debug($progress);

        //$this->loadModel('LessonUser');
//  $total_completed_contents = $this->LessonUser->find('all',
//       array('fields'=>array('total_completed_content'),
//         'conditions'=>array('user_id ='=>$userid, 'lesson_id'=>$lessonid),
//     )
//    );
        $this->loadModel('Content');
        $total_contents = $this->Content->find('count',array('conditions'=>array('Content.lesson_id ='=>$lessonid)));
        //}
        echo json_encode(array( 'total_content'=>$total_contents,
                'content_completion'=>$total_completed_contents[0]['LessonUser']['total_completed_content'],
                'percentage'=>ceil(($total_completed_contents[0]['LessonUser']['total_completed_content']/$total_contents)*100).'%'
            )
        );

    }

    public function faq(){
        //Configure::write('debug',0);
        //$this->layout = 'ajax';
        $this->autoRender = false;
        //if(isset($userid) && !empty($userid) && isset($lessonid) && !empty($lessonid)){
        //$progress = $this->Lesson->find('first', array('recursive'=>2,'conditions'=>array('Lesson.id ='=>$lessonid ,'User.id ='=>$userid) ));
//  $this->Lesson->unbindModel(
//   array('hasMany' => array('Content','Condition','Period'), 'hasAndBelongsToMany' => array('Course'))
//  );
//  $total_completed_contents = $this->Lesson->query('SELECT total_completed_content FROM lesson_users AS LessonUser WHERE lesson_id ='.$lessonid .' AND user_id ='.$userid);
        //debug($progress);

        $this->loadModel('Faq');
        $total_question = $this->Faq->find('all',
            array('fields'=>array('question'),
            )
        );
//  var_dump($total_question);
//  $this->loadModel('Content');
//  $total_contents = $this->Faq->find('count',array('conditions'=>array('Faq.id ='=>$lessonid)));
        //}
        echo json_encode(array(
                'question'=>$total_question,

            )
        );

    }
}


text:
(function() {

  function SongPlayer($rootScope, Fixtures) {

/**
* @desc SongPlayer set to an Object
* @type {Object}
**/
    var SongPlayer = {};

/**
* @desc currentAlbum set from getAlbum in Fixtures
* @type {Object}
**/
    var currentAlbum = Fixtures.getAlbum();

/**
* @desc Buzz object audio file
* @type {Object}
**/
    var currentBuzzObject = null;

/**
* @function setSong
* @desc Stops currently playing song and loads new audio file as currentBuzzObject
* @param {Object} song
**/
    var setSong = function(song) {
      if (currentBuzzObject) {
        currentBuzzObject.stop();
        SongPlayer.currentSong.playing = null;
      }

      currentBuzzObject = new buzz.sound(song.audioUrl, {
        formats: ['mp3'],
        preload: true
      });

      currentBuzzObject.bind('timeupdate', function() {
        $rootScope.$apply(function() {
          SongPlayer.currentTime = currentBuzzObject.getTime();
        });
      });

      SongPlayer.currentSong = song;
    };

/**
* @function playSong
* @desc Plays song and sets song.playing to true
* @param {Object} song
**/
    var playSong = function(song) {
      currentBuzzObject.play();
      song.playing = true;
      SongPlayer.muted = false;
    };

/**
* @function stopSong
* @desc Stops song and sets song.playing to null
* @param {Object} song
**/
    var stopSong = function(song) {
      currentBuzzObject.stop();
      song.playing = null;
    }

/**
* @function getSongIndex
* @desc Get the index of a song from album(s)
* @param {Object} song
**/
    var getSongIndex = function(song) {
      return currentAlbum.songs.indexOf(song);
    };

/**
* @desc currentSong set to null on page load
* @type {Object}
**/
    SongPlayer.currentSong = null;

/**
* @desc currentTime set to null on page load
* @type {Number}
**/
    SongPlayer.currentTime = null;

/**
* @desc Set song player volume, default: 80
* @type {Number}
**/
    SongPlayer.volume = 80;

/**
* @desc Set value for whether or not a song is muted
* @type {Boolean}
**/
    SongPlayer.muted = false;

/**
* @function SongPlayer.play(song)
* @desc Plays a new song and resumes a paused song
* @param {Object} song
**/
    SongPlayer.play = function(song) {
      song = song || SongPlayer.currentSong;

      if (SongPlayer.currentSong !== song) {
        setSong(song);
        playSong(song);

      } else if (SongPlayer.currentSong === song) {
        if (currentBuzzObject.isPaused()) {
          playSong(song);
        }
      }
    };

/**
* @function SongPlayer.pause(song)
* @desc Pauses a currently playing song and sets song.playing to false
* @param {Object} song
**/
    SongPlayer.pause = function(song) {
      song = song || SongPlayer.currentSong;

      currentBuzzObject.pause();
      song.playing = false;
    };

/**
* @function SongPlayer.previous()
* @desc Goes to the previously played song through the song index
* @param {Number} currentSongIndex
**/
    SongPlayer.previous = function() {
      var currentSongIndex = getSongIndex(SongPlayer.currentSong);
      currentSongIndex--;

      if (currentSongIndex < 0) {
        currentBuzzObject.stop();
        SongPlayer.currentSong.playing = null;

      } else {
        var song = currentAlbum.songs[currentSongIndex];
        setSong(song);
        playSong(song);
      }
    };

/**
* @function SongPlayer.next()
* @desc Goes to the next song through the song index
* @param {Number} currentSongIndex
**/
    SongPlayer.next = function() {
      var currentSongIndex = getSongIndex(SongPlayer.currentSong);
      currentSongIndex++;

      if (currentSongIndex > currentAlbum.songs.length) {
        stopSong(song);

      } else {
        var song = currentAlbum.songs[currentSongIndex];
        setSong(song);
        playSong(song);
      }
    };

/**
* @function setCurrentTime
* @desc Set current time (in seconds) of currently playing song
* @param {Number} time
**/
    SongPlayer.setCurrentTime = function(time) {
      if (currentBuzzObject) {
        currentBuzzObject.setTime(time);
      }
    };

/**
* @function setVolume
* @desc Set volume based on volume bar
* @param {Number} volume
**/
    SongPlayer.setVolume = function(volume) {
      if (currentBuzzObject) {
        currentBuzzObject.setVolume(volume);
      }
    };

/**
* @function muteVolume
* @desc Mute volume based on icon click
* @param {Number} volume
**/
    SongPlayer.muteVolume = function() {
      if (currentBuzzObject) {
        if (!currentBuzzObject.isMuted()) {                                      /* If currentBuzzObject is NOT muted */
          currentBuzzObject.mute();                                              /* Mute buzz object */
          SongPlayer.muted = true;                                               /* Set SongPlayer.muted value to 'true' */

        } else {                                                                 /* If currentBuzzObject IS muted */
            currentBuzzObject.unmute();                                          /* Unmute buzz object */
            SongPlayer.muted = false;                                            /* Set SongPlayer.muted value to 'false' */
        }
      }
    };

    return SongPlayer;

  }                                                                              /* End SongPlayer() */

  angular
    .module('blocJams')                                                          /* Angular module 'blocJams' */
    .factory('SongPlayer', ['$rootScope', 'Fixtures', SongPlayer]);              /* Factory recipe name: SongPlayer, Callback: $rootScope, Fixtures, SongPlayer */

})();


text:
#include <aws/marketplace-catalog/model/ListChangeSetsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::MarketplaceCatalog::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

ListChangeSetsRequest::ListChangeSetsRequest() :
    m_catalogHasBeenSet(false),
    m_filterListHasBeenSet(false),
    m_sortHasBeenSet(false),
    m_maxResults(0),
    m_maxResultsHasBeenSet(false),
    m_nextTokenHasBeenSet(false)
{
}

Aws::String ListChangeSetsRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_catalogHasBeenSet)
  {
   payload.WithString("Catalog", m_catalog);

  }

  if(m_filterListHasBeenSet)
  {
   Array<JsonValue> filterListJsonList(m_filterList.size());
   for(unsigned filterListIndex = 0; filterListIndex < filterListJsonList.GetLength(); ++filterListIndex)
   {
     filterListJsonList[filterListIndex].AsObject(m_filterList[filterListIndex].Jsonize());
   }
   payload.WithArray("FilterList", std::move(filterListJsonList));

  }

  if(m_sortHasBeenSet)
  {
   payload.WithObject("Sort", m_sort.Jsonize());

  }

  if(m_maxResultsHasBeenSet)
  {
   payload.WithInteger("MaxResults", m_maxResults);

  }

  if(m_nextTokenHasBeenSet)
  {
   payload.WithString("NextToken", m_nextToken);

  }

  return payload.View().WriteReadable();
}


text:
using System;

using Android.Content;
using Android.Runtime;
using Android.Widget;
using Android.Util;
using Android;

namespace MvvmQuickCross
{
    // Based on https://github.com/xamarin/monodroid-samples/blob/master/CustomChoiceList/CheckableLinearLayout.cs
    // For usage tip on propogating child state changes, see: http://chris.banes.me/2013/03/22/checkable-views/

    public class CheckableLinearLayout : LinearLayout, ICheckable
    {
        static readonly int[] CHECKED_STATE_SET = { Resource.Attribute.StateChecked };
        private bool _checked = false;

        public CheckableLinearLayout(Context context) : base(context) { }
        public CheckableLinearLayout(Context context, IAttributeSet attrs) : base(context, attrs) { }
        public CheckableLinearLayout(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer) { }
        public CheckableLinearLayout(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle) { }

        protected override int[] OnCreateDrawableState(int extraSpace)
        {
            int[] drawableState = base.OnCreateDrawableState(extraSpace + 1);
            if (Checked) MergeDrawableStates(drawableState, CHECKED_STATE_SET);
            return drawableState;
        }

        public bool Checked
        {
            get { return _checked; }
            set { if (_checked != value) { _checked = value; RefreshDrawableState(); } }
        }

        public void Toggle() { Checked = !Checked; }
    }

    public class CheckableRelativeLayout : RelativeLayout, ICheckable
    {
        static readonly int[] CHECKED_STATE_SET = { Resource.Attribute.StateChecked };
        private bool _checked = false;

        public CheckableRelativeLayout(Context context) : base(context) { }
        public CheckableRelativeLayout(Context context, IAttributeSet attrs) : base(context, attrs) { }
        public CheckableRelativeLayout(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer) { }
        public CheckableRelativeLayout(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle) { }

        protected override int[] OnCreateDrawableState(int extraSpace)
        {
            int[] drawableState = base.OnCreateDrawableState(extraSpace + 1);
            if (Checked) MergeDrawableStates(drawableState, CHECKED_STATE_SET);
            return drawableState;
        }

        public bool Checked
        {
            get { return _checked; }
            set { if (_checked != value) { _checked = value; RefreshDrawableState(); } }
        }

        public void Toggle() { Checked = !Checked; }
    }
}


text:
'use strict';

//Chemicaldocs service used to communicate Chemicaldocs REST endpoints
angular.module('chemicaldocs').factory('Chemicaldocs', ['$resource',
	function($resource) {
		return $resource('api/chemicaldocs/:chemicaldocId', { chemicaldocId: '@_id'
		}, {
			update: {
				method: 'PUT'
			}
		});
	}
]);