text:
package com.elmakers.mine.bukkit;

import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import org.bukkit.Location;
import org.bukkit.plugin.Plugin;

public class WorldGuardManager {
	private WorldGuardPlugin worldGuard = null;

	public void initialize(Plugin plugin) {
        try {
            Plugin wgPlugin = plugin.getServer().getPluginManager().getPlugin("WorldGuard");
            if (wgPlugin instanceof WorldGuardPlugin) {
                worldGuard = (WorldGuardPlugin)wgPlugin;
            }
        } catch (Throwable ex) {
        }

        if (worldGuard == null) {
            plugin.getLogger().info("WorldGuard not found, regions will be ignored.");
        }  else {
            plugin.getLogger().info("WorldGuard found, will ignore chunks in any region");
		}
	}

    public boolean isPassthrough(Location location) {
		if (worldGuard == null || location == null) return true;

		RegionManager regionManager = worldGuard.getRegionManager(location.getWorld());
        if (regionManager == null) return true;

		ApplicableRegionSet checkSet = regionManager.getApplicableRegions(location);
		if (checkSet == null) return true;
		return checkSet.size() == 0 || checkSet.allows(DefaultFlag.PASSTHROUGH);
	}
}


text:
using System;
using System.Runtime;
using System.ServiceModel;
using System.Threading;

namespace System.ServiceModel.Dispatcher
{
    internal class ThreadBehavior
    {
        private SendOrPostCallback _threadAffinityStartCallback;
        private SendOrPostCallback _threadAffinityEndCallback;
        private static Action<object> s_cleanThreadCallback;
        private readonly SynchronizationContext _context;

        internal ThreadBehavior(DispatchRuntime dispatch)
        {
            _context = dispatch.SynchronizationContext;
        }

        private SendOrPostCallback ThreadAffinityStartCallbackDelegate
        {
            get
            {
                if (_threadAffinityStartCallback == null)
                {
                    _threadAffinityStartCallback = new SendOrPostCallback(this.SynchronizationContextStartCallback);
                }
                return _threadAffinityStartCallback;
            }
        }
        private SendOrPostCallback ThreadAffinityEndCallbackDelegate
        {
            get
            {
                if (_threadAffinityEndCallback == null)
                {
                    _threadAffinityEndCallback = new SendOrPostCallback(this.SynchronizationContextEndCallback);
                }
                return _threadAffinityEndCallback;
            }
        }

        private static Action<object> CleanThreadCallbackDelegate
        {
            get
            {
                if (ThreadBehavior.s_cleanThreadCallback == null)
                {
                    ThreadBehavior.s_cleanThreadCallback = new Action<object>(ThreadBehavior.CleanThreadCallback);
                }
                return ThreadBehavior.s_cleanThreadCallback;
            }
        }

        internal void BindThread(ref MessageRpc rpc)
        {
            this.BindCore(ref rpc, true);
        }

        internal void BindEndThread(ref MessageRpc rpc)
        {
            this.BindCore(ref rpc, false);
        }

        private void BindCore(ref MessageRpc rpc, bool startOperation)
        {
            SynchronizationContext syncContext = GetSyncContext(rpc.InstanceContext);

            if (syncContext != null)
            {
                IResumeMessageRpc resume = rpc.Pause();
                if (startOperation)
                {
                    syncContext.OperationStarted();
                    syncContext.Post(this.ThreadAffinityStartCallbackDelegate, resume);
                }
                else
                {
                    syncContext.Post(this.ThreadAffinityEndCallbackDelegate, resume);
                }
            }
            else if (rpc.SwitchedThreads)
            {
                IResumeMessageRpc resume = rpc.Pause();
                ActionItem.Schedule(ThreadBehavior.CleanThreadCallbackDelegate, resume);
            }
        }

        private SynchronizationContext GetSyncContext(InstanceContext instanceContext)
        {
            Fx.Assert(instanceContext != null, "instanceContext is null !");
            SynchronizationContext syncContext = instanceContext.SynchronizationContext ?? _context;
            return syncContext;
        }

        private void SynchronizationContextStartCallback(object state)
        {
            ResumeProcessing((IResumeMessageRpc)state);
        }
        private void SynchronizationContextEndCallback(object state)
        {
            IResumeMessageRpc resume = (IResumeMessageRpc)state;

            ResumeProcessing(resume);

            SynchronizationContext syncContext = GetSyncContext(resume.GetMessageInstanceContext());
            Fx.Assert(syncContext != null, "syncContext is null !?");
            syncContext.OperationCompleted();
        }
        private void ResumeProcessing(IResumeMessageRpc resume)
        {
            bool alreadyResumedNoLock;
            resume.Resume(out alreadyResumedNoLock);

            if (alreadyResumedNoLock)
            {
                string text = SR.Format(SR.SFxMultipleCallbackFromSynchronizationContext, _context.GetType().ToString());
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(text));
            }
        }

        private static void CleanThreadCallback(object state)
        {
            bool alreadyResumedNoLock;
            ((IResumeMessageRpc)state).Resume(out alreadyResumedNoLock);

            if (alreadyResumedNoLock)
            {
                Fx.Assert("IOThreadScheduler called back twice");
            }
        }

        internal static SynchronizationContext GetCurrentSynchronizationContext()
        {
            return SynchronizationContext.Current;
        }
    }
}

redpajama_set_name: RedPajamaGithub


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

namespace ES5.Script.EcmaScript.Objects
{
    public class PropertyValue
    {
        public PropertyValue(PropertyAttributes aAttributes, object aValue)
        {
            Value = aValue;
            Attributes = aAttributes | PropertyAttributes.HasValue;
        }

        public PropertyValue(PropertyAttributes aAttributes, EcmaScriptBaseFunctionObject aGet, EcmaScriptBaseFunctionObject aSet)
        {
            Attributes = aAttributes;
            Get = aGet;
            Set = aSet;
        }

        public EcmaScriptObject Owner { get; set; }
        public ulong Ticks { get; set; }
        public bool Deleted { get; set; }

        public PropertyAttributes Attributes { get; set; }
        public EcmaScriptBaseFunctionObject Get { get; set; }
        public EcmaScriptBaseFunctionObject Set { get; set; }
        public object Value { get; set; }

        public static PropertyValue Enumerable(object aValue)
        {
            return new PropertyValue(PropertyAttributes.Enumerable, aValue);
        }

        public static PropertyValue NotEnum(object aValue)
        {
            return new PropertyValue(PropertyAttributes.All & ~PropertyAttributes.Enumerable, aValue);
        }

        public static PropertyValue NotAllFlags(object aValue)
        {
            return new PropertyValue(PropertyAttributes.None, aValue);
        }

        public static PropertyValue NotDeleteAndReadOnly(object aValue)
        {
            return new PropertyValue(PropertyAttributes.All & ~PropertyAttributes.Writable & ~PropertyAttributes.Configurable, aValue);
        }

        public static PropertyValue Create(object aValue, PropertyAttributes properties = PropertyAttributes.None)
        {
            return new PropertyValue(properties, aValue);
        }
    }
}


text:
package tfexec

import (
	"context"
	"fmt"
	"os/exec"
	"strconv"
)

type workspaceNewConfig struct {
	lock        bool
	lockTimeout string
	copyState   string
}

var defaultWorkspaceNewOptions = workspaceNewConfig{
	lock:        true,
	lockTimeout: "0s",
}

// WorkspaceNewCmdOption represents options that are applicable to the WorkspaceNew method.
type WorkspaceNewCmdOption interface {
	configureWorkspaceNew(*workspaceNewConfig)
}

func (opt *LockOption) configureWorkspaceNew(conf *workspaceNewConfig) {
	conf.lock = opt.lock
}

func (opt *LockTimeoutOption) configureWorkspaceNew(conf *workspaceNewConfig) {
	conf.lockTimeout = opt.timeout
}

func (opt *CopyStateOption) configureWorkspaceNew(conf *workspaceNewConfig) {
	conf.copyState = opt.path
}

// WorkspaceNew represents the workspace new subcommand to the Terraform CLI.
func (tf *Terraform) WorkspaceNew(ctx context.Context, workspace string, opts ...WorkspaceNewCmdOption) error {
	cmd, err := tf.workspaceNewCmd(ctx, workspace, opts...)
	if err != nil {
		return err
	}
	return tf.runTerraformCmd(ctx, cmd)
}

func (tf *Terraform) workspaceNewCmd(ctx context.Context, workspace string, opts ...WorkspaceNewCmdOption) (*exec.Cmd, error) {
	// TODO: [DIR] param option

	c := defaultWorkspaceNewOptions

	for _, o := range opts {
		switch o.(type) {
		case *LockOption, *LockTimeoutOption:
			err := tf.compatible(ctx, tf0_12_0, nil)
			if err != nil {
				return nil, fmt.Errorf("-lock and -lock-timeout were added to workspace new in Terraform 0.12: %w", err)
			}
		}

		o.configureWorkspaceNew(&c)
	}

	args := []string{"workspace", "new", "-no-color"}

	if c.lockTimeout != "" && c.lockTimeout != defaultWorkspaceNewOptions.lockTimeout {
		// only pass if not default, so we don't need to worry about the 0.11 version check
		args = append(args, "-lock-timeout="+c.lockTimeout)
	}
	if !c.lock {
		// only pass if false, so we don't need to worry about the 0.11 version check
		args = append(args, "-lock="+strconv.FormatBool(c.lock))
	}
	if c.copyState != "" {
		args = append(args, "-state="+c.copyState)
	}

	args = append(args, workspace)

	cmd := tf.buildTerraformCmd(ctx, nil, args...)

	return cmd, nil
}


text:
package org.gradle.initialization;

import org.gradle.api.internal.initialization.AbstractClassLoaderScope;
import org.gradle.api.internal.initialization.ClassLoaderScope;
import org.gradle.api.internal.initialization.RootClassLoaderScope;
import org.gradle.api.internal.initialization.loadercache.ClassLoaderCache;

public class DefaultClassLoaderScopeRegistry implements ClassLoaderScopeRegistry {

    public static final String CORE_NAME = "core";
    public static final String CORE_AND_PLUGINS_NAME = "coreAndPlugins";

    private final AbstractClassLoaderScope coreAndPluginsScope;
    private final AbstractClassLoaderScope coreScope;

    public DefaultClassLoaderScopeRegistry(ClassLoaderRegistry loaderRegistry, ClassLoaderCache classLoaderCache, ClassLoaderScopeRegistryListener listener) {
        this.coreScope = new RootClassLoaderScope(CORE_NAME, loaderRegistry.getRuntimeClassLoader(), loaderRegistry.getGradleCoreApiClassLoader(), classLoaderCache, listener);
        this.coreAndPluginsScope = new RootClassLoaderScope(CORE_AND_PLUGINS_NAME, loaderRegistry.getPluginsClassLoader(), loaderRegistry.getGradleApiClassLoader(), classLoaderCache, listener);
        rootScopesCreated(listener);
    }

    @Override
    public ClassLoaderScope getCoreAndPluginsScope() {
        return coreAndPluginsScope;
    }

    @Override
    public ClassLoaderScope getCoreScope() {
        return coreScope;
    }

    private void rootScopesCreated(ClassLoaderScopeRegistryListener listener) {
        listener.rootScopeCreated(coreScope.getId());
        listener.rootScopeCreated(coreAndPluginsScope.getId());
    }
}


text:
require_relative '../../bundler_setup'
require 'log4r'
require 'VMwareWebService/MiqVim'

#
# Formatter to output log messages to the console.
#
class ConsoleFormatter < Log4r::Formatter
  def format(event)
    (event.data.kind_of?(String) ? event.data : event.data.inspect) + "\n"
  end
end
$vim_log = Log4r::Logger.new 'toplog'
Log4r::StderrOutputter.new('err_console', :level => Log4r::INFO, :formatter => ConsoleFormatter)
$vim_log.add 'err_console'

# $miq_wiredump = true

TARGET_VM = "testxav"
vim = MiqVim.new(SERVER, USERNAME, PASSWORD)

begin

  puts "vim.class: #{vim.class}"
  puts "#{vim.server} is #{(vim.isVirtualCenter? ? 'VC' : 'ESX')}"
  puts "API version: #{vim.apiVersion}"

  miqVm = vim.getVimVmByFilter("config.name" => TARGET_VM)

  puts "VM UUID: #{miqVm.vmh['config']['uuid']}"

  puts
  if miqVm.remoteDisplayVncEnabled?
    vmsAttr = miqVm.getRemoteDisplayVncAttributes
    puts "RemoteDisplay.vnc.enabled:  #{vmsAttr['enabled']}"
    puts "RemoteDisplay.vnc.key:      #{vmsAttr['key']}"
    puts "RemoteDisplay.vnc.password: #{vmsAttr['password']}"
    puts "RemoteDisplay.vnc.port:     #{vmsAttr['port']}"
  else
    puts "VM RemoveDisplay.vnc is not enabled"
  end

  miqVm.setRemoteDisplayVncAttributes('enabled' => "true", 'password' => PASSWORD, 'port' => 5901)
  miqVm.refresh

  puts
  if miqVm.remoteDisplayVncEnabled?
    vmsAttr = miqVm.getRemoteDisplayVncAttributes
    puts "RemoteDisplay.vnc.enabled:  #{vmsAttr['enabled']}"
    puts "RemoteDisplay.vnc.key:      #{vmsAttr['key']}"
    puts "RemoteDisplay.vnc.password: #{vmsAttr['password']}"
    puts "RemoteDisplay.vnc.port:     #{vmsAttr['port']}"
  else
    puts "VM RemoveDisplay.vnc vnc is not enabled"
  end

rescue => err
  puts err.to_s
  puts err.backtrace.join("\n")
ensure
  vim.disconnect
end


text:
'use strict';

const variadic = require('../helpers/variadic');

module.exports = function has(...args) {
  const properties = variadic(args);

  return properties.filter(key => Object.hasOwnProperty.call(this.items, key)).length
    === properties.length;
};


text:
namespace openworld {
  class MultiModel {
  public:
    virtual list<Variable> getVariables() = 0;
    virtual void setVariables(map<string, Distribution*>& vars) = 0;
    virtual map<string, Distribution*> evaluate(double tt) = 0;
  };

  template<class T>
  class MonteCarloModel : public MultiModel {
  protected:
    vector<SimpleModel*> runs;

  public:
    MonteCarloModel(unsigned runs) {
      for (unsigned ii = 0; ii < runs; ii++)
        this->runs.push_back((SimpleModel*) new T());
    }

    virtual list<Variable> getVariables() {
      return runs[0]->getVariables();
    }

    virtual void setVariables(map<string, Distribution*>& vars) {
      for (unsigned ii = 0; ii < runs.size(); ii++) {
        map<string, double> dvars;
        for (map<string, Distribution*>::iterator it = vars.begin(); it != vars.end(); it++)
          dvars[it->first] = it->second->random(ii + 1);

        runs[ii]->setVariables(dvars);
      }
    }

    virtual map<string, Distribution*> evaluate(double tt) {
      map<string, Distribution*> vars;

      for (unsigned ii = 0; ii < runs.size(); ii++) {
        map<string, double> dvars = runs[ii]->evaluateVariables(tt);
        if (vars.size() == 0) {
          for (map<string, double>::iterator it = dvars.begin(); it != dvars.end(); it++)
            vars[it->first] = new MonteCarloDistribution(vector<double>());
        }

        for (map<string, double>::iterator it = dvars.begin(); it != dvars.end(); it++)
          ((MonteCarloDistribution*) vars[it->first])->addSample(it->second);
      }

      return vars;
    }
  };

  class GaussianNoiseModel : public MultiModel, public IDeletable {
  protected:
    SimpleModel* model; // owns
    double fraction;

  public:
    GaussianNoiseModel(SimpleModel* model, double fraction) {
      this->model = model;
      this->fraction = fraction;
    }

    virtual ~GaussianNoiseModel() {
      delete model;
    }

    // don't report model, because I own it.
    //virtual list<IDeletable*> getContainedPointers() const {}

    virtual list<Variable> getVariables() {
      return model->getVariables();
    }

    virtual void setVariables(map<string, Distribution*>& vars) {
      map<string, double> dvars;
      for (map<string, Distribution*>::iterator it = vars.begin(); it != vars.end(); it++)
        dvars[it->first] = it->second->getMode();

      model->setVariables(dvars);
    }

    virtual map<string, Distribution*> evaluate(double tt) {
      map<string, Distribution*> vars;

      map<string, double> dvars = model->evaluateVariables(tt);
      for (map<string, double>::iterator it = dvars.begin(); it != dvars.end(); it++)
        vars[it->first] = tew_(GaussianDistribution(it->second, (fraction * it->second) * (fraction * it->second)));

      return vars;
    }
  };

  class DeltaModel : public MultiModel, public IDeletable {
  protected:
    SimpleModel* model; // owns

  public:
    DeltaModel(SimpleModel* model) {
      this->model = model;
    }

    virtual ~DeltaModel() {
      delete model;
    }

    // don't report model, because I own it.
    //virtual list<IDeletable*> getContainedPointers() const {}

    virtual list<Variable> getVariables() {
      return model->getVariables();
    }

    virtual void setVariables(map<string, Distribution*>& vars) {
      map<string, double> dvars;
      for (map<string, Distribution*>::iterator it = vars.begin(); it != vars.end(); it++)
        dvars[it->first] = it->second->getMode();

      model->setVariables(dvars);
    }

    virtual map<string, Distribution*> evaluate(double tt) {
      map<string, Distribution*> vars;

      map<string, double> dvars = model->evaluateVariables(tt);
      for (map<string, double>::iterator it = dvars.begin(); it != dvars.end(); it++)
        vars[it->first] = tew_(DeltaDistribution(it->second));

      return vars;
    }
  };
}

#endif


text:
<?php

namespace Crm\ClienteBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Crm\ClienteBundle\Entity\RangoCliente;
use Crm\ClienteBundle\Form\RangoClienteType;

/**
 * RangoCliente controller.
 *
 */
class RangoClienteController extends Controller
{

    /**
     * Lists all RangoCliente entities.
     *
     */
    public function indexAction()
    {
        return $this->render('ClienteBundle:RangoCliente:index.html.twig');
    }

    public function listadoAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('ClienteBundle:RangoCliente')->findAll();

        return $this->render('ClienteBundle:RangoCliente:listado.html.twig', array(
            'entities' => $entities,
        ));
    }
    /**
     * Creates a new RangoCliente entity.
     *
     */
    public function createAction(Request $request)
    {
        $entity = new RangoCliente();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();
            $this->get('session')->getFlashBag()->add(
                                'mensaje',
                                'Se ha creado el registro exitosamente'
                            );

            return $this->redirect($this->generateUrl('rangocliente_show', array('id' => $entity->getId())));
        }

        return $this->render('ClienteBundle:RangoCliente:dnew.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Creates a form to create a RangoCliente entity.
     *
     * @param RangoCliente $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(RangoCliente $entity)
    {
        $form = $this->createForm(new RangoClienteType(), $entity, array(
            'action' => $this->generateUrl('rangocliente_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new RangoCliente entity.
     *
     */
    public function newAction()
    {
        $entity = new RangoCliente();
        $form   = $this->createCreateForm($entity);

        return $this->render('ClienteBundle:RangoCliente:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Finds and displays a RangoCliente entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('ClienteBundle:RangoCliente')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find RangoCliente entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('ClienteBundle:RangoCliente:show.html.twig', array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing RangoCliente entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('ClienteBundle:RangoCliente')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find RangoCliente entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('ClienteBundle:RangoCliente:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
    * Creates a form to edit a RangoCliente entity.
    *
    * @param RangoCliente $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(RangoCliente $entity)
    {
        $form = $this->createForm(new RangoClienteType(), $entity, array(
            'action' => $this->generateUrl('rangocliente_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
    /**
     * Edits an existing RangoCliente entity.
     *
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('ClienteBundle:RangoCliente')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find RangoCliente entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();
            $this->get('session')->getFlashBag()->add(
                                'mensaje',
                                'Se ha editado el registro exitosamente'
                            );

            return $this->redirect($this->generateUrl('rangocliente_edit', array('id' => $id)));
        }

        return $this->render('ClienteBundle:RangoCliente:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }
    /**
     * Deletes a RangoCliente entity.
     *
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('ClienteBundle:RangoCliente')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find RangoCliente entity.');
            }

            $em->remove($entity);
            $em->flush();
            $this->get('session')->getFlashBag()->add(
                                'mensaje',
                                'Se ha eliminado el registro exitosamente'
                            );
        }

        return $this->redirect($this->generateUrl('rangocliente'));
    }

    /**
     * Creates a form to delete a RangoCliente entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('rangocliente_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Eliminar','attr' => array('class' => 'btn btn-danger')))
            ->getForm()
        ;
    }
}


text:
<?php

/**
 * Class CommandLine
 * Receives CLI input and decides which command must run
 */
class CommandLine
{
    const INSTALLED_VERSION = "0.5";
    const RELEASE_DATE = "2016-11-04";

    public static $debug = false;

    public static $colorTags = [
        "/<red>(.*)?<\/red>/",
        "/<yellow>(.*)?<\/yellow>/",
        "/<green>(.*)?<\/green>/",
    ];
    public static $colorReplacements = [
        "\033[31m$1\033[0m",
        "\033[33m$1\033[0m",
        "\033[32m$1\033[0m",
    ];

    /***
     * Parses the received command && decides which command must run
     * @param array $arguments
     */
    public static function init($arguments)
    {
        self::checkForUpdates();

        // check if ocomposer.json exists
        try {
            new OxideComposer();
        } catch (Exception $e) {
            if ($e->getCode() === 1) {
                self::setup();
                return;
            }
        }

        if (!isset($arguments[1])) {
            $arguments[1] = "help";
        }

        self::parseOptions($arguments);

        switch ($arguments[1]) {
            case "install":
                self::install($arguments[2]);
                break;
            case "update":
                self::update();
                break;
            case "about":
                self::about();
                break;
            case "validate":
                self::validate();
                break;
            case "full-update":
                self::fullUpdate();
                break;
            case "self-update":
                self::selfUpdate();
                break;
            default:
                self::help();
                break;
        }
    }

    /**
     * Checks for options in arguments list
     * @param array $arguments
     */
    public static function parseOptions(&$arguments)
    {
        $firstChar = substr($arguments[1], 0, 1);

        if ($firstChar == "-") {
            $option = substr($arguments[1], 1);

            switch ($option) {
                case "d":
                    self::$debug = true;
                    break;
            }
            // delete the option from arguments list
            unset($arguments[1]);
            $arguments = array_values($arguments);
        }
    }

    /**
     * Searches for OComposer updates
     */
    public static function checkForUpdates ()
    {
        $currentVersion = @file_get_contents("https://raw.githubusercontent.com/tetreum/ocomposer/master/currentVersion.txt");
	$currentVersion = trim($currentVersion);

        if (!empty($currentVersion) && $currentVersion != self::INSTALLED_VERSION) {
            self::display("<yellow>A newer version of OComposer is available, run 'ocomposer self-update' to update it</yellow>\n\n");
        }
    }

    /**
     * Runs validate command
     */
    public static function validate()
    {
        // OComposer construct already Validates them
        try {
            new OxideComposer();
        } catch (Exception $e) {
            self::handleError($e);
        }

        self::display("<green>They seem valid</green>");
    }

    /**
     * Runs install command
     * @param string $pluginId Ex: kits.668
     */
    public static function install($pluginId)
    {
        try {
            $composer = new OxideComposer();

            // convert http://oxidemod.org/plugins/stack-size-controller.1185/
            // to stack-size-controller.1185
            if (strpos($pluginId, "http://") !== false) {
                preg_match("/\/plugins\/(.*)?\//", $pluginId, $matches);

                if (isset($matches[1]) && !empty($matches[1])) {
                    $pluginId = $matches[1];
                }
            }

            $composer->install($pluginId);
        } catch (Exception $e) {
            self::handleError($e);
        }
    }

    /**
     * Handles the app Exceptions
     * @param Exception $e Exception to handle
     */
    public static function handleError($e)
    {
        if (self::$debug) {
            echo $e->__toString();
        } else {
            self::display("<red>" . $e->getMessage() . "</red>");
        }
        exit;
    }

    /**
     * Runs update command
     */
    public static function update()
    {
        try {
            $composer = new OxideComposer();
            $composer->update();
        } catch (Exception $e) {
            self::handleError($e);
        }
    }

    /**
     * Runs full update command
     */
    public static function fullUpdate()
    {
        try {
            $composer = new OxideComposer();

            self::display("Stopping server");
            echo self::runCommand("cd .. && ./rustserver stop", true);

            self::display("\n<yellow>Updating Oxide plugins</yellow>");
            $composer->update();

            self::display("<yellow>Updating Rust (will take a long time..)</yellow>");
            $composer->updateRust();

            self::display("\n<yellow>Updating Oxide (may take a while)</yellow>");
            $composer->updateOxide();

            self::display("<yellow>Starting server</yellow>");
            echo self::runCommand("cd .. && ./rustserver start", true);
        } catch (Exception $e) {
            self::handleError($e);
        }
    }

    /**
     * Updates OComposer to its latest version
     */
    public static function selfUpdate ()
    {
        self::display("\n<yellow>Updating OComposer</yellow>");
        self::runCommand("curl -s https://raw.githubusercontent.com/tetreum/ocomposer/master/compiled/installer | bash");

        $dateFormat = "Y-m-d H:i";
        $fileDate = date($dateFormat, filemtime("/usr/bin/ocomposer"));

        if ($fileDate != date($dateFormat)) {
            self::display("<red>You must be sudoer to run this command</red>");
            exit;
        }

        self::display("<green>¡Successfully updated!</green>");
    }

    /**
     * Runs about command
     */
    public static function about()
    {
        self::display("<yellow>Ocomposer is an oxide plugin manager for your servers.</yellow>\n<yellow>See https://github.com/tetreum/ocomposer for more information.</yellow>");
    }

    /**
     * Colors & prints the given text
     * @param string $text
     */
    public static function display($text, $newline = true)
    {
        Utils::p(preg_replace(self::$colorTags, self::$colorReplacements, $text), $newline);
    }

    public static function setup()
    {
        self::display("Config file (ocomposer.json) not found, starting setup....");

        $paths = self::runCommand("find / -name \"oxide\" -type d");
        if (empty($paths) || sizeof($paths) == 0) {
            self::display("<red>Unable to find any /oxide/ folder in your server.</red>");
            return;
        }

        $setupData = new stdClass();
        $setupData->plugins = new stdClass();
        $setupData->login = new stdClass();

        self::display("<yellow>Ocomposer needs an OxideMod.org account to download the plugins, your login details will be saved in ocomposer.json.</yellow>");

        self::prompt("Username: ", function ($response) use (&$setupData) {
            $setupData->login->user = $response;
        });

        self::prompt("Password: ", function ($response) use (&$setupData) {
            $setupData->login->password = $response;
        });

        self::display("<yellow>Select your server /serverfiles/ folder:</yellow>");
        $plainList = "";

        foreach ($paths as $k => $v) {
            $plainList .= "[$k] - $v\n";
        }
        self::display($plainList);

        self::prompt("Input the number: ", function ($response) use (&$setupData, $paths) {
            $number = (int)$response;

            if ($number > sizeof($paths) || $number < 0) {
                $number = 0;
            }

            $setupData->oxideFolder = $paths[$number] . "/";
        });

        $saved = file_put_contents("ocomposer.json", json_encode($setupData, JSON_PRETTY_PRINT));

        if ($saved === false) {
            self::display("<red>Could not save ocomposer.json</red>");
        } else {
            self::display("<green>Config saved</green>");
        }
    }

    /**
     * Prompts a message requesting user input
     * @param string $message
     * @param $callback
     * @param boolean $newline
     */
    public static function prompt($message, $callback, $newline = false)
    {
        self::display($message, $newline);

        $handle = fopen("php://stdin", "r");
        $line = fgets($handle);

        $callback(trim($line));

        fclose($handle);
    }

    /**
     * Runs a terminal command
     * @param string $command
     * @param bool $stringOutput force string output
     * @return mixed
     */
    public static function runCommand($command, $stringOutput = false)
    {
        exec($command, $out);

        if ($stringOutput && is_array($out)) {
            $out = implode("\n", $out);
        }

        return $out;
    }

    /**
     * Runs help command
     */
    public static function help()
    {
        self::display("
  ____       _     _       _____
 / __ \     (_)   | |     / ____|
| |  | |_  ___  __| | ___| |     ___  _ __ ___  _ __   ___  ___  ___ _ __
| |  | \ \/ / |/ _` |/ _ \ |    / _ \| '_ ` _ \| '_ \ / _ \/ __|/ _ \ '__|
| |__| |>  <| | (_| |  __/ |___| (_) | | | | | | |_) | (_) \__ \  __/ |
 \____//_/\_\_|\__,_|\___|\_____\___/|_| |_| |_| .__/ \___/|___/\___|_|
 					       | |
 					       |_|
<green>OxideComposer</green> version <yellow>" . self::INSTALLED_VERSION . "</yellow> " . self::RELEASE_DATE . "

<yellow>Usage:</yellow>
	[options] command [arguments]

<yellow>Options:</yellow>
	<green>-d</green>		Prints Exception traces

<yellow>Available commands:</yellow>
	<green>about</green>		Short information about OxideComposer
	<green>install</green>		Installs the plugin set as argument1 Ex: 'ocomposer.phar install kits.668'
	<green>update</green>		Updates your plugins to the latest version according to ocomposer.json & installed.json
	<green>full-update</green>	Updates Rust server (LGSM), Oxide & it's plugins
	<green>self-update</green>	Updates OComposer to it's latest version
	<green>validate</green>        Validates ocomposer.json & installed.json
		");
    }
}


text:
from infotv.policy import BasePolicy

class TraconPolicy(BasePolicy):
    def get_event_slug(self, request, slug):
        return slug

    def can_edit_slides(self, request):
        return request.user.is_staff

    def can_post_datum(self, request):
        return request.user.is_staff


text:
{% extends "base/content.html" %}
{% set prevmode="game" %}
{% block scripts %}

{% endblock %}
{% block  content %}

                {% for game in games[:8] %}

{{ game.name }}

{{ game.short_description }}

                {% endfor %}

            {% for game in games[:8] %}

{{ game.name }}

            {% endfor %}

Games

            {% set itemsperrow=4 %}
            {% set prevmode="game" %}
            {% for item in games %}
                {% include"parts/previewbox.html" %}
                {% if (loop.index % itemsperrow) is equalto 0 and not loop.first %}

{% endif %}

            {% endfor %}

    {% if not user %}

{{ site_name }} is a community modding site

There have been a few poor modding sites in the past. {{ site_name }} aims to be different. We
                fix the
                problems with the old and make the new work great. Most of all,
                {{ site_name }} brings the community back into
                the loop and puts the power in the modder's hands.

Great for Players

Get email updates

Easily keep track of your favorite mods. Don't bother
                        checking the forums every 5 minutes, just sit back and we'll
                        email you when the time comes.

Easy to use search

Searching for mods on {{ site_name }} is painless and easy. You'll find the mod you're
                        looking for on the first try, or your money back.

Full version history

Got a nostalgic itch to scratch? {{ site_name }} keeps around old versions of mods and
                        includes the last version of your Game they worked with.

Find new and cool mods

We don't need to tell you about the popular mods you already know about. Instead, we feature
                        new and interesting mods to give you something new.

Great for Modders

Get detailed stats

We'll give you a history of downloads and we'll give it to you with nice pretty graphs. You
                        can also export the raw data if you want to visualize it yourself.

Update in moments

No nonsense updates. Give us a version number, a zip file, and optionally a changelog, and
                        your followers get an email with the latest version.

Exposure where it's due

Got a popular mod? It'll be the first in the search results. Got a cool brand-new mod? We'll
                        make sure you get the exposure you need.

Open source

Wouldn't it be great if you could help make your modding site even better? You
                        can! {{ site_name }} is open source, come check out the code.

Register

                    <form class="form-horizontal" role="form" action="/register" method="POST">

                            Email

                            <input type="email" class="form-control" id="email" placeholder="Email" name="email"
                                   value="">

                            Username

                            <input type="text" class="form-control" id="username" placeholder="Username"
                                   name="username" value="">

                            Password

                            <input type="password" class="form-control" id="password" name="password"
                                   placeholder="Password">

                                <input type="password" class="form-control" id="password" name="repeatPassword"
                                       placeholder="Repeat password">

                            <input type="submit" value="Register" class="btn btn-register btn-block btn-lg">

                    </form>

Ready to make an account? You'll be able to:

Upload new mods

Keep track of your favorite mods

Tell your friends "I have a {{ site_name }} account!"

Replace the "Log In" link with a "Log Out" link

And not much more!

                {% for provider in oauth_providers %}
                    {% set provider_icon = oauth_providers[provider].icon %}
                    {% set provider_full_name = oauth_providers[provider].full_name %}

                    <form action="/login-oauth" method="POST">
                        <input type="hidden" name="provider" value="{{ provider }}">
                        <button type="submit" class="btn btn-register btn-lg">
                             Register using {{ provider_full_name }}
                        </button>
                    </form>

                {% endfor %}

    {% endif %}

{% endblock %}


text:
<?php

namespace Badgeville\Api\Cairo\Sites;

use Badgeville\Api\Cairo\ResourceAbstract;

/**
 * Description of Players
 *
 * @author Joey Rivera <joey1.rivera@gmail.com>
 */
class Behaviors extends ResourceAbstract
{
    protected $resourceName = 'behaviors';

    protected $queryable = [
        'id',
        'name',
        'verb'
    ];

    public function getResourceName()
    {
        return $this->resourceName;
    }
}


text:
<?php
namespace backend\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;

/**
 * Site controller
 */
class SiteController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'index', 'image-upload'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'image-upload' => [
                'class' => 'vova07\imperavi\actions\UploadAction',
                'url' => Yii::$app->params['frontendUrl'] . '/uploads/', // Directory URL address, where files are stored.
                'path' => '@frontend/web/uploads', // Or absolute path to directory where files are stored.
                'uploadOnlyImage' => false, // For not image-only uploading.
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex()
    {
        return $this->render('index');
    }

    /**
     * Login action.
     *
     * @return string
     */
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        } else {
            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Logout action.
     *
     * @return string
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }
}


text:
package com.gigamole.infinitecycleviewpager;

import android.database.DataSetObserver;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by GIGAMOLE on 7/27/16.
 */

// PagerAdapter that wrap original ViewPager adapter with infinite scroll feature.
// There is VIRTUAL_ITEM_COUNT which equals to 10_000_000.
// At start, ViewPager set position to half of virtual and find nearest zero position.
class InfiniteCyclePagerAdapter extends PagerAdapter {

    private final static int VIRTUAL_ITEM_COUNT = 10_000_000;

    private final PagerAdapter mPagerAdapter;
    private OnNotifyDataSetChangedListener mOnNotifyDataSetChangedListener;

    public InfiniteCyclePagerAdapter(final PagerAdapter pagerAdapter) {
        mPagerAdapter = pagerAdapter;
    }

    public PagerAdapter getPagerAdapter() {
        return mPagerAdapter;
    }

    public void setOnNotifyDataSetChangedListener(final OnNotifyDataSetChangedListener onNotifyDataSetChangedListener) {
        mOnNotifyDataSetChangedListener = onNotifyDataSetChangedListener;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        mPagerAdapter.destroyItem(container, getVirtualPosition(position), object);
    }

    @Override
    public void finishUpdate(ViewGroup container) {
        mPagerAdapter.finishUpdate(container);
    }

    @Override
    public int getCount() {
        if (mPagerAdapter.getCount() == 0) return 0;
        return VIRTUAL_ITEM_COUNT;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mPagerAdapter.getPageTitle(getVirtualPosition(position));
    }

    @Override
    public float getPageWidth(int position) {
        return mPagerAdapter.getPageWidth(getVirtualPosition(position));
    }

    @Override
    public boolean isViewFromObject(View view, Object o) {
        return mPagerAdapter.isViewFromObject(view, o);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        return mPagerAdapter.instantiateItem(container, getVirtualPosition(position));
    }

    @Override
    public Parcelable saveState() {
        return mPagerAdapter.saveState();
    }

    @Override
    public void restoreState(Parcelable state, ClassLoader loader) {
        mPagerAdapter.restoreState(state, loader);
    }

    @Override
    public void startUpdate(ViewGroup container) {
        mPagerAdapter.startUpdate(container);
    }

    @Override
    public void unregisterDataSetObserver(DataSetObserver observer) {
        mPagerAdapter.unregisterDataSetObserver(observer);
    }

    @Override
    public void registerDataSetObserver(DataSetObserver observer) {
        mPagerAdapter.registerDataSetObserver(observer);
    }

    @Override
    public void notifyDataSetChanged() {
        mPagerAdapter.notifyDataSetChanged();
        // Callback for invalidating transformer position
        if (mOnNotifyDataSetChangedListener != null) mOnNotifyDataSetChangedListener.onChanged();
    }

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        mPagerAdapter.setPrimaryItem(container, position, object);
    }

    @Override
    public int getItemPosition(Object object) {
        return mPagerAdapter.getItemPosition(object);
    }

    // Main feature of this adapter which return virtual position
    // relative to virtual count and original count
    protected int getVirtualPosition(final int realPosition) {
        return realPosition % mPagerAdapter.getCount();
    }

    protected interface OnNotifyDataSetChangedListener {
        void onChanged();
    }
}


text:
#include "configuration.h"
#include "../hw_string.h"
#include "../khash.h"
#include "ini.h"

KHASH_MAP_INIT_STR(route_hashes, char*)

int configuration_handler(void* user, const char* section, const char* name, const char* value)
{
    configuration* config = (configuration*)user;

#define MATCH(s, n) strcmp(section, s) == 0 && strcmp(name, n) == 0
    if (MATCH("http", "listen_address"))
    {
        config->http_listen_address = dupstr(value);
    }
    else if (MATCH("http", "listen_port"))
    {
        config->http_listen_port = atoi(value);
    }
    else
    {
        return 0;  /* unknown section/name, error */
    }
    return 1;
}

configuration* load_configuration(const char* filename)
{
    configuration* config = malloc(sizeof(configuration));
    if (ini_parse(filename, configuration_handler, config) < 0)
    {
        printf("Can't load configuration\n");
        return NULL;
    }
    return config;
}


text:
<?php

namespace Drupal\Tests\comment\Kernel\Views;

use Drupal\comment\Entity\Comment;
use Drupal\comment\Tests\CommentTestTrait;
use Drupal\Core\Render\RenderContext;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\KernelTests\KernelTestBase;
use Drupal\node\Entity\NodeType;
use Drupal\Tests\node\Traits\NodeCreationTrait;
use Drupal\Tests\user\Traits\UserCreationTrait;
use Drupal\views\Tests\ViewResultAssertionTrait;
use Drupal\views\Tests\ViewTestData;
use Drupal\views\Views;

/**
 * Tests the comment field name field.
 *
 * @group comment
 */
class CommentFieldNameTest extends KernelTestBase {

  use CommentTestTrait;
  use NodeCreationTrait;
  use UserCreationTrait;
  use ViewResultAssertionTrait;

  /**
   * {@inheritdoc}
   */
  protected static $modules = [
    'comment',
    'comment_test_views',
    'field',
    'filter',
    'node',
    'system',
    'text',
    'user',
    'views',
  ];

  /**
   * Views used by this test.
   *
   * @var array
   */
  public static $testViews = ['test_comment_field_name'];

  /**
   * Tests comment field name.
   */
  public function testCommentFieldName() {
    $renderer = $this->container->get('renderer');

    $this->installEntitySchema('user');
    $this->installEntitySchema('node');
    $this->installEntitySchema('comment');
    $this->installSchema('system', ['sequences']);
    $this->installSchema('comment', ['comment_entity_statistics']);
    $this->installConfig(['filter']);

    NodeType::create(['type' => 'page'])->save();
    FieldStorageConfig::create([
      'type' => 'text_long',
      'entity_type' => 'comment',
      'field_name' => 'comment_body',
    ])->save();
    $this->addDefaultCommentField('node', 'page', 'comment');
    $this->addDefaultCommentField('node', 'page', 'comment_custom');

    ViewTestData::createTestViews(static::class, ['comment_test_views']);

    $node = $this->createNode();
    $comment = Comment::create([
      'entity_id' => $node->id(),
      'entity_type' => 'node',
      'field_name' => 'comment',
    ]);
    $comment->save();
    $comment2 = Comment::create([
      'entity_id' => $node->id(),
      'entity_type' => 'node',
      'field_name' => 'comment_custom',
    ]);
    $comment2->save();

    $view = Views::getView('test_comment_field_name');
    $view->preview();

    $expected_result = [
      [
        'cid' => $comment->id(),
        'field_name' => $comment->getFieldName(),
      ],
      [
        'cid' => $comment2->id(),
        'field_name' => $comment2->getFieldName(),
      ],
    ];
    $column_map = [
      'cid' => 'cid',
      'comment_field_data_field_name' => 'field_name',
    ];
    $this->assertIdenticalResultset($view, $expected_result, $column_map);

    // Test that data rendered correctly.
    $expected_output = $renderer->executeInRenderContext(new RenderContext(), function () use ($view) {
      return $view->field['field_name']->advancedRender($view->result[0]);
    });
    $this->assertEquals($expected_output, $comment->getFieldName());
    $expected_output = $renderer->executeInRenderContext(new RenderContext(), function () use ($view) {
      return $view->field['field_name']->advancedRender($view->result[1]);
    });
    $this->assertEquals($expected_output, $comment2->getFieldName());
  }

}


text:
namespace nQCircuit
{
	enum struct QBit
	{
		EMPTY,
		NOT,
		CONTROLLED_NOT,
		WHITE_CONTROLLED_NOT
		//,OR	//this is an example to help you understand how to use IQBit correctly
	};
}

#endif


text:
/*
 * Author: Raul Peralta Lozada
 * e-mail: raulpl25@gmail.com
 * date: 24/03/2015
*/

#include "navigation_services/battery_inspector.h"
#include "std_msgs/Float64.h"

using namespace std;

BatteryInspector::BatteryInspector()
{

}

bool BatteryInspector::get_batterry_voltage(json_msgs::JsonSrv::Request& req, json_msgs::JsonSrv::Response& res)
{
    std_msgs::Float64ConstPtr b_p = ros::topic::waitForMessage<std_msgs::Float64>("/RosAria/battery_voltage");
    Json::FastWriter writer;
    Json::Value response;
    response["battery_voltage"] = b_p->data;
	res.json = writer.write(response);
    return true;
}


text:
namespace windy {
	namespace entity {
		class texture;
	}

	namespace content {
			class sprite : public item {
			public:
				sprite(const std::string& name,
					   const std::string& uuid,
					   const std::string& path);
				std::string path();
				std::shared_ptr<instance> build();
				void remove(std::shared_ptr<class instance> instance);

			private:
				std::string _path;
				std::shared_ptr<entity::texture> _texture;
			};
	}
}

#endif


text:
id: 587d78aa367417b2b2512aec
title: Define the Head and Body of an HTML Document
challengeType: 0
videoUrl: 'https://scrimba.com/p/pVMPUv/cra9bfP'
---

## Description

You can add another level of organization in your HTML document within the html tags with the head and body elements. Any markup with information about your page would go into the head tag. Then any markup with the content of the page (what displays for a user) would go into the body tag.
Metadata elements, such as link, meta, title, and style, typically go inside the head element.
Here's an example of a page's layout:

<!DOCTYPE html>
<html>
  <head>
    <!-- metadata elements -->
  </head>
  <body>
    <!-- page contents -->
  </body>
</html>

## Instructions

Edit the markup so there's a head and a body. The head element should only include the title, and the body element should only include the h1 and p.

## Tests

```yml
tests:
  - text: There should be only one <code>head</code> element on the page.
    testString: assert($('head').length == 1, 'There should be only one <code>head</code> element on the page.');
  - text: There should be only one <code>body</code> element on the page.
    testString: assert($('body').length == 1, 'There should be only one <code>body</code> element on the page.');
  - text: The <code>head</code> element should be a child of the <code>html</code> element.
    testString: assert($('html').children('head').length == 1, 'The <code>head</code> element should be a child of the <code>html</code> element.');
  - text: The <code>body</code> element should be a child of the <code>html</code> element.
    testString: assert($('html').children('body').length == 1, 'The <code>body</code> element should be a child of the <code>html</code> element.');
  - text: The <code>head</code> element should wrap around the <code>title</code> element.
    testString: assert(code.match(/<head>\s*?<title>\s*?.*?\s*?<\/title>\s*?<\/head>/gi), 'The <code>head</code> element should wrap around the <code>title</code> element.');
  - text: The <code>body</code> element should wrap around both the <code>h1</code> and <code>p</code> elements.
    testString: assert($('body').children('h1').length == 1 && $('body').children('p').length == 1, 'The <code>body</code> element should wrap around both the <code>h1</code> and <code>p</code> elements.');

```

## Challenge Seed

```html
<!DOCTYPE html>
<html>
  <title>The best page ever</title>

  <h1>The best page ever</h1>
  <p>Cat ipsum dolor sit amet, jump launch to pounce upon little yarn mouse, bare fangs at toy run hide in litter box until treats are fed. Go into a room to decide you didn't want to be in there anyway. I like big cats and i can not lie kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff. Meow i could pee on this if i had the energy for slap owner's face at 5am until human fills food dish yet scamper. Knock dish off table head butt cant eat out of my own dish scratch the furniture. Make meme, make cute face. Sleep in the bathroom sink chase laser but pee in the shoe. Paw at your fat belly licks your face and eat grass, throw it back up kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.</p>

</html>
```

## Solution

```js
// solution required
```


text:
<?xml version="1.0" encoding="UTF-8"?>
<GetHostedZoneResponse xmlns="https://route53.amazonaws.com/doc/2012-02-29/">
   <HostedZone>
      <Id>/hostedzone/47234</Id>
      <Name>t.com</Name>
      <CallerReference>some unique reference</CallerReference>
      <Config>
         <Comment>some comment</Comment>
      </Config>
      <ResourceRecordSetCount>0</ResourceRecordSetCount>
   </HostedZone>
   <DelegationSet>
      <NameServers>
         <NameServer>ns1.example.com</NameServer>
         <NameServer>ns2.example.com</NameServer>
         <NameServer>ns3.example.com</NameServer>
         <NameServer>ns4.example.com</NameServer>
      </NameServers>
   </DelegationSet>
</GetHostedZoneResponse>


text:
<form id="search" action="/search/" method="GET">

search craigslist

    <input type="hidden" name="sort" value="rel">
    <input id="query" name="query" data-suggest="search" autocorrect="off" autocapitalize="off" placeholder="search">

    <select id="catAbb" name="catAbb">
        <option value="ccc">community</option>
        <option value="eee">events</option>
        <option value="ggg">gigs</option>
        <option value="hhh">housing</option>
        <option value="jjj">jobs</option>
        <option value="ppp">personals</option>
        <option value="res">resumes</option>
        <option value="sss" selected="selected">for sale</option>
        <option value="bbb">services</option>
    </select>
    <input id="go" type="submit" value=">">
</form>


text:
/*global jQuery, window, document, console, google, MarkerClusterer */

var Codeweek = window.Codeweek || {};

(function ($, Codeweek) {

	'use strict';

	var datetime_handler = function () {
		var start_date = $('#id_datepicker_start'),
			end_date = $('#id_datepicker_end'),
			get_date_range = function (input) {
				var value = input.val() ? input.val() : false,
					parsed_value = [];

				if (value) {
					parsed_value = /\d{4}-\d{2}-\d{2}/.exec(value);
				}
				if (parsed_value && parsed_value.length > 0) {
					return parsed_value[0];
				}
				return false;
			};

        start_date.datetimepicker({
            format: "Y-m-d H:i",
            formatDate: "Y-m-d",
            formatTime: "H:i",
            minDate: "2015-01-01",
            closeOnDateSelect: true,
            dayOfWeekStart:1,
            onShow: function () {
                this.setOptions({
                    maxDate: get_date_range(end_date)
                });
            }
        });
        end_date.datetimepicker({
            format: "Y-m-d H:i",
            formatDate: "Y-m-d",
            formatTime: "H:i",
            minDate: 0,
            closeOnDateSelect: true,
            dayOfWeekStart:1,
            onShow: function () {
                this.setOptions({
                    minDate: get_date_range(start_date),
                    value: start_date.val()
                });
            }
        });
    },

		placeSearch,
		autocomplete,
		map,
		marker,
		geocoder,
		address;

	function createMap(latLng, zoomVal) {
		var mapOptions = {
			scrollwheel: false,
			zoom: zoomVal,
			center: latLng
		};
		map = new google.maps.Map(document.getElementById('view-event-map'), mapOptions);
	}

	function updateCountrySelection(country) {
		var choice = document.getElementById('id_country');
		selectItemByValue(choice, country);
	}

	function updateAddress(new_latLng) {
		geocoder = new google.maps.Geocoder();
		geocoder.geocode({'latLng': new_latLng}, function (results, status) {
			if ( status === google.maps.GeocoderStatus.OK ||
				 ( status === google.maps.GeocoderStatus.ZERO_RESULTS && results.length > 0 ) ) {
				document.getElementById("autocomplete").value = results[0].formatted_address;
				// the last item in the geocoder for latLng results array is the country
				var country = results.slice(-1)[0].address_components.slice(-1)[0].short_name;
				var frenchColonies = ['MQ', 'GF', 'GP'] // Martinique, French Guiana, Guadeloupe
				if (frenchColonies.indexOf(country) >= 0) {
					country = 'FR';
				}
				updateCountrySelection(country);
			}
		});
	}

	function updateLatLng(lat, lng) {
		document.getElementById("id_geoposition_0").value = lat;
		document.getElementById("id_geoposition_1").value = lng;
	}

	function createMarker(markerLatLng, viewport) {
		if (!marker) {
			marker = new google.maps.Marker({
				position: markerLatLng,
				animation: google.maps.Animation.DROP,
				title: "Event location",
				draggable: true
			});
		} else {
			marker.setPosition(markerLatLng);
		}

		if (!map) {
			createMap(markerLatLng, 15);
		}

		marker.setMap(map);

		if (viewport) {
			map.fitBounds(viewport);
		}

		google.maps.event.addListener(marker, 'dragend', function (event) {
			updateLatLng(this.getPosition().lat(), this.getPosition().lng());
			updateAddress(marker.getPosition());
		});
	}

	function selectItemByValue(elmnt, value) {
		var i;
		for (i = 0; i < elmnt.options.length; i = i + 1) {
			if (elmnt.options[i].value === value) {
				elmnt.selectedIndex = i;
			}
		}
	}

	function listenForPastedAddress() {
		var address_field = document.getElementById('autocomplete');
		address_field.addEventListener('focusout',function () {
			var address_value = address_field.value;
			if (address_value) {
				getAddress(address_value);
			}
		}, true);
	}

	function fillInAddress() {
		// geoLatLng contains the Google Maps geocoded latitude, longitude
		var geometry = autocomplete.getPlace().geometry;
		if (!geometry) return;
		var geoLatLng = geometry.location;

		createMarker(geoLatLng, geometry.viewport);
		updateLatLng(geoLatLng.lat(), geoLatLng.lng());
		updateAddress(geoLatLng);
	}

	function auto_complete() {
		var autocompleteField = document.getElementById('autocomplete');

		autocomplete = new google.maps.places.Autocomplete(
			autocompleteField,
			{
				types: ['geocode']
			}
		);

		google.maps.event.addListener(autocomplete, 'place_changed', function () {
			fillInAddress();
		});

		$(document).on('keydown', '#autocomplete', function(event) {
			if (event.keyCode === 13) {
				event.preventDefault();
				return false;
			}
		});
	}

	function getAddress(address) {
		if (!address) return;

		geocoder = new google.maps.Geocoder();

		geocoder.geocode({'address': address}, function (results, status) {
			if (status === google.maps.GeocoderStatus.OK) {
				var updated_location = results[0].geometry.location;
				createMarker(updated_location, results[0].geometry.viewport);
				updateLatLng(updated_location.lat(), updated_location.lng());
				updateAddress(updated_location);
			}
		});
	}

	function initialize(address) {
		var initialCenter = new google.maps.LatLng(46.0608144, 14.497165600000017);
		createMap(initialCenter, 4);
		auto_complete();
		getAddress(address);
		listenForPastedAddress();

		google.maps.event.addListener(map, 'click', function (event) {
			var position = event.latLng;
			if (!position) return;

			createMarker(position);
			updateLatLng(position.lat(), position.lng());
			updateAddress(position);
		});
	}

	var add = function (address) {

		$(function () {
			google.maps.event.addDomListener(window, 'load', function () {
				address = document.getElementById('autocomplete').value;
				initialize(address);
			});

			datetime_handler();
		});

	};

	Codeweek.Event = {};
	Codeweek.Event.add = add;

}(jQuery, Codeweek));


text:
/*
 * Copyright (C) 1998, 1999, 2000, 2001, 2002
 *
 * Arjuna Technologies Ltd.
 * Newcastle upon Tyne,
 * Tyne and Wear,
 * UK.
 *
 * $Id: javaidl_1_4.java 2342 2006-03-30 13:06:17Z  $
 */
package com.arjuna.orbportability.internal.orbspecific.javaidl.orb.implementations;

import com.arjuna.orbportability.internal.orbspecific.orb.implementations.ORBBase;

public class javaidl_1_4 extends ORBBase
{
    public javaidl_1_4()
    {
	System.setProperty("org.omg.CORBA.ORBClass", "com.sun.corba.se.internal.Interceptors.PIORB");
	System.setProperty("org.omg.CORBA.ORBSingletonClass", "com.sun.corba.se.internal.corba.ORBSingleton");

    // it seems nothing ever reads this, so we should be able to get away without it
	// opPropertyManager.getPropertyManager().setProperty("com.arjuna.orbportability.internal.defaultBindMechanism", Services.bindString(Services.CONFIGURATION_FILE));
    }
}


text:
/*//= require _sassline*/
//= require main
//= require card


text:
package com.gs.fw.common.mithra.test.util.tinyproxy;

/**
 * Wrapper for protocol exceptions thrown in the proxy.
 */
public class PspRuntimeException extends RuntimeException
{
    public PspRuntimeException()
    {
    }

    /**
     * Create the exception.
     */
    public PspRuntimeException(String message)
    {
        super(message);
    }

    /**
     * Create the exception.
     */
    public PspRuntimeException(String message, Throwable rootCause)
    {
        super(message, rootCause);
    }
}


text:
class CSimpleString
{
public:
    CSimpleString();
    virtual ~CSimpleString();

    bool AllocateString( DWORD dwNumChars );
    bool ReAllocateString( DWORD dwNumChars );
    void FreeString();

    TCHAR* GetString() const;

    DWORD GetBufSizeInBytes() const;
    DWORD GetBufSizeInChars() const;

    bool Prepend( const TCHAR* strString );
    bool Append( const TCHAR* strString );

private:
    TCHAR* m_String;
    DWORD m_dwLength;
};


text:
namespace FormatNumber
{
    using System;
    using System.Linq;

    /*•	Write a program that reads a number and prints it as a decimal number, hexadecimal number,
             * percentage and in scientific notation.
              •	Format the output aligned right in 15 symbols.*/

    class FormatNumber
    {
        static void Main()
        {
            int number = int.Parse(Console.ReadLine());
            string decimalNumber = number.ToString("D15");
            string hexadecNumber = number.ToString("X");
            string percentage = number.ToString("P");
            string scientificNotation = number.ToString("E");
            Console.WriteLine("{0, 15}", decimalNumber);
            Console.WriteLine("{0, 15}", hexadecNumber);
            Console.WriteLine("{0, 15}", percentage);
            Console.WriteLine("{0, 15}", scientificNotation);

        }
    }
}


text:
<?php
error_reporting(0);
//require user classes for user and item
require_once("classes/terrans.class.php");
require_once("classes/zerg.class.php");
require_once("classes/protoss.class.php");
require_once("classes/item.class.php");
require_once("classes/challenge.class.php");

//session key
$seesionKey = 'user_session';

// create slug string
function create_slug($string){
   $slug = preg_replace('/[^A-Za-z0-9-]+/', '_', $string);
   return strtolower($slug);
}

function call_user_class($user)
{
	//Call user class
	if($user=='terrans')
		$userClass = new terrans();
	else if($user=='zerg')
		$userClass = new zerg();
	else if($user=='protoss')
		$userClass = new protoss();
	return $userClass;
}
function get_user_values($user)
{
	//get user values
	$userClass = call_user_class($user);
	$getUserValues = $userClass->get_values();
	return $getUserValues[$user];
}

//get item based on challenge property
function get_user_item($challenge)
{
	$userItems = new item();
	$propertyArray = array('health','stamina','speed','strength'); //default user property
	foreach($propertyArray as $value){
		if(array_key_exists($value,$challenge)){ // get challenge property type
			return $userItems->get_items_list($value); // get item based on challenge property
		}
	}
}

//Returns remain pc users array with
function pc_users($user,$challenge)
{
	//get random item
	$userArray = array('terrans','zerg','protoss'); //default users
	foreach($userArray as $value){
		if($value!=$user){
			$remainUser[] = array("slug_name"=>create_slug($value),"name"=>$value,"user"=>get_user_values($value),"point"=>50,"challenge"=>$challenge,"item"=>array(get_user_item($challenge)));
		}
	}
	return $remainUser;
}

//Set session values by key
function set_session($key,$value)
{
	$_SESSION[$key] = $value;
}
//Get session values by key
function get_session($key)
{
	return @$_SESSION[$key];
}

//get challenge property name
function get_challenge_property($property)
{
	$propertyArray = array('health','stamina','speed','strength'); //default user property
	foreach($propertyArray as $value){
		if(array_key_exists($value,$property)){ // get challenge property type
			$propertyValue['property'] = $value;
			$propertyValue['value'] = $property[$value];
			return $propertyValue;
			break;
		}
	}
}

//get user property name
function get_user_property($s,$property)
{
		if(array_key_exists($s,$property)){ // get user property type
			$propertyValue['property'] = $s;
			$propertyValue['value'] = $property[$s];
			return $propertyValue;
			break;
		}
}
//Remove users temp challenge values with temp challenge value and user result
function remove_users_temp_values($i)
{
	global $seesionKey;
	if($i==0){
		//unset($_SESSION[$seesionKey]);

		//unset($_SESSION[$seesionKey][1]['user']['temp_challenge_value']);
		//unset($_SESSION[$seesionKey][2]);
		if(@$_SESSION[$seesionKey][1]!=NULL){
			$_SESSION[$seesionKey][1]['user']['temp_challenge_value'] = 0;
			$_SESSION[$seesionKey][1]['user']['result'] = '';
		}

		if(@$_SESSION[$seesionKey][2]!=NULL){
			$_SESSION[$seesionKey][2]['user']['temp_challenge_value'] = 0;
			$_SESSION[$seesionKey][2]['user']['result'] = '';
		}
	}
	else if($i==1){
		//unset($_SESSION[$seesionKey][2]);

		if(@$_SESSION[$seesionKey][2]!=NULL){
			$_SESSION[$seesionKey][2]['user']['temp_challenge_value'] = 0;
			$_SESSION[$seesionKey][2]['user']['result'] = '';
		}
	}
}

//Set user position based on challenge property
function set_users_position($challenge_property,$i)
{
	global $seesionKey;
	//calcuate user property
	$j=0;
	while($j<sizeof(@$_SESSION[$seesionKey]))
	{
		if($i==$j){
			$_SESSION[$seesionKey][$i]['user']['position'] = 1;
			//if user win add new item
			winTool($i);
		}
		else{
			$remain_user[] = $j;
		}
		$j++;
	}

	if(@$_SESSION[$seesionKey][$remain_user[0]]!=NULL){

		if(@$_SESSION[$seesionKey][$remain_user[0]]['user'][@$challenge_property]>@$_SESSION[$seesionKey][$remain_user[1]]['user'][@$challenge_property]){
				$_SESSION[$seesionKey][$remain_user[0]]['user']['position'] = 2;
				//unset($_SESSION[$seesionKey][$remain_user[0]]['item'][end($_SESSION[$seesionKey][$remain_user[0]]['item'])]);
		}
		else{
			$_SESSION[$seesionKey][$remain_user[0]]['user']['position'] = 3;
		}
	}

	if(@$_SESSION[$seesionKey][$remain_user[1]]!=NULL){
		if(@$_SESSION[$seesionKey][$remain_user[1]]['user'][$challenge_property]>@$_SESSION[$seesionKey][$remain_user[0]]['user'][$challenge_property]){
				$_SESSION[$seesionKey][$remain_user[1]]['user']['position'] = 2;
		}
		else{
			$_SESSION[$seesionKey][$remain_user[1]]['user']['position'] = 3;
		}
	}

	//remove item if user lose
	loseTool(@$remain_user);
	#return $reamin_user;
}

//set new random challenge
function set_new_random_challenge()
{
	global $seesionKey;
 	//regenerate new challenge after set position
	$challenge = new challenge();
	$challenges_list = $challenge->get_challenges();
	//set randomly selected challenge to session
	set_session('user_challenge',$challenges_list);
 	$j=0;
	while($j<sizeof($_SESSION[$seesionKey]))
	{
		$challenges_list['name'] = $_SESSION[$seesionKey][$j]['user']['name'];
		$_SESSION[$seesionKey][$j]['challenge'] = $challenges_list;
		$j++;
	}

	/*$challenge = new challenge();
	$challenges_list = $challenge->get_challenges();
	//set randomly selected challenge to session
	set_session('user_challenge',$challenges_list);
	$challenges_list['name'] = $_SESSION[$seesionKey][$i]['user']['name'];
	$_SESSION[$seesionKey][$i]['challenge'] = $challenges_list;
	foreach($remain_user as $user){
		$_SESSION[$seesionKey][$user]['challenge'] = $challenges_list;
	}*/
}

//set challenge property in array and return
function set_challenge_property_value($property,$value)
{
	return array('challenge_property'=>$property,'challenge_value'=>$value);
}

//reindex user session
function reindex_user_session()
{
	global $seesionKey;
	if(@$_SESSION[$seesionKey]!=NULL){
		$_SESSION[$seesionKey] = array_values(@$_SESSION[$seesionKey]);
	}
}

//increase and decrease success point
function increase_decrease_success_point($challengeType)
{
	if($challengeType=='carryOutChallenge')
		$successPoints = array(array('position'=>1,'point'=>15),array('position'=>2,'point'=>0),array('position'=>3,'point'=>(-5)));
	else if($challengeType=='carryOutChallengeWithCompanion')
		$successPoints = array(array('position'=>1,'point'=>9),array('position'=>2,'point'=>0),array('position'=>3,'point'=>(-5)));
	if($successPoints!=NULL)
	{

 		global $seesionKey;

		//check if real user win remove all session
		$j=0;
		while($j<sizeof(@$_SESSION[$seesionKey]))
		{
			$userSuccessPoint = @$_SESSION[$seesionKey][$j]['user']['success_point'];
			if($userSuccessPoint<=0 || $userSuccessPoint>=100){
				if($_SESSION[$seesionKey][$j]['slug_name']==$_SESSION['real_user_name']['slug_name']){
						unset($_SESSION[$seesionKey]);
				}
 			}
			unset($userSuccessPoint);
			$j++;
		}

		//checking success point limit stop increase and decrease if user success point reach 0 or 100
		$j=0;
		while($j<sizeof(@$_SESSION[$seesionKey]))
		{
			$userSuccessPoint = @$_SESSION[$seesionKey][$j]['user']['success_point'];
			if($userSuccessPoint<=0 || $userSuccessPoint>=100){
					//$_SESSION[$seesionKey][$j]['user']['success_point'] = "REMOVE THIS USER";
					$_SESSION[$seesionKey][$j] = '';
					unset($_SESSION[$seesionKey][$j]);
 			}
			unset($userSuccessPoint);
			$j++;
		}

		reindex_user_session();

 		$j=0;
		while($j<sizeof(@$_SESSION[$seesionKey]))
		{
			$getPos = @$_SESSION[$seesionKey][$j]['user']['position'];
			$userSuccessPoint = @$_SESSION[$seesionKey][$j]['user']['success_point'];
			//get success point with position and match users position
			foreach($successPoints as $points)
			{
					if($points['position']==$getPos){
						if ($points['point']>0){
							 $_SESSION[$seesionKey][$j]['user']['success_point'] = ($userSuccessPoint + $points['point']);
						}
						else{
							 $_SESSION[$seesionKey][$j]['user']['success_point'] = ($userSuccessPoint - (abs($points['point'])));
 						}
					}
			}
			unset($userSuccessPoint);
			unset($getPos);
			$j++;
		}
	}
}
//Add new random item when user win in session
function winTool($i)
{
	global $seesionKey;
	$userItems = new item();
	//get random item
	$newItem = $userItems->get_items_list(false);
	if($newItem!=NULL && (count($_SESSION[$seesionKey][$i]['item'])<3)){
		$_SESSION[$seesionKey][$i]['item'][] = $newItem;
	}
}
//Remove item when user lose in session
function loseTool($remain_user)
{
	global $seesionKey;
	//calcuate user property
	$j=0;
	while($j<sizeof($remain_user))
	{
		//return $_SESSION[$seesionKey][$remain_user[$j]]['item'];
		unset($_SESSION[$seesionKey][$remain_user[$j]]['item'][(count($_SESSION[$seesionKey][$remain_user[$j]]['item'])-1)]);
		$j++;
	}
}

//play together decrease success point
function play_challenge_together()
{
		global $seesionKey;
		if($_SESSION[$seesionKey][0]!=NULL && $_SESSION[$seesionKey][1]!=NULL){
        	$_SESSION[$seesionKey][0]['user']['success_point'] = ($_SESSION[$seesionKey][0]['user']['success_point']-5);
			$_SESSION[$seesionKey][1]['user']['success_point'] = ($_SESSION[$seesionKey][1]['user']['success_point']-5);
		}
}
//decrease user success point new challenge
function new_challenge()
{
		global $seesionKey;
		if($_SESSION[$seesionKey][0]!=NULL){
        	$_SESSION[$seesionKey][0]['user']['success_point'] = ($_SESSION[$seesionKey][0]['user']['success_point']-5);
		}
}
?>


text:
@implementation GSWAllAuthorOwnPictureResponse

@end


text:
const should = require("should");

const construct_ISA95_addressSpace = require("./helpers/bootstrap").construct_ISA95_addressSpace;

const opcua = require("node-opcua");

describe("GitHub Issues ",function() {

    let addressSpace = null;
    this.timeout(20000);

    before(function (done) {
        construct_ISA95_addressSpace(function (err, r) {
            addressSpace = r;
            done(err);
        });
    });

    after(function () {
        if (addressSpace) {
            addressSpace.dispose();
            addressSpace = null;
        }
    });

    it("#2 - should be possible to specify nodeId in addEquipment",function() {

      const equipment = addressSpace.addEquipment({
          browseName:"SomeEquiment",
          nodeId: "i=1234"
      });
      equipment.nodeId.toString().should.eql("ns=1;i=1234");
    });

});


text:
package com.opengamma.sesame.engine;

import javax.management.MXBean;

/**
 * MBean interface for exposing engine operations via JMX.
 */
@MXBean
public interface ViewFactoryMonitor {

  /**
   * Discards all entries from the engine cache.
   * <p>
   * The current cache is unchanged, but it is replaced by an empty cache.
   * This doesn't affect views that are already running a calculation cycle,
   * they continue to use the old cache until they start their next cycle.
   */
  void clearCache();

  /**
   * Discards all entries from the metrics registry.
   */
  void clearMetrics();
}


text:
package com.hctrom.romcontrol;

import android.app.Fragment;
import android.os.Bundle;
import android.preference.PreferenceFragment;

public class BotonesFisicosFragment extends PreferenceFragment {
    HandlePreferenceFragments hpf;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        hpf = new HandlePreferenceFragments(getActivity(), this, "botones_fisicos_prefs");
    }

    @Override
    public void onResume() {
        super.onResume();
        hpf.onResumeFragment();
    }

    @Override
    public void onPause() {
        super.onPause();
        hpf.onPauseFragment();
    }

}


text:
set -e
set -o pipefail

check_installed() {
  if ! command -v $1 > /dev/null 2>&1; then
    printf "$1 must be installed before running this script!"
    exit 1
  fi
}

configure_pipeline() {
  local name=$1
  local pipeline=$2

  printf "configuring the $name pipeline...\n"

  fly -t ci set-pipeline \
    -p $name \
    -c $pipeline \
    -l <(lpass show "Shared-Concourse/Concourse Pipeline Credentials" --notes)
}

check_installed lpass
check_installed fly

# Make sure we're up to date and that we're logged in.
lpass sync

pipelines_path=$(cd $(dirname $0)/../ci/pipelines && pwd)

configure_pipeline main \
  $pipelines_path/concourse.yml

configure_pipeline resources \
  $pipelines_path/resources.yml

configure_pipeline images \
  $pipelines_path/images.yml


text:
package de.oliver_heger.linedj.archivehttp.impl

import akka.actor.ActorRef
import de.oliver_heger.linedj.shared.archive.union.{AddMedia, ArchiveComponentRemoved, MediaContribution}
import scalaz.State
import scalaz.State._

/**
  * Data class that represents a sequence of messages to an actor to be sent.
  *
  * With instances of this class the update service indicates the messages to
  * be sent when a state transition occurs.
  *
  * @param target   the target to receive the messages
  * @param messages the actual messages
  */
case class MessageData(target: ActorRef, messages: Iterable[Any])

/**
  * Data class collecting the actors involved in a result propagation
  * operation.
  *
  * These actor references are required by the propagation update service to
  * generate the messages to be sent.
  *
  * @param mediaManager the union media manager actor
  * @param metaManager  the union meta data manager actor
  * @param client       the client actor to ACK when results are processed
  */
case class PropagationActors(mediaManager: ActorRef, metaManager: ActorRef, client: ActorRef)

/**
  * A class representing the propagation state to the union archive.
  *
  * The state contains the messages that are to be sent to the actors of the
  * union archive. If the ACK of a remove request is pending, messages cannot
  * be sent directly, but have to be buffered.
  *
  * @param messages        a list with messages to be sent
  * @param pendingMessages messages that are pending to be sent
  * @param removeAck       flag whether a remove ACK has been received
  */
case class ContentPropagationState(messages: List[MessageData],
                                   pendingMessages: List[MessageData],
                                   removeAck: Boolean)

/**
  * A service that manages the state of the propagation of media data to the
  * union archive during content processing of an HTTP archive.
  *
  * While reading the content document and the referenced documents of an HTTP
  * archive, the data extracted must be eventually passed to the union archive.
  * This is not too difficult for the media data, but becomes more complex when
  * another scan starts and the content of the current HTTP archive has to be
  * removed first from the union archive.
  *
  * This service takes care about this by providing corresponding update
  * functions for a propagation state object.
  */
trait ContentPropagationUpdateService {
  /** Type for a state update. */
  type StateUpdate[T] = State[ContentPropagationState, T]

  /**
    * Updates the state for another medium that has been processed. Messages to
    * be sent for this medium to the union archive actors are generated. If the
    * boolean remove parameter is '''true''', a request to remove the content
    * of the current HTTP archive from the union archive is generated as well.
    *
    * @param result    the medium processing result
    * @param actors    involved actors
    * @param archiveID the ID of the current HTTP archive
    * @param remove    flag whether archive content is to be removed
    * @return the updated state
    */
  def mediumProcessed(result: MediumProcessingResult, actors: PropagationActors,
                      archiveID: String, remove: Boolean): StateUpdate[Unit]

  /**
    * Updates the state when an ACK for a remove request arrives. Then pending
    * messages with results can be actually sent.
    *
    * @return the updated state
    */
  def removalConfirmed(): StateUpdate[Unit]

  /**
    * Updates the state regarding messages to be sent. With this function the
    * messages that are ready to be sent can be fetched. The state is updated
    * as if the messages were already sent to their receivers.
    *
    * @return the updated state and the messages to be sent
    */
  def messagesToSend(): StateUpdate[Iterable[MessageData]]

  /**
    * Handles a notification about a processed medium by updating the state
    * accordingly and returning a sequence with messages that have to be sent
    * now.
    *
    * @param result    the medium processing result
    * @param actors    involved actors
    * @param archiveID ID of the current HTTP archive
    * @param remove    flag whether archive content is to be removed
    * @return the updated state and messages to be sent
    */
  def handleMediumProcessed(result: MediumProcessingResult, actors: PropagationActors,
                            archiveID: String, remove: Boolean):
  StateUpdate[Iterable[MessageData]] = for {
    _ <- mediumProcessed(result, actors, archiveID, remove)
    msg <- messagesToSend()
  } yield msg

  /**
    * Handles an incoming confirmation of a removal request by updating the
    * state accordingly and returning a sequence of messages that have to be
    * sent now.
    *
    * @return the updated state and messages to be sent
    */
  def handleRemovalConfirmed(): StateUpdate[Iterable[MessageData]] = for {
    _ <- removalConfirmed()
    msg <- messagesToSend()
  } yield msg
}

/**
  * The implementation of the ''ContentPropagationUpdateService''.
  */
object ContentPropagationUpdateServiceImpl extends ContentPropagationUpdateService {
  /** Constant for the initial propagation state. */
  val InitialState: ContentPropagationState =
    ContentPropagationState(messages = Nil, pendingMessages = Nil, removeAck = true)

  override def mediumProcessed(result: MediumProcessingResult, actors: PropagationActors,
                               archiveID: String, remove: Boolean):
  StateUpdate[Unit] = modify { s =>
    if (remove)
      ContentPropagationState(messages = List(MessageData(actors.mediaManager,
        Seq(ArchiveComponentRemoved(archiveID)))), removeAck = false,
        pendingMessages = createMessagesForMedium(result, actors, archiveID, result.seqNo))
    else {
      val orgMessages = if (s.removeAck) s.messages else s.pendingMessages
      val updateMessages = createMessagesForMedium(result, actors, archiveID,
        result.seqNo) ::: orgMessages
      val (newMessages, newPending) =
        if (s.removeAck) (updateMessages, s.pendingMessages)
        else (s.messages, updateMessages)
      s.copy(messages = newMessages, pendingMessages = newPending)
    }
  }

  override def removalConfirmed(): StateUpdate[Unit] = modify { s =>
    if (s.removeAck) s
    else ContentPropagationState(messages = s.pendingMessages, pendingMessages = Nil,
      removeAck = true)
  }

  override def messagesToSend(): StateUpdate[Iterable[MessageData]] = State { s =>
    (s.copy(messages = Nil), s.messages)
  }

  /**
    * Creates a list with ''MessageData'' objects representing the messages to
    * be sent for the result of a processed medium.
    *
    * @param result    the ''MediumProcessingResult''
    * @param actors    actors involved in propagation
    * @param archiveID the ID of the archive
    * @param seqNo     the sequence number of the current operation
    * @return a list with the messages to propagate this result
    */
  private def createMessagesForMedium(result: MediumProcessingResult, actors: PropagationActors,
                                      archiveID: String, seqNo: Int): List[MessageData] =
    List(createAddMediaMessage(result, actors, archiveID),
      createMetaDataMessages(result, actors), createPropagatedMessage(seqNo, actors))

  /**
    * Creates the message to the media manager actor that adds a medium
    * description to the union archive.
    *
    * @param result    the current result object
    * @param actors    actors involved in propagation
    * @param archiveID the ID of the archive
    * @return the ''MessageData'' object with the message
    */
  private def createAddMediaMessage(result: MediumProcessingResult, actors: PropagationActors,
                                    archiveID: String): MessageData =
    MessageData(actors.mediaManager,
      Seq(AddMedia(Map(result.mediumInfo.mediumID -> result.mediumInfo), archiveID,
        Some(actors.client))))

  /**
    * Creates a ''MessageData'' with the messages to be sent to the meta data
    * manager to add the content of a medium to the union archive.
    *
    * @param result the result object for the medium
    * @param actors actors involved in propagation
    * @return the ''MessageData'' object
    */
  private def createMetaDataMessages(result: MediumProcessingResult, actors: PropagationActors):
  MessageData = {
    val files = result.metaData map (m => m.uri)
    val contribution = MediaContribution(Map(result.mediumInfo.mediumID -> files))
    val messages = contribution :: result.metaData.toList
    MessageData(actors.metaManager, messages)
  }

  /**
    * Creates a ''MessageData'' object with an ACK message indicating that the
    * results of a medium have been propagated to the union archive.
    *
    * @param seqNo  the sequence number of the current operation
    * @param actors actors involved in propagation
    * @return the ''MessageData'' object
    */
  private def createPropagatedMessage(seqNo: Int, actors: PropagationActors): MessageData =
    MessageData(actors.client, Seq(MediumPropagated(seqNo)))
}


text:
<TITLE>Review for Lake Placid (1999)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Lake Placid (1999)

reviewed by
Walter Frith

'Lake Placid' (1999)

A movie review by Walter Frith

wfrith@cgocable.net

Member of the 'Online Film Critics Society'
http://www.ofcs.org

I'm puzzled by the fact that in 1998 the American Film Institute rated the
original 'Jaws' from 1975 #48 on its all time list.  Don't misunderstand.
The ratings were not based just on being the BEST in the minds of those who
rated the list of films involved but included the movies with the biggest
historical impact and cultural significance.  Having gotten that out of the
way, why was 1952's 'Singing in the Rain' #10 all time when the musical in
this day and age has practically dried up and vanished yet we still have
predatory films laced with thrills and humour the way 'Jaws' portrayed its
subject matter.  Heck, in 'Lake Placid' a human head even pops out at you
the way one did from the bottom of the boat in 'Jaws'.

In today's surroundings, you can certainly make a film with gritty special
effects that look realistic enough.  This seems understood already but look
at 1997's 'Anaconda', a film with horribly digitized special effects where
the crop marks on the giant snake stood out so much that you could
practically feel them if you touched the movie screen.  Things have been
cleaned up a lot here.

'Lake Placid' is directed by Steve Miner ('Friday the 13th 2+3').  Miner
tastefully edits his picture here so that the gore is generally quick like a
lightening bolt (perhaps a wee bit longer than that) but he stretches out
the laughs to overlap any squeamish feeling audiences may have about all the
blood and guts.

'Lake Placid' is an end of the century 'Jaws' rip-off in an endearing sort
of way, and the material is dumbfounded and irreverent entertainment that
somehow works.  I suppose you could argue that 83 minutes isn't enough to
justify a ticket price of nearly ten dollars but you will get several laughs
to soften the blow and many of you will like the film's strange brew of
different ingredients.

The film begins in Maine as a small town sheriff named Hank Keough (Brendan
Gleeson) and a diver are out on a black coloured lake and the diver gets
bitten in half below the waist and the investigation begins!  This film has
nothing to do with Lake Placid, New York.  The title is irreverent as they
joke that they wanted to give the lake in question that name but it was
already taken.  A game warden, Jack Wells (Bill Pullman) is called in from
the local area as is paleontologist Kelly Scott (Bridget Fonda) from New
York City.  They are later joined by Hector Cyr (Oliver Platt) who is a
mythology professor who likes and worships the presence of crocodiles.  His
character is thrown into the mix for comic relief and is similar to the Matt
Hooper character portrayed in 'Jaws' by Richard Dreyfuss as the shark
expert.

In typical 'Jaws' like fashion, the crocodile isn't seen right away but much
later on in the film and there isn't much of an explanation as to how one
identified to have Asian origins could end up in a lake in New England.

Despite the gaps in logic, there is plenty of off beat and original humour
penned by David E. Kelley of television's 'The Practice' and Ally McBeal.
One of his characters includes a potty-mouthed Betty White.  Yes, that's
right.  Betty White of 'The Mary Tyler Moore Show' and 'The Golden Girls'.
She plays a widow living on the lake who sort of treats the croc to free
meals made of full living cows and her now deceased husband?

A 30-foot crocodile may seem like a stretch (no pun intended) to believe
they could exist in the type of places they do in this picture but if you
want a good scary picture a bit more effective, look for 1980's 'Alligator'
as it is better and uses Chicago as its setting where a bigger population is
threatened that seems more exciting but 'Lake Placid' is still that form of
entertainment where the 'boing' sound would have matched its goofy but
effective scenes.

OUT OF 5 > * * * 1/2

Visit FILM FOLLOW-UP by Walter Frith
http://www.cgocable.net/~wfrith/movies.htm

* * * * * - a must see
* * * * 1/2 - don't miss it
* * * * - an excellent film
* * * 1/2 - a marginal recommendation
* * * - can't quite recommend it
* * 1/2 - don't recommend it
* * - avoid it
* 1/2 - avoid it seriously
* - avoid it AT ALL COSTS
1/2 - see it at your own risk
zero - may be hazardous to your health

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews