text:
classdef Adapter < handle
        %changes the tranformation flow by applying different strategies such
        %as crossvalidations, processing of different segments, mra, etc.
        %before data it can exectute a processing chain
	properties
		adptee
		patternProcessor
	end

	methods
		function self=Adapter(adptee,patternProcessor)
			self.adptee=adptee;
			self.patternProcessor=patternProcessor;
		end
	end

	methods(Abstract)
		[train,test]=doAdapt(self,train,test);
	end

        methods (Access=public)
                function [train,test]=adapt(train,test)
			if ~isempty(self.patternProcessor)
				[train,test]=self.patternProcessor.process(train,test);
			end
                        [train,test]= self.doAdapt(train,test);

                end

        end

end

redpajama_set_name: RedPajamaGithub


text:
requirejs.config({
  paths: {
    'jquery': "https://code.jquery.com/jquery-1.12.4.min",
    'Model': 'model-MVC',
    'View': 'view-MVC',
    'Controller': 'controller-MVC'
  },
  shim: {
    'jquery': {
      exports: 'jQuery'
    }
  }
});

require(
  [
    'jquery',
    'tmpl',
    'Model',
    'View',
    'Controller'
  ],
  function($, tmpl, Model, View, Controller) {

        var firstTodoList = ['сделать домашки', 'сделать экзамен', 'гульнуть'];
        var model = new Model.Model(firstTodoList);
        var view = new View.View(model);
        var controller = new Controller.Controller(model, view);

  }
);


text:
package commands

import (
	"fmt"
	"regexp"

	"github.com/github/hub/github"
	"github.com/github/hub/utils"
)

var cmdMerge = &Command{
	Run:          merge,
	GitExtension: true,
	Usage:        "merge PULLREQ-URL",
	Short:        "Join two or more development histories (branches) together",
	Long: `Merge the pull request with a commit message that includes the pull request
ID and title, similar to the GitHub Merge Button.
`,
}

func init() {
	CmdRunner.Use(cmdMerge)
}

/*
  $ gh merge https://github.com/jingweno/gh/pull/73
  > git fetch git://github.com/jingweno/gh.git +refs/heads/feature:refs/remotes/jingweno/feature
  > git merge jingweno/feature --no-ff -m 'Merge pull request #73 from jingweno/feature...'
*/
func merge(command *Command, args *Args) {
	if !args.IsParamsEmpty() {
		err := transformMergeArgs(args)
		utils.Check(err)
	}
}

func transformMergeArgs(args *Args) error {
	words := args.Words()
	if len(words) == 0 {
		return nil
	}

	mergeURL := words[0]
	url, err := github.ParseURL(mergeURL)
	if err != nil {
		return nil
	}

	pullURLRegex := regexp.MustCompile("^pull/(\\d+)")
	projectPath := url.ProjectPath()
	if !pullURLRegex.MatchString(projectPath) {
		return nil
	}

	id := pullURLRegex.FindStringSubmatch(projectPath)[1]
	gh := github.NewClient(url.Project.Host)
	pullRequest, err := gh.PullRequest(url.Project, id)
	if err != nil {
		return err
	}

	branch := pullRequest.Head.Ref
	headRepo := pullRequest.Head.Repo
	if headRepo == nil {
		return fmt.Errorf("Error: that fork is not available anymore")
	}

	u := url.GitURL(headRepo.Name, headRepo.Owner.Login, headRepo.Private)
	mergeHead := fmt.Sprintf("%s/%s", headRepo.Owner.Login, branch)
	ref := fmt.Sprintf("+refs/heads/%s:refs/remotes/%s", branch, mergeHead)
	args.Before("git", "fetch", u, ref)

	// Remove pull request URL
	idx := args.IndexOfParam(mergeURL)
	args.RemoveParam(idx)

	mergeMsg := fmt.Sprintf("Merge pull request #%v from %s\n\n%s", id, mergeHead, pullRequest.Title)
	args.AppendParams(mergeHead, "-m", mergeMsg)

	if args.IndexOfParam("--ff-only") == -1 && args.IndexOfParam("--squash") == -1 && args.IndexOfParam("--ff") == -1 {
		i := args.IndexOfParam("-m")
		args.InsertParam(i, "--no-ff")
	}

	return nil
}


text:
import os
from setuptools import setup, find_packages

f = open(os.path.join(os.path.dirname(__file__), 'README.md'))
readme = f.read()
f.close()

setup(
    name='django-tracer',
    version="0.9.2",
    description='django-tracer gives you an easy way to generate and use a UUID per request',
    long_description=readme,
    long_description_content_type='text/markdown',
    author='Frank Wiles',
    author_email='frank@revsys.com',
    url='https://github.com/revsys/django-tracer/',
    include_package_data=True,
    packages=find_packages(),
    zip_safe=False,
    test_suite='runtests.runtests',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3',
        'Framework :: Django',
    ],
)


text:
<?php

namespace EDB\ContentBundle\Services;

use EDB\ContentBundle\Entity\StockItem;

class Stock
{
    private $db = null;
    private $className = '';

    public function __construct($db, $className)
    {
        $this->db = $db;
        $this->className = $className;
    }

    public function getAllByUser($user_id)
    {
        return $this->db->getRepository($this->className)->findBy(array('user_id' => $user_id, 'deleted' => false), array('name' => 'ASC'));
    }

    public function getAllByArticleAndUser($article_id, $user_id)
    {
        return $this->db->getRepository($this->className)->findBy(array('item_id' => $article_id, 'user_id' => $user_id, 'deleted' => false), array('name' => 'ASC'));
    }

    public function getStockItem($article_id, $user_id, $stock_id)
    {
        return $this->db->getRepository($this->className)->findOneBy(array('item_id' => $article_id, 'user_id' => $user_id, 'id' => $stock_id, 'deleted' => false));
    }

    public function put($o, $article_id, $user_id, $name, $qty, $package, $note, $storage)
    {
        if (!$o) {
            $o = new StockItem();
            $o->setItemId($article_id);
            $o->setUserId($user_id);
        }

        $o->setName($name);
        $o->setQuantity($qty);
        $o->setPackage($package);
        $o->setNote($note);
        $o->setStorage($storage);
        $o->setDeleted(false);

        $this->db->persist($o);
        $this->db->flush();

        return $o;
    }

    public function delete($o)
    {
        if (!is_object($o)) {
            return false;
        }

        $o->setDeleted(true);
        $this->db->flush();

        return true;
    }

}


text:
<!DOCTYPE html>

  <meta charset="utf-8"/>
  <title>Converter Romani!</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

  <link rel="stylesheet" type="text/css" href="style.css" />

Jen

Dva

Tri

Štiri

Converter Romani

    <input id="decimal" type="radio" name="convert-type" value="Decimal" class="form-check-input" >Decimal to Roman

    <input id="roman" type="radio" name="convert-type" value="Roman" class="form-check-input" >Roman to Decimal

    <form id="form" class="form-group">
      Number to Convert:
      <input id="input-text" type="text" name="number" class="form-control">
      Enter a number
      <input type="submit" id="submit" value="Submit" class="btn btn-default btn-primary" >
      <input type="reset" id="reset" value="Reset" class="btn btn-default">

    </form>

      Converted Value


text:
import java.io.*;

public class Count {
    public static void countChars(InputStream in) throws IOException
    {
        int count = 0;

        while (in.read() != -1)
            count++;

        System.out.println("Counted " + count + " chars.");
    }

    public static void main(String[] args) throws Exception
    {
        if (args.length >= 1)
            countChars(new FileInputStream(args[0]));
        else
            System.err.println("Usage: Count filename");
    }
}


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

namespace Tortilla {
    public enum ClockState {
        TickOn,
        TickEnable,
        TickSet,
        TickOff,
        TickDecode
    }

    public interface IClock {
        bool IsRunning { get; }
        void Start();
        void Stop();
        void ConnectComponent(IBusComponent component);
        void Tick();
    }

    public interface IBus {

    }

    public interface IDataBus<DataType> : IBus {
        DataType Value { get; set; }
    }

    public enum BusTypes {
        AddressBus,
        DataBus,
        IOBus
    }

    public interface IBusComponent {
        void OnTick(ClockState state);
        void Enable(BusTypes type);
        void Set(BusTypes type);
        bool AddressBusEnabled { get; }
        bool AddressBusSet { get; }
        bool DataBusEnabled { get; }
        bool DataBusSet { get; }
        bool IOBusEnabled { get; }
        bool IOBusSet { get; }

        bool IsEnabled { get; }
        bool IsSet { get; }
    }

    public interface IRegister<DataType> : IBusComponent {
        IDataBus<DataType> DataBus { get; set; }
        IDataBus<DataType> AddressBus { get; set; }
        IDataBus<DataType> IOBus { get; set; }
        DataType Value { get; set; }
    }

    public interface IMotherboard<DataType> {
        IClock Clock { get; }

        void OnDebug(string disasm);
        void OnDebug();
        void OnPowerOff();
        void OnRaiseException(byte id);
        void RaiseInterrupt(int id);

        event EventHandler<string> Debug;
        event EventHandler PoweredOff;
        event EventHandler<byte> RaiseException;

        IDataBus<DataType> DataBus { get; }
        IDataBus<DataType> AddressBus { get; }
        IDataBus<DataType> IOBus { get; }
        ICpu<DataType> Cpu { get; }
        UInt32 MemorySize { get; }
        void Reset();
        void PowerOn();
        void PowerOff();
        byte ReadByte(DataType address);
        void WriteByte(DataType address, byte value);
        void EnablePort(byte address);
        void SetPort(byte address);

        void ConnectComponent(IBusComponent component);
        void ConnectDevice(IBusComponent component, int address);
        int ConnectInterrupt(IBusComponent component, int address);
    }

    public interface ICpu<DataType> : IBusComponent {
        void PowerOn();
        void PowerOff();
        void Reset();
        void RaiseInterrupt(int id);
        void Break();
        bool SingleStep { get; set; }
        void Continue();
        string RegisterDump { get; }
        bool IsPowerOn { get; }

        event EventHandler<Tuple<UInt64, UInt64>> DecodeInstruction;
    }

    public interface IPic<DataType> : IRegister<DataType> {
        UInt32 CommandPort { get; set; }
        UInt32 DataPort { get; set; }
    }

    public interface IDissasember<DataType, AddressType> {
        int Decode(DataType value, AddressType address, out string text);
    }
}


text:
from __future__ import absolute_import

from sentry.models import (
    Commit, CommitAuthor, Environment, EnvironmentProject, Event, EventAttachment, File, Group, GroupAssignee, GroupMeta,
    GroupResolution, Project, Release, ReleaseCommit, Repository, ScheduledDeletion,
    ProjectDSymFile
)
from sentry.tasks.deletion import run_deletion
from sentry.testutils import TestCase

class DeleteProjectTest(TestCase):
    def test_simple(self):
        project = self.create_project(
            name='test',
        )
        group = self.create_group(project=project)
        event = self.create_event(group=group)
        GroupAssignee.objects.create(group=group, project=project, user=self.user)
        GroupMeta.objects.create(group=group, key='foo', value='bar')
        release = Release.objects.create(version='a' * 32, organization_id=project.organization_id)
        release.add_project(project)
        GroupResolution.objects.create(group=group, release=release)
        env = Environment.objects.create(
            organization_id=project.organization_id, project_id=project.id, name='foo'
        )
        env.add_project(project)
        repo = Repository.objects.create(
            organization_id=project.organization_id,
            name=project.name,
        )
        commit_author = CommitAuthor.objects.create(
            organization_id=project.organization_id,
            name='foo',
            email='foo@example.com',
        )
        commit = Commit.objects.create(
            repository_id=repo.id,
            organization_id=project.organization_id,
            author=commit_author,
            key='a' * 40,
        )
        ReleaseCommit.objects.create(
            organization_id=project.organization_id,
            project_id=project.id,
            release=release,
            commit=commit,
            order=0,
        )
        file = File.objects.create(
            name='dsym-file',
            type='project.dsym',
        )
        dsym_file = ProjectDSymFile.objects.create(
            file=file,
            debug_id='uuid',
            cpu_name='cpu',
            object_name='object',
            project=project,
        )
        EventAttachment.objects.create(
            event_id=event.event_id,
            project_id=event.project_id,
            file=File.objects.create(
                name='hello.png',
                type='image/png',
            ),
            name='hello.png',
        )

        deletion = ScheduledDeletion.schedule(project, days=0)
        deletion.update(in_progress=True)

        with self.tasks():
            run_deletion(deletion.id)

        assert not Project.objects.filter(id=project.id).exists()
        assert not EnvironmentProject.objects.filter(
            project_id=project.id, environment_id=env.id
        ).exists()
        assert Environment.objects.filter(id=env.id).exists()
        assert not Group.objects.filter(project_id=project.id).exists()
        assert not Event.objects.filter(project_id=project.id).exists()
        assert not EventAttachment.objects.filter(project_id=project.id).exists()
        assert Release.objects.filter(id=release.id).exists()
        assert ReleaseCommit.objects.filter(release_id=release.id).exists()
        assert Commit.objects.filter(id=commit.id).exists()
        assert not ProjectDSymFile.objects.filter(id=dsym_file.id).exists()
        assert not File.objects.filter(id=file.id).exists()


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Ocellularia polydisca var. margaritacea Redinger

### Remarks
null


text:
package com.grietenenknapen.sithandroid.maingame.usecases;

import com.grietenenknapen.sithandroid.R;

import junit.framework.Assert;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;

public class BobaFettUseCaseTest {

    private static final long KILLED_USER_ID = 1L;

    private BobaFettUseCase bobaFettUseCase;

    @Mock
    private BobaFettUseCase.CallBack callBack;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testBobaFett_NoHistoryUseMedPackUseRocketLauncher_Active() {
        bobaFettUseCase = new BobaFettUseCase(callBack, true, false, false);

        bobaFettUseCase.onSetupUseCase(1);

        Assert.assertEquals(bobaFettUseCase.finishUseCase(1), false);
        bobaFettUseCase.onPrepareStep(1);
        Mockito.verify(callBack).speak(R.raw.basis11_bobafettwordtwakker, R.string.basis11_boba_fett_wordt_wakker, bobaFettUseCase);
        bobaFettUseCase.onExecuteStep(1);

        Assert.assertEquals(bobaFettUseCase.finishUseCase(2), false);
        bobaFettUseCase.onPrepareStep(2);
        Mockito.verify(callBack).showKilledPlayerMedPackYesNo(bobaFettUseCase);
        bobaFettUseCase.onExecuteStep(2, true);
        Mockito.verify(callBack).useMedPack();

        Assert.assertEquals(bobaFettUseCase.finishUseCase(3), false);
        bobaFettUseCase.onPrepareStep(3);
        Mockito.verify(callBack).speak(R.raw.basis12_bobafettrocketlauncher, R.string.basis12_boba_fett_rocketlauncher, bobaFettUseCase);
        bobaFettUseCase.onExecuteStep(3);

        Assert.assertEquals(bobaFettUseCase.finishUseCase(4), false);
        bobaFettUseCase.onPrepareStep(4);
        Mockito.verify(callBack).requestYesNoAnswerRocket(bobaFettUseCase);
        bobaFettUseCase.onExecuteStep(4, true);
        Mockito.verify(callBack).setRockedAlreadySelected(true);

        Assert.assertEquals(bobaFettUseCase.finishUseCase(5), false);
        bobaFettUseCase.onPrepareStep(5);
        Mockito.verify(callBack).requestUserPlayerRocketSelection(bobaFettUseCase);
        bobaFettUseCase.onExecuteStep(5, KILLED_USER_ID);
        Mockito.verify(callBack).useRockedLauncher(KILLED_USER_ID);

        Assert.assertEquals(bobaFettUseCase.finishUseCase(6), false);
        bobaFettUseCase.onPrepareStep(6);
        Mockito.verify(callBack).speak(R.raw.basis13_bobafettgaatterugslapen, R.string.basis13_boba_fett_gaat_terug_slapen, bobaFettUseCase);
        bobaFettUseCase.onExecuteStep(6);

        Mockito.verify(callBack, Mockito.times(2)).playBobaFettMusic();
        Mockito.verify(callBack, Mockito.times(2)).stopPlayingMusic();

        Assert.assertEquals(bobaFettUseCase.finishUseCase(7), true);

        Mockito.verify(callBack, Mockito.times(6)).nextStep(Mockito.anyInt());
    }

    @Test
    public void testBobaFett_NoHistoryUseNothing_Active() {
        bobaFettUseCase = new BobaFettUseCase(callBack, true, false, false);

        bobaFettUseCase.onSetupUseCase(1);

        Assert.assertEquals(bobaFettUseCase.finishUseCase(1), false);
        bobaFettUseCase.onPrepareStep(1);
        Mockito.verify(callBack).speak(R.raw.basis11_bobafettwordtwakker, R.string.basis11_boba_fett_wordt_wakker, bobaFettUseCase);
        bobaFettUseCase.onExecuteStep(1);

        Assert.assertEquals(bobaFettUseCase.finishUseCase(2), false);
        bobaFettUseCase.onPrepareStep(2);
        Mockito.verify(callBack).showKilledPlayerMedPackYesNo(bobaFettUseCase);
        bobaFettUseCase.onExecuteStep(2, false);

        Assert.assertEquals(bobaFettUseCase.finishUseCase(3), false);
        bobaFettUseCase.onPrepareStep(3);
        Mockito.verify(callBack).speak(R.raw.basis12_bobafettrocketlauncher, R.string.basis12_boba_fett_rocketlauncher, bobaFettUseCase);
        bobaFettUseCase.onExecuteStep(3);

        Assert.assertEquals(bobaFettUseCase.finishUseCase(4), false);
        bobaFettUseCase.onPrepareStep(4);
        Mockito.verify(callBack).requestYesNoAnswerRocket(bobaFettUseCase);
        bobaFettUseCase.onExecuteStep(4, false);

        Assert.assertEquals(bobaFettUseCase.finishUseCase(5), false);
        bobaFettUseCase.onPrepareStep(5);
        Mockito.verify(callBack).speak(R.raw.basis13_bobafettgaatterugslapen, R.string.basis13_boba_fett_gaat_terug_slapen, bobaFettUseCase);
        bobaFettUseCase.onExecuteStep(5);

        Mockito.verify(callBack, Mockito.times(2)).playBobaFettMusic();
        Mockito.verify(callBack, Mockito.times(2)).stopPlayingMusic();

        Assert.assertEquals(bobaFettUseCase.finishUseCase(6), true);

        Mockito.verify(callBack, Mockito.times(5)).nextStep(Mockito.anyInt());
    }

    @Test
    public void testBobaFett_RocketAlreadyUsedUseNothing_Active() {
        bobaFettUseCase = new BobaFettUseCase(callBack, true, false, true);

        bobaFettUseCase.onSetupUseCase(2);

        Assert.assertEquals(bobaFettUseCase.finishUseCase(5), false);
        bobaFettUseCase.onPrepareStep(5);
        Mockito.verify(callBack).requestUserPlayerRocketSelection(bobaFettUseCase);
        bobaFettUseCase.onExecuteStep(5, KILLED_USER_ID);
        Mockito.verify(callBack).useRockedLauncher(KILLED_USER_ID);

        Assert.assertEquals(bobaFettUseCase.finishUseCase(6), false);
        bobaFettUseCase.onPrepareStep(6);
        Mockito.verify(callBack).speak(R.raw.basis13_bobafettgaatterugslapen, R.string.basis13_boba_fett_gaat_terug_slapen, bobaFettUseCase);
        bobaFettUseCase.onExecuteStep(6);

        Assert.assertEquals(bobaFettUseCase.finishUseCase(7), true);

        Mockito.verify(callBack, Mockito.times(1)).stopPlayingMusic();
        Mockito.verify(callBack, Mockito.times(2)).nextStep(Mockito.anyInt());
    }

    @Test
    public void testBobaFett_NotActive() {
        bobaFettUseCase = new BobaFettUseCase(callBack, false, false, false);

        bobaFettUseCase.onSetupUseCase(1);

        Assert.assertEquals(bobaFettUseCase.finishUseCase(1), false);
        bobaFettUseCase.onPrepareStep(1);
        Mockito.verify(callBack).speak(R.raw.basis11_bobafettwordtwakker, R.string.basis11_boba_fett_wordt_wakker, bobaFettUseCase);
        bobaFettUseCase.onExecuteStep(1);

        Assert.assertEquals(bobaFettUseCase.finishUseCase(2), false);
        bobaFettUseCase.onPrepareStep(2);
        bobaFettUseCase.onExecuteStep(2);

        Assert.assertEquals(bobaFettUseCase.finishUseCase(3), false);
        bobaFettUseCase.onPrepareStep(3);
        Mockito.verify(callBack).speak(R.raw.basis12_bobafettrocketlauncher, R.string.basis12_boba_fett_rocketlauncher, bobaFettUseCase);
        bobaFettUseCase.onExecuteStep(3);

        Assert.assertEquals(bobaFettUseCase.finishUseCase(4), false);
        bobaFettUseCase.onPrepareStep(4);
        bobaFettUseCase.onExecuteStep(4);

        Assert.assertEquals(bobaFettUseCase.finishUseCase(5), false);
        bobaFettUseCase.onPrepareStep(5);
        bobaFettUseCase.onExecuteStep(5);

        Assert.assertEquals(bobaFettUseCase.finishUseCase(6), false);
        bobaFettUseCase.onPrepareStep(6);
        Mockito.verify(callBack).speak(R.raw.basis13_bobafettgaatterugslapen, R.string.basis13_boba_fett_gaat_terug_slapen, bobaFettUseCase);
        bobaFettUseCase.onExecuteStep(6);

        Mockito.verify(callBack, Mockito.times(2)).playBobaFettMusic();
        Mockito.verify(callBack, Mockito.times(2)).stopPlayingMusic();

        Assert.assertEquals(bobaFettUseCase.finishUseCase(7), true);

        Mockito.verify(callBack, Mockito.times(2)).skipStepDelay(Mockito.anyLong());
        Mockito.verify(callBack, Mockito.times(1)).skipStep();

        Mockito.verify(callBack, Mockito.times(6)).nextStep(Mockito.anyInt());
    }

    @Test
    public void testBobaFett_RoundOne_Akip() {
        bobaFettUseCase = new BobaFettUseCase(callBack, true, true, false);

        bobaFettUseCase.onSetupUseCase(1);
        Assert.assertEquals(bobaFettUseCase.finishUseCase(1), true);
    }

}


text:
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden, HttpResponseBadRequest
from django.template import Context, RequestContext, loader
from django.http import Http404
from django.shortcuts import render_to_response, get_object_or_404
from django.core.urlresolvers import reverse
from django.conf import settings
from django.contrib.auth.decorators import permission_required
from signbank.log import debug
from tagging.models import TaggedItem, Tag
import os, shutil, re

from signbank.dictionary.models import *
from signbank.dictionary.forms import *

@permission_required('dictionary.add_gloss')
def add_gloss(request):
    """Create a new gloss and redirect to the edit view"""

    if request.method == "POST":

        form = GlossCreateForm(request.POST)
        if form.is_valid():

            gloss = form.save()
            gloss.excludeFromEcv = False

            return HttpResponseRedirect(reverse('dictionary:admin_gloss_view', kwargs={'pk': gloss.id})+'?edit')
        else:
            return render_to_response('dictionary/add_gloss_form.html',
                                      {'add_gloss_form': form},
                                      context_instance=RequestContext(request))

    return HttpResponseRedirect(reverse('dictionary:admin_gloss_list'))

def update_gloss(request, glossid):
    """View to update a gloss model from the jeditable jquery form
    We are sent one field and value at a time, return the new value
    once we've updated it."""

    if not request.user.has_perm('dictionary.change_gloss'):
        return HttpResponseForbidden("Gloss Update Not Allowed")

    if request.method == "POST":

        gloss = get_object_or_404(Gloss, id=glossid)

        field = request.POST.get('id', '')
        value = request.POST.get('value', '')
        values = request.POST.getlist('value[]')   # in case we need multiple values

        # validate
        # field is a valid field
        # value is a valid value for field

        if field == 'deletegloss':
            if value == 'confirmed':
                # delete the gloss and redirect back to gloss list
                gloss.delete()
                return HttpResponseRedirect(reverse('dictionary:admin_gloss_list'))

        if field.startswith('definition'):

            return update_definition(request, gloss, field, value)

        elif field == 'keywords':

            return update_keywords(gloss, field, value)

        elif field.startswith('relation'):

            return update_relation(gloss, field, value)

        elif field != 'regional_template' and field.startswith('region'):

            return update_region(gloss, field, value)

        elif field == 'language':
            # expecting possibly multiple values

            try:
                gloss.language.clear()
                for value in values:
                    lang = Language.objects.get(name=value)
                    gloss.language.add(lang)
                gloss.save()
                newvalue = ", ".join([str(g) for g in gloss.language.all()])
            except:
                return HttpResponseBadRequest("Unknown Language %s" % values, {'content-type': 'text/plain'})

        elif field == 'dialect':
            # expecting possibly multiple values

            try:
                gloss.dialect.clear()
                for value in values:
                    lang = Dialect.objects.get(name=value)
                    gloss.dialect.add(lang)
                gloss.save()
                newvalue = ", ".join([str(g.name) for g in gloss.dialect.all()])
            except:
                return HttpResponseBadRequest("Unknown Dialect %s" % values, {'content-type': 'text/plain'})

        elif field == "sn":
            # sign number must be unique, return error message if this SN is
            # already taken

            if value == '':
                gloss.__setattr__(field, None)
                gloss.save()
                newvalue = ''
            else:
                try:
                    value = int(value)
                except:
                    return HttpResponseBadRequest("SN value must be integer", {'content-type': 'text/plain'})

                existing_gloss = Gloss.objects.filter(sn__exact=value)
                if existing_gloss.count() > 0:
                    g = existing_gloss[0].idgloss
                    return HttpResponseBadRequest("SN value already taken for gloss %s" % g, {'content-type': 'text/plain'})
                else:
                    gloss.sn = value
                    gloss.save()
                    newvalue = value

        elif field == 'inWeb':
            # only modify if we have publish permission
            if request.user.has_perm('dictionary.can_publish'):
                gloss.inWeb = (value == 'Yes')
                gloss.save()

            if gloss.inWeb:
                newvalue = 'Yes'
            else:
                newvalue = 'No'

        elif field in 'excludeFromEcv':
            # only modify if we have publish permission

            gloss.excludeFromEcv = value.lower() in ['Yes','yes','true',True,1]
            gloss.save()

            if gloss.excludeFromEcv:
                newvalue = 'Yes'
            else:
                newvalue = 'No'

        else:

            if not field in Gloss._meta.get_all_field_names():
                return HttpResponseBadRequest("Unknown field", {'content-type': 'text/plain'})

            # special cases
            # - Foreign Key fields (Language, Dialect)
            # - keywords
            # - videos
            # - tags

            # special value of 'notset' or -1 means remove the value
            if value == 'notset' or value == -1 or value == '':
                if field == 'regional_template':
                    gloss.__setattr__(field, '')
                else:
                    gloss.__setattr__(field, None)
                gloss.save()
                newvalue = ''
            else:

                gloss.__setattr__(field, value)
                gloss.save()

                f = Gloss._meta.get_field(field)

                # for choice fields we want to return the 'display' version of
                # the value
                valdict = dict(f.flatchoices)
                # some fields take ints
                if valdict.keys() != [] and type(valdict.keys()[0]) == int:
                    newvalue = valdict.get(int(value), value)
                else:
                    # either it's not an int or there's no flatchoices
                    # so here we use get with a default of the value itself
                    newvalue = valdict.get(value, value)

        return HttpResponse(newvalue, {'content-type': 'text/plain'})

def update_keywords(gloss, field, value):
    """Update the keyword field"""

    kwds = [k.strip() for k in value.split(',')]
    # remove current keywords
    current_trans = gloss.translation_set.all()
    #current_kwds = [t.translation for t in current_trans]
    current_trans.delete()
    # add new keywords
    for i in range(len(kwds)):
        (kobj, created) = Keyword.objects.get_or_create(text=kwds[i])
        trans = Translation(gloss=gloss, translation=kobj, index=i)
        trans.save()

    newvalue = ", ".join([t.translation.text for t in gloss.translation_set.all()])

    return HttpResponse(newvalue, {'content-type': 'text/plain'})

def update_region(gloss, field, value):
    """Update one of the regions for this gloss"""

    (what, regid) = field.split('_')

    try:
        region = Region.objects.get(id=regid)
    except:
        return HttpResponseBadRequest("Bad Region ID '%s'" % regid, {'content-type': 'text/plain'})

    if not gloss == region.gloss:
        return HttpResponseBadRequest("Region doesn't match gloss", {'content-type': 'text/plain'})

    if what == 'regiondelete':
        region.delete()
        return HttpResponseRedirect(reverse('dictionary:admin_gloss_view', kwargs={'pk': gloss.id}) + "#regions")
    elif what == 'regiondialect':
        dialect = Dialect.objects.get(name=value)
        existing_region = gloss.region_set.filter(dialect=dialect)
        if len(existing_region) == 0 or existing_region[0] == region:
            region.dialect = dialect
            region.save()
        else:
            # We tried to change to an existing value, ignore it
            return HttpResponse(region.dialect.name, {'content-type': 'text/plain'})
    elif what == 'regionfrequency':
        region.frequency = value
        region.save()
    elif what == 'regiontraditional':
        if value == 1 or value == "1" or value == "traditional":
            region.traditional = True
            value = "traditional"
        else:
            region.traditional = False
            value = "attested"
        region.save()

    return HttpResponse(value, {'content-type': 'text/plain'})

def update_relation(gloss, field, value):
    """Update one of the relations for this gloss"""

    (what, relid) = field.split('_')

    try:
        rel = Relation.objects.get(id=relid)
    except:
        return HttpResponseBadRequest("Bad Relation ID '%s'" % defid, {'content-type': 'text/plain'})

    if not rel.source == gloss:
        return HttpResponseBadRequest("Relation doesn't match gloss", {'content-type': 'text/plain'})

    if what == 'relationdelete':
        print "DELETE: ", rel
        rel.delete()
        return HttpResponseRedirect(reverse('dictionary:admin_gloss_view', kwargs={'pk': gloss.id}))
    elif what == 'relationrole':
        rel.role = value
        rel.save()
        newvalue = rel.get_role_display()
    elif what == 'relationtarget':

        target = gloss_from_identifer(value)
        if target:
            rel.target = target
            rel.save()
            newvalue = str(target)
        else:
            return HttpResponseBadRequest("Badly formed gloss identifier '%s'" % value, {'content-type': 'text/plain'})
    else:

        return HttpResponseBadRequest("Unknown form field '%s'" % field, {'content-type': 'text/plain'})

    return HttpResponse(newvalue, {'content-type': 'text/plain'})

def gloss_from_identifier(value):
    """Given an id of the form idgloss (pk) return the
    relevant gloss or None if none is found"""

    match = re.match('(.*) \((\d+)\)', value)
    if match:
        print "MATCH: ", match
        idgloss = match.group(1)
        pk = match.group(2)
        print "INFO: ", idgloss, pk

        target = Gloss.objects.get(pk=int(pk))
        print "TARGET: ", target
        return target
    else:
        return None

def update_definition(request, gloss, field, value):
    """Update one of the definition fields"""

    (what, defid) = field.split('_')
    try:
        defn = Definition.objects.get(id=defid)
    except:
        return HttpResponseBadRequest("Bad Definition ID '%s'" % defid, {'content-type': 'text/plain'})

    if not defn.gloss == gloss:
        return HttpResponseBadRequest("Definition doesn't match gloss", {'content-type': 'text/plain'})

    if what == 'definitiondelete':
        defn.delete()
        return HttpResponseRedirect(reverse('dictionary:admin_gloss_view', kwargs={'pk': gloss.id})+'?editdef')

    if what == 'definition':
        # update the definition
        defn.text = value
        defn.save()
        newvalue = defn.text
    elif what == 'definitioncount':
        defn.count = int(value)
        defn.save()
        newvalue = defn.count
    elif what == 'definitionpub':

        if request.user.has_perm('dictionary.can_publish'):
            defn.published = value == 'Yes'
            defn.save()

        if defn.published:
            newvalue = 'Yes'
        else:
            newvalue = 'No'
    elif what == 'definitionrole':
        defn.role = value
        defn.save()
        newvalue = defn.get_role_display()

    return HttpResponse(newvalue, {'content-type': 'text/plain'})

def add_region(request, glossid):
    """Add a new region to a gloss"""

    if request.method == "POST":
        # Get the data, don't use a form it just adds overhead
        gloss = get_object_or_404(Gloss, id=glossid)
        dialect = get_object_or_404(Dialect, id=request.POST['dialect'])
        frequency = request.POST['frequency']
        if 'traditional' in request.POST and request.POST['traditional'] == "1":
            traditional = True
        else:
            traditional = False

        # Make sure there isn't already a dialect of this type
        if gloss.dialect.filter(name=dialect.name):
            return HttpResponseRedirect(reverse('dictionary:admin_gloss_view', kwargs={'pk': glossid})+'?editrel&error=DialectExists#regions')

        region = Region(gloss=gloss, dialect=dialect, frequency=frequency, traditional=traditional)
        region.save()

        return HttpResponseRedirect(reverse('dictionary:admin_gloss_view', kwargs={'pk': glossid})+'?editrel#regions')

def add_relation(request):
    """Add a new relation instance"""

    if request.method == "POST":

        form = RelationForm(request.POST)
        if form.is_valid():

            role = form.cleaned_data['role']
            sourceid = form.cleaned_data['sourceid']
            targetid = form.cleaned_data['targetid']

            try:
                source = Gloss.objects.get(pk=int(sourceid))
            except:
                return HttpResponseBadRequest("Source gloss not found.", {'content-type': 'text/plain'})

            target = gloss_from_identifier(targetid)
            if target:
                rel = Relation(source=source, target=target, role=role)
                rel.save()

                return HttpResponseRedirect(reverse('dictionary:admin_gloss_view', kwargs={'pk': source.id})+'?editrel#relations')
            else:
                return HttpResponseBadRequest("Target gloss not found.", {'content-type': 'text/plain'})
        else:
            print form

    # fallback to redirecting to the requesting page
    return HttpResponseRedirect('/')

def add_definition(request, glossid):
    """Add a new definition for this gloss"""

    thisgloss = get_object_or_404(Gloss, id=glossid)

    if request.method == "POST":
        form = DefinitionForm(request.POST)

        if form.is_valid():

            count = form.cleaned_data['count']
            role = form.cleaned_data['role']
            text = form.cleaned_data['text']

            # create definition, default to not published
            defn = Definition(gloss=thisgloss, count=count, role=role, text=text, published=False)
            defn.save()

    return HttpResponseRedirect(reverse('dictionary:admin_gloss_view', kwargs={'pk': thisgloss.id})+'?editdef')

@permission_required('dictionary.change_gloss')
def add_tag(request, glossid):
    """View to add a tag to a gloss"""

    # default response
    response = HttpResponse('invalid', {'content-type': 'text/plain'})

    if request.method == "POST":
        thisgloss = get_object_or_404(Gloss, id=glossid)

        form = TagUpdateForm(request.POST)
        if form.is_valid():

            tag = form.cleaned_data['tag']

            if form.cleaned_data['delete']:
                # get the relevant TaggedItem
                ti = get_object_or_404(TaggedItem, object_id=thisgloss.id, tag__name=tag)
                ti.delete()
                response = HttpResponse('deleted', {'content-type': 'text/plain'})
            else:
                # we need to wrap the tag name in quotes since it might contain spaces
                Tag.objects.add_tag(thisgloss, '"%s"' % tag)
                # response is new HTML for the tag list and form
                response = render_to_response('dictionary/glosstags.html',
                                              {'gloss': thisgloss,
                                               'tagform': TagUpdateForm(),
                                               },
                                              context_instance=RequestContext(request))
        else:
            print "invalid form"
            print form.as_table()

    return response


text:
<!DOCTYPE html>

    <title>Tinkerlist</title>
    <link rel="stylesheet" href="main.css">


text:
<?php

namespace TripSorter;

use TripSorter\Business\BoardingCard;

class Trip implements Business\Trip
{

    /**
     * Flag if it is sorted
     * @var bool
     */
    private $isSorted;

    /**
     * @var array
     */
    private $boardingCards;

    /**
     * Sort a boarding cards
     */
    private function sort()
    {
        $boardingCards = $this->boardingCards;
        $sorted = [array_pop($boardingCards)];

        for ($i = count($boardingCards); $i > 0; $i--) {
            foreach ($boardingCards as $key => $boardingCard) {
                if (end($sorted)->to()->equals($boardingCard->from())) {
                    array_push($sorted, $boardingCard);
                    unset($boardingCards[$key]);

                } elseif (reset($sorted)->from()->equals($boardingCard->to())) {
                    array_unshift($sorted, $boardingCard);
                    unset($boardingCards[$key]);
                }
            }
        }

        if (count($boardingCards) > 0) {
            throw new \DomainException("Wrong Boarding cards provided");
        }

        $this->isSorted = true;
        $this->boardingCards = $sorted;
    }

    /**
     * {@inheritdoc}
     */
    public function addBoardingCard(BoardingCard $boardingCard) : bool
    {
        $this->isSorted = false;
        $this->boardingCards[] = $boardingCard;
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function describe() : string
    {
        if (!$this->isSorted) {
            $this->sort();
        }

        $describe = array_map(function(BoardingCard $boardingCard) {
            return $boardingCard->describe();
        }, $this->boardingCards);

        $describe[] = "You have arrived at your final destination.";
        return implode("\n", $describe);
    }

}


text:
app.controller('webModelerController', ['$scope', 'webModelerExampleService', '$timeout',
        function ($scope, exampleService, $timeout) {

            (function init() {

                $scope.test = "test입니다.";
                $scope.modelData = null; //exampleService.getExample(); //null; //{'cells': []};
            })();

            $scope.$on('test_RESPONSE_SAVE_JSON_AT_WEB_MODELER', function(event, data) {
                console.log('test_RESPONSE_SAVE_JSON_AT_WEB_MODELER: ', data);
            });

            $scope.$on('test_OPEN_POPUP_AT_WEB_MODELER', function(event, data) {
                console.log('test_OPEN_POPUP_AT_WEB_MODELER', data);
            })

            $scope.onSave = function() {
                $scope.$broadcast('test_REQUEST_SAVE_JSON_AT_WEB_MODELER');
            }

            // UPDATE_CELL_AT_WEB_MODELER

        }
    ]);


text:
class Plugins::CamaleonUserTag::FrontController < CamaleonCms::Apps::PluginsFrontController
  include Plugins::CamaleonUserTag::MainHelper
  def index
    # actions for frontend module
  end

  # add custom methods below
end


text:
'use strict';

describe('Service: tags', function () {

  // load the service's module
  beforeEach(module('libraryboxApp'));

  // instantiate service
  var tags;
  beforeEach(inject(function (Tags) {
    tags = Tags;
  }));

  it('should do something', function () {
    expect(!!tags).toBe(true);
  });

});


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 297028 $ -->
<refentry xmlns="http://docbook.org/ns/docbook" xml:id="function.pdf-add-outline">
 <refnamediv>
  <refname>PDF_add_outline</refname>
  <refpurpose>Add bookmark for current page [deprecated]</refpurpose>
 </refnamediv>
 <refsect1 role="description">
  &reftitle.description;
  <para>
   This function is deprecated, use <function>PDF_create_bookmark</function>
   instead.
  </para>
 </refsect1>
</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
/*
 * Axamit, gc.support@axamit.com
 */

package com.axamit.gc.core.services.impl;

import com.axamit.gc.api.GCContext;
import com.axamit.gc.api.dto.*;
import com.axamit.gc.api.services.GCContentApi;
import com.axamit.gc.api.services.GCContentNewApi;
import com.axamit.gc.core.exception.GCException;
import com.axamit.gc.core.pojo.FieldMappingProperties;
import com.axamit.gc.core.pojo.ImportItem;
import com.axamit.gc.core.pojo.ImportResultItem;
import com.axamit.gc.core.pojo.MappingType;
import com.axamit.gc.core.services.AbstractPageModifier;
import com.axamit.gc.core.services.GCPageModifier;
import com.axamit.gc.core.services.plugins.GCPluginManager;
import com.axamit.gc.core.services.plugins.GCPlugin;
import com.axamit.gc.core.sightly.models.MapperModel;
import com.axamit.gc.core.util.Constants;
import com.axamit.gc.core.util.GCStringUtil;
import com.axamit.gc.core.util.GCUtil;
import com.axamit.gc.core.util.ResourceResolverUtil;
import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.PageManager;
import com.google.common.collect.ImmutableList;
import org.apache.commons.lang3.StringUtils;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.ModifiableValueMap;
import org.apache.sling.api.resource.PersistenceException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.resource.ResourceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * The <tt>GCItemCreator</tt> interface provides methods to create items in GatherContent.
 *
 * @author Axamit, gc.support@axamit.com
 */
@Service(value = GCPageModifier.class)
@Component(description = "GC Page Modifier Service", name = "GC Page Modifier", immediate = true, metatype = true)
public final class GCPageModifierImpl extends AbstractPageModifier implements GCPageModifier {

    private static final Logger LOGGER = LoggerFactory.getLogger(GCPageModifierImpl.class);

    @Reference
    private ResourceResolverFactory resourceResolverFactory;

    @Reference
    private GCContentApi gContentApi;

    @Reference
    private GCContentNewApi gcContentNewApi;

    @Reference
    private GCPluginManager gcPluginManager;

    private static GCItem createGCItem(final Integer projectId, final MapperModel mapperModel, final String folderUuid,
                                       final String name) {
        GCItem gcItem = new GCItem();
        if (mapperModel != null && MappingType.TEMPLATE == mapperModel.getMappingType()) {
            gcItem.setTemplateId(mapperModel.getTemplateId());
        }
//        if (mapperModel != null) {
//            gcItem.setConfig(mapperModel.getGcGroups());
//        }
        gcItem.setProjectId(projectId);
        gcItem.setFolderUuid(folderUuid);
        gcItem.setName(name);

        return gcItem;
    }

    private static String findOutFolderOrPage(PageManager pageManager, ImportItem importItem) {
        return pageManager.getPage(importItem.getImportPath()) == null ? "folder" : "page";
    }

    private static MapperModel getMapperModel(ResourceResolver resourceResolver, ImportItem importItem) {
        Resource mappingResource = resourceResolver.resolve(importItem.getMappingPath());
        if (mappingResource == null || ResourceUtil.isNonExistingResource(mappingResource)) {
            LOGGER.error("Mapping \"{}\" not found", importItem.getMappingPath());
            return null;
        }
        MapperModel mapperModel = mappingResource.adaptTo(MapperModel.class);
        if (mapperModel == null) {
            LOGGER.error("Can not adapt mapping \"{}\" to model {}", importItem.getMappingPath(),
                    MapperModel.class.getName());
            return null;
        }
        return mapperModel;
    }

    private static void updateGCSpecialPropertiesInAEMPage(ResourceResolver resourceResolver, PageManager pageManager,
                                                           Integer projectId, Integer itemId, ImportItem importItem) {
        ModifiableValueMap modifiableValueMap = pageManager.getPage(importItem.getImportPath()) != null
                ? pageManager.getPage(importItem.getImportPath()).getContentResource().adaptTo(ModifiableValueMap.class)
                : resourceResolver.getResource(importItem.getImportPath()).adaptTo(ModifiableValueMap.class);
        try {
            GCUtil.addGCExportProperties(resourceResolver, modifiableValueMap, projectId,
                    itemId, importItem.getMappingPath() == null ? StringUtils.EMPTY : importItem.getMappingPath());
        } catch (PersistenceException | GCException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    private void updateGCProperty(final GCItem gcItem, final Page page, final String key,
                                  final FieldMappingProperties fieldMappingProperties,
                                  final ResourceResolver resourceResolver, final String configurationPath, final GCContext gcContext) {
        GCContent gcContent = findContentByKey(gcItem, key);
        if (gcContent != null) {
            if (!fieldMappingProperties.getPath().isEmpty()) {
                for (String relativePropertyPath : fieldMappingProperties.getPath()) {
                    if (!ResourceUtil.isNonExistingResource(resourceResolver.resolve(
                            GCStringUtil.appendNewLevelToPath(page.getPath(), relativePropertyPath)))) {
                        String fullPath = GCStringUtil.appendNewLevelToPath(page.getPath(), relativePropertyPath);
                        String propertyPath = GCStringUtil.getRelativeNodePathFromPropertyPath(fullPath);
                        String propertyValue = GCStringUtil.getPropertyNameFromPropertyPath(fullPath);

                        try {
                            GCPlugin gcPlugin = gcPluginManager.getPlugin(resourceResolver, configurationPath,
                                    gcContent.getType().getValue(), StringUtils.EMPTY, fieldMappingProperties.getPlugin());
                            if (isNewEditorMultifieldElement(gcContext, gcContent)) {
                                //TODO
//                                gcContent.setType(GCElementType.MULTIVALUE_NEW_EDITOR);
                            }
                            if (gcPlugin != null) {
                                gcPlugin.transformFromAEMtoGC(resourceResolver, page, gcContent, propertyPath, propertyValue);
                            }
                        } catch (Exception e) {
                            LOGGER.error(e.getMessage(), e);
                        }
                        break;
                    }
                }
            } else if (gcItem.getTemplateId() == null) {
                if (GCElementType.TEXT.equals(gcContent.getType())) {
                    gcContent.setText(StringUtils.EMPTY);
                } /*else if (GCElementType.SECTION.equals(gcContent.getType())) {*/
                    //TODO
//                    gcContent.setSubtitle(StringUtils.EMPTY);
//                }
            }
        }
    }

    private boolean isNewEditorMultifieldElement(GCContext gcContext, GCContent gcContent) {
        GCElementType elementType = gcContent.getType();
        return (GCElementType.CHOICE_CHECKBOX.equals(elementType) || GCElementType.CHOICE_RADIO.equals(elementType));
    }

    /**
     * @inheritDoc
     */
    @Override
    public List<ImportResultItem> createPage(final List<ImportItem> importItemsToMerge, final GCContext gcContext,
                                             final List<ImportItem> childrenItems, final Integer projectId) {
        ResourceResolver resourceResolver = null;
        try {
            resourceResolver = getPageCreatorResourceResolver();
            PageManager pageManager = resourceResolver.adaptTo(PageManager.class);
            GCItem gcItem = createMergedGCItem(importItemsToMerge, projectId, resourceResolver, pageManager, gcContext);
            if (gcItem != null) { //! Else? I would log and early break/return
                Integer createdItemId = gcContentNewApi.createItem(gcItem, gcContext);
                if (createdItemId != null) { //! Else? I would log and early break/return
                    GCStatus statusData = new GCStatus();
                    if (!importItemsToMerge.isEmpty() && importItemsToMerge.get(0).getNewStatusData().getId() != null
                            && gContentApi.updateItemStatus(gcContext, createdItemId,
                            importItemsToMerge.get(0).getNewStatusData().getId())) {
                        statusData = importItemsToMerge.get(0).getNewStatusData();
                    } else {
                        List<GCStatus> gcStatusList = gContentApi.statusesByProjectId(gcContext, projectId);
                        for (GCStatus gcStatus : gcStatusList) {
                            if (gcStatus.getIsDefault()) {
                                statusData = gcStatus;
                                break;
                            }
                        }
                    }
                    for (ImportItem childItem : childrenItems) {
                        childItem.setGcTargetItemId(createdItemId);
                    }
                    ImmutableList.Builder<ImportResultItem> importResultItemList = ImmutableList.builder();
                    for (ImportItem importItem : importItemsToMerge) {
                        updateGCSpecialPropertiesInAEMPage(resourceResolver, pageManager, gcItem.getProjectId(),
                                createdItemId, importItem);
                        final ImportResultItem importResultItem = new ImportResultItem(statusData.getName(),
                                gcItem.getName(),
                                importItem.getAemTitle(),
                                ImportResultItem.IMPORTED,
                                importItem.getTemplate(),
                                //! OSGI configurable mask like "https://{0}.gathercontent.com/item/" would be great.
                                "https://" + importItem.getSlug() + ".gathercontent.com/item/" + createdItemId,
                                importItem.getImportPath(),
                                statusData.getColor(),
                                gcItem.getPosition(),
                                createdItemId,
//                                gcItem.getParentId(),
                                "0",
                                importItem.getImportIndex(),
                                importItem.getMappingName());
                        importResultItemList.add(importResultItem.setType(findOutFolderOrPage(pageManager, importItem)));
                    }
                    return importResultItemList.build();
                }
            }
        } catch (LoginException e) {
            LOGGER.error("Failed to get ServiceResourceResolver {}", e.getMessage());
        } catch (GCException e) {
            LOGGER.error("Failed to get get data from GC {}", e.getMessage());
        } catch (Exception e) {
            LOGGER.error("Failed to export AEM page {}", e.getMessage());
        } finally {
            if (resourceResolver != null && resourceResolver.isLive()) {
                resourceResolver.close();
            }
        }

        ImmutableList.Builder<ImportResultItem> importResultItemList = ImmutableList.builder();
        for (ImportItem importItem : importItemsToMerge) {
            LOGGER.error("Couldn't export AEM page {}", importItem.getImportPath());
            importResultItemList.add(new ImportResultItem().setImportStatus(ImportResultItem.NOT_IMPORTED)
                    .setGcTemplateName(importItem.getTemplate()).setAemLink(importItem.getImportPath())
                    .setAemTitle(importItem.getAemTitle()).setImportIndex(importItem.getImportIndex()));
        }
        return importResultItemList.build();
    }

    private GCItem createMergedGCItem(final Iterable<ImportItem> importItemsToMerge, final Integer projectId,
                                      final ResourceResolver resourceResolver, final PageManager pageManager, final GCContext gcContext) {
        GCItem gcItem = null;
        for (ImportItem importItem : importItemsToMerge) {
            if (importItem.getMappingPath() != null) {
                Page page = pageManager.getPage(importItem.getImportPath());
                MapperModel mapperModel = getMapperModel(resourceResolver, importItem);
                if (mapperModel != null) {
                    Map<String, FieldMappingProperties> mapping = mapperModel.getMapper();
                    importItem.setMappingName(mapperModel.getMappingName());
                    String pluginConfigPath = mapperModel.getPluginConfigPath();
                    //! First-time create in loop?
                    if (gcItem == null) {
                        //TODO
//                        gcItem =
//                                createGCItem(projectId, mapperModel, importItem.getFolderUuid(), importItem.getTitle());
                    }
                    if (mapping != null && page != null) {
                        for (Map.Entry<String, FieldMappingProperties> mapEntry : mapping.entrySet()) {
                            updateGCProperty(gcItem, page, mapEntry.getKey(), mapEntry.getValue(), resourceResolver,
                                    pluginConfigPath, gcContext);
                        }
                    } else {
                        LOGGER.error("No mapped properties in the mapping \"{}\"", importItem.getMappingPath());
                        //! Break/return?
                    }
                }
            } else {
                //! Overwrite in loop?

                //TODO
//                gcItem = createGCItem(projectId, null, importItem.getFolderUuid(), importItem.getTitle());
            }
        }
        return gcItem;
    }

    /**
     * @inheritDoc
     */
    @Override
    public ImportResultItem updatePage(final GCContext gcContext, final ImportItem importItem) {
        ResourceResolver resourceResolver = null;
        String mappingName = null;
        try {
            resourceResolver = getPageCreatorResourceResolver();
            PageManager pageManager = resourceResolver.adaptTo(PageManager.class);
            Page page = pageManager.getPage(importItem.getImportPath());

            MapperModel mapperModel = getMapperModel(resourceResolver, importItem);
            if (mapperModel != null) { //! Else? I would log and early break/return
                String pluginConfigPath = mapperModel.getPluginConfigPath();
                Map<String, FieldMappingProperties> mapping = mapperModel.getMapper();
                mappingName = mapperModel.getMappingName();

                GCItem gcItem = gcContentNewApi.itemById(gcContext, importItem.getItemId());

                if (gcItem != null) {
                    if (mapping == null) {
                        LOGGER.error("No mapped properties in the mapping \"{}\"", importItem.getMappingPath());
                        //! Break/return?
                    } else {
                        for (Map.Entry<String, FieldMappingProperties> mapEntry : mapping.entrySet()) {
                            updateGCProperty(gcItem, page, mapEntry.getKey(), mapEntry.getValue(),
                                    resourceResolver, pluginConfigPath, gcContext);
                        }
                    }
//TODO
//                    Boolean isUpdatedSuccessfully = gcContentNewApi.updateItem(gcItem.getConfig(), gcItem.getId(), gcContext);
                    boolean isUpdatedSuccessfully = false;

                    if (isUpdatedSuccessfully) {
                        boolean updateItemStatus = false;
                        if (importItem.getNewStatusData().getId() != null) {
                            updateItemStatus = gContentApi
                                    .updateItemStatus(gcContext, gcItem.getId(), importItem.getNewStatusData().getId());
                        }
                        //TODO
//                        final GCData statusData =
//                                updateItemStatus ? importItem.getNewStatusData() : gcItem.getStatus().getData();
//                        updateGCSpecialPropertiesInAEMPage(resourceResolver, pageManager, gcItem.getProjectId(),
//                                gcItem.getId(), importItem);
//                        return new ImportResultItem(statusData.getName(),
//                                gcItem.getName(),
//                                page.getTitle(),
//                                ImportResultItem.IMPORTED,
//                                importItem.getTemplate(),
//                                //! OSGI configurable mask like "https://{0}.gathercontent.com/item/" would be great.
//                                "https://" + importItem.getSlug() + ".gathercontent.com/item/" + gcItem.getId(),
//                                importItem.getImportPath(),
//                                statusData.getColor(),
//                                gcItem.getPosition(),
//                                gcItem.getId(),
//                                gcItem.getParentId(),
//                                importItem.getImportIndex(),
//                                mappingName);
                        return null;
                    } else {
                        LOGGER.error("Couldn't update item {}", importItem.getItemId());
                        //TODO
                        return null;
//                        return new ImportResultItem(null,
//                                null,
//                                null,
//                                ImportResultItem.NOT_IMPORTED,
//                                importItem.getTemplate(),
//                                "https://" + importItem.getSlug() + ".gathercontent.com/item/" + gcItem.getId(),
//                                importItem.getImportPath(),
//                                null,
//                                gcItem.getPosition(),
//                                gcItem.getId(),
//                                gcItem.getParentId(),
//                                importItem.getImportIndex(),
//                                mappingName);
                    }
                }
            }
        } catch (LoginException e) {
            LOGGER.error("Failed to get ServiceResourceResolver {}", e.getMessage());
        } catch (GCException e) {
            LOGGER.error("Failed to get get data from GC {}", e.getMessage());
        } catch (Exception e) {
            LOGGER.error("Failed to export update AEM page {}", e.getMessage());
        } finally {
            if (resourceResolver != null && resourceResolver.isLive()) {
                resourceResolver.close();
            }
        }
        LOGGER.error("Couldn't update item {}", importItem.getItemId());
        return new ImportResultItem(null, null, null, ImportResultItem.NOT_IMPORTED, importItem.getTemplate(),
                null, importItem.getImportPath(), null, null, null, null, importItem.getImportIndex(), mappingName);
    }

    private ResourceResolver getPageCreatorResourceResolver() throws LoginException {
        return ResourceResolverUtil.getResourceResolver(resourceResolverFactory,
                Constants.PAGE_CREATOR_SUBSERVICE_NAME);
    }
}