text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.compute.models;

import com.azure.core.util.ExpandableStringEnum;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.Collection;

/**
 * Specifies the priority for a standalone virtual machine or the virtual machines in the scale set.
 *

 'Low' enum will be deprecated in the future, please use 'Spot' as the enum to deploy Azure Spot
 * VM/VMSS.
 */
public final class VirtualMachinePriorityTypes extends ExpandableStringEnum<VirtualMachinePriorityTypes> {
    /** Static value Regular for VirtualMachinePriorityTypes. */
    public static final VirtualMachinePriorityTypes REGULAR = fromString("Regular");

    /** Static value Low for VirtualMachinePriorityTypes. */
    public static final VirtualMachinePriorityTypes LOW = fromString("Low");

    /** Static value Spot for VirtualMachinePriorityTypes. */
    public static final VirtualMachinePriorityTypes SPOT = fromString("Spot");

    /**
     * Creates or finds a VirtualMachinePriorityTypes from its string representation.
     *
     * @param name a name to look for.
     * @return the corresponding VirtualMachinePriorityTypes.
     */
    @JsonCreator
    public static VirtualMachinePriorityTypes fromString(String name) {
        return fromString(name, VirtualMachinePriorityTypes.class);
    }

    /**
     * Gets known VirtualMachinePriorityTypes values.
     *
     * @return known VirtualMachinePriorityTypes values.
     */
    public static Collection<VirtualMachinePriorityTypes> values() {
        return values(VirtualMachinePriorityTypes.class);
    }
}


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

#nullable disable

extern alias InteractiveHost;

using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.VisualStudio.Text.Editor;
using System;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.VisualStudio.InteractiveWindow;
using System.Collections.Generic;
using InteractiveHost::Microsoft.CodeAnalysis.Interactive;
using Microsoft.VisualStudio.Utilities;
using Microsoft.VisualStudio.Language.Intellisense.Utilities;
using Microsoft.CodeAnalysis.Interactive;
using Microsoft.CodeAnalysis.Options;

namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Interactive.Commands
{
    internal class TestResetInteractive : ResetInteractive
    {
        private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor;

        private readonly bool _buildSucceeds;

        internal int BuildProjectCount { get; private set; }

        internal int CancelBuildProjectCount { get; private set; }

        internal ImmutableArray<string> References { get; set; }

        internal ImmutableArray<string> ReferenceSearchPaths { get; set; }

        internal ImmutableArray<string> SourceSearchPaths { get; set; }

        internal ImmutableArray<string> ProjectNamespaces { get; set; }

        internal ImmutableArray<string> NamespacesToImport { get; set; }

        internal InteractiveHostPlatform? Platform { get; set; }

        internal string ProjectDirectory { get; set; }

        public TestResetInteractive(
            IUIThreadOperationExecutor uiThreadOperationExecutor,
            EditorOptionsService editorOptionsService,
            Func<string, string> createReference,
            Func<string, string> createImport,
            bool buildSucceeds)
            : base(editorOptionsService, createReference, createImport)
        {
            _uiThreadOperationExecutor = uiThreadOperationExecutor;
            _buildSucceeds = buildSucceeds;
        }

        protected override void CancelBuildProject()
        {
            CancelBuildProjectCount++;
        }

        protected override Task<bool> BuildProjectAsync()
        {
            BuildProjectCount++;
            return Task.FromResult(_buildSucceeds);
        }

        protected override bool GetProjectProperties(
            out ImmutableArray<string> references,
            out ImmutableArray<string> referenceSearchPaths,
            out ImmutableArray<string> sourceSearchPaths,
            out ImmutableArray<string> projectNamespaces,
            out string projectDirectory,
            out InteractiveHostPlatform? platform)
        {
            references = References;
            referenceSearchPaths = ReferenceSearchPaths;
            sourceSearchPaths = SourceSearchPaths;
            projectNamespaces = ProjectNamespaces;
            projectDirectory = ProjectDirectory;
            platform = Platform;
            return true;
        }

        protected override IUIThreadOperationExecutor GetUIThreadOperationExecutor()
        {
            return _uiThreadOperationExecutor;
        }

        protected override Task<IEnumerable<string>> GetNamespacesToImportAsync(IEnumerable<string> namespacesToImport, IInteractiveWindow interactiveWindow)
        {
            return Task.FromResult((IEnumerable<string>)NamespacesToImport);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
// This file is automatically generated.

package adila.db;

/*
 * LG Optimus F6
 *
 * DEVICE: f6
 * MODEL: LG-D500
 */
final class f6_lg2dd500 {
    public static final String DATA = "LG|Optimus F6|";
}


text:
<?php
/**
* Provides an API to access PHPDoc XML files.
*
* It's up to you eigther to use this class to access
* the phpdoc xml files or to write your own parser.
*
* @version  $Id: PhpdocAccessor.php,v 1.1 2001/05/08 04:48:35 sbergmann Exp $
*/
class PhpdocAccessor extends PhpdocObject {

    /**
    * Instance of PhpdocXMLReader
    * @var  object  PhpdocXMLReader $xmlreader
    */
    var $xmlreader;

    /**
    * Result of the PhpdocXMLReader
    * @var    array    $xml
    */
    var $xml = array();

    /**
    * Free xml resources on calling a getXY() function?
    *
    * One of the design goals was to minimize the memory consumption of PHPdoc.
    * So PHPdoc tries to save data as soon as possible to the disk, reuse objects
    * and free resources of an object when they are no longer needed. The default
    * value of true will cause the object to free the memory used by the
    * xml data as soon as possible.
    *
    * @var  boolean
    */
    var $freeOnGet = true;

    /**
    * Reformatted PhpdocXMLReader result array
    * @var  array
    */
    var $data = array();

    /**
    * Loads the specified xml file.
    *
    * @param    string  Name of the xml file
    * @return   boolean False if the given xml file was not
    *                   found or is empty otherwise true.
    * @access   public
    * @see      init()
    */
    function loadXMLFile($filename) {

        $this->xmlreader = new PhpdocXMLReader;

        $this->xml = $this->xmlreader->parse($filename);
        $this->xml = $this->xml["phpdoc"];
        $ok = (!is_array($this->xml) || 0 == count($this->xml)) ? false : true;

        $this->init();

        return $ok;
    } // end func loadXMLFile

    /**
    * Reformats the xml result array from the PhpdocXMLReader.
    *
    * Every derived class must override this function to call the functions
    * it needs to reorganize the data from the PhpdocXMLReader in a
    * way that it needs.
    *
    * @abstract
    * @see    $xml, $data
    */
    function init() {
    } // end func init

} // end class PhpdocAccessor
?>


text:
import {Poll, PartialPoll} from "./poll.models";
import {Action} from "@ngrx/store";
export interface PollsState {
  ids: string[],
  entities: { [id: string]: Poll };
}

export const PollsActions = {
  LOAD_POLL: '[Polls] loadPoll',
  POLL_LOADED: '[Polls] pollLoaded',
  CREATE_POLL: '[Polls] createPoll',
  POLL_CREATED: '[Polls] pollCreated'
};

export class LoadPollAction implements Action {
  public readonly type = PollsActions.LOAD_POLL;

  constructor(public readonly payload: string) {}
}

export class PollLoadedAction implements Action {
  public readonly type = PollsActions.POLL_LOADED;

  constructor(public readonly payload: Poll) {}
}

export class CreatePollAction implements Action {
  public readonly type = PollsActions.CREATE_POLL;

  constructor(public readonly payload: PartialPoll) {}
}

export class PollCreatedAction implements Action {
  public readonly type = PollsActions.POLL_CREATED;

  constructor(public readonly payload: Poll) {}
}

export const getPollIds = (state: PollsState) => state.ids;

export const getPollEntities = (state: PollsState) => state.entities;


text:
    <form id="project1">
        Project Name

        <input id="projectName" type="text" value="name" disabled />

        Project Number

        <input id="projectNumber" type="text" value="number" disabled />

        Project Location

        <input id="projectLocation" type="text" value="number" />

        Project Description

        <textarea id="projectDescription">description</textarea>

        <button id="save1">save1 all</button>
    </form>


text:
package tk.roaimsapp.centrefinder;

import android.content.Context;
import android.database.Cursor;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;
import android.util.Log;

/**
 * Created by Roaim on 14-Dec-15.
 */
public class SettingAdapter extends CursorAdapter {
    public final int mPosition;

    public SettingAdapter(Context context, DataHelper dbhelper, int position) {
        super(context, dbhelper.getCursor(position), false);
        mPosition = position;
				lg("adaptr position"+position);
    }
		/*
		public int[] getPlanIds(int position){
				int[] ids = new int[3];
				Cursor c= getCursor();
				c.moveToPosition(position);
				ids[0]=c.getInt(1);
				ids[1]=c.getInt(2);
				ids[2]=c.getInt(3);
				return ids;
		}
*/
		@Override
		public long getItemId ( int position ) {
				// TODO: Implement this method
				Cursor c = getCursor();
				c.moveToPosition(position);
				return c.getLong(0);
		}

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View v = null;
        switch (mPosition){
            case 0:{
								v=View.inflate ( context, R.layout.viewlist_centre, null );
						} break;
						case 1:{
								v=View.inflate ( context, R.layout.viewlist_roll, null );
						} break;
						case 2:{
								v=View.inflate ( context, R.layout.viewlist_group, null );
						} break;
						case 3:{
								//seat plan
								v = View.inflate(context,R.layout.viewlist_plan,null);
						}
        }
        return v;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        setTvText(view, mPosition,cursor);
    }

		private void setTvText ( View v,int argument,Cursor c ) {
				// TODO: Implement this method
				TextView tv1,tv2,tv3;
				int id1 = 0,id2 = 0;
				switch(argument){
						case 0:{
								id1=R.id.textViewCentre;
								id2=R.id.textViewAddress;
						} break;
						case 1:{
								id1=R.id.viewlistrollTextViewStart;
								id2=R.id.viewlistrollTextViewEnd;
						} break;
						case 2:{
								id1=R.id.viewlistgroupTextViewGroup;
								id2=R.id.viewlistgroupTextViewTime;
						} break;
						case 3 :{
								tv1 = getTv ( v, R.id.viewlistplanTextView1 );
								tv2 = getTv ( v, R.id.viewlistplanTextView2 );
								tv3 = getTv(v,R.id.viewlistplanTextView3);
								tv1.setText(c.getString(1));
								tv2.setText(c.getString(2));
								tv3.setText(c.getString(3));
								return;
						}
				}
				tv1 = getTv ( v, id1 );
				tv2 = getTv ( v, id2 );
				tv1.setText(c.getString(1));
				tv2.setText(c.getString(2));
		}

		private TextView getTv(View v,int id){
				return (TextView)v.findViewById(id);
		}
		private void lg ( String p0 ) {
				Log.i("rah",p0);
		}
}


text:
@interface PodsDummy_Pods_Holarchy_Tests : NSObject
@end
@implementation PodsDummy_Pods_Holarchy_Tests
@end


text:
{% capture now %}{{ site.time | date: '%x' }}{% endcapture %}

    {% for item in site.categories.event limit:2 %}
    {% capture date %}{{ item.date | date: '%B %Y' }}{% endcapture %}
    {% capture ndate %}{{ item.next.date | date: '%B %Y' }}{% endcapture %}

    {% assign delimiter = ' - ' %}
      {% capture verifydate %}{{ item.eventdate | date: '%x' }}{% endcapture %}
      {% capture verifydate %}{{ verifydate | replace: delimiter, ' ' }}{% endcapture %}
      {% capture myFirstWord %}{{ verifydate | truncatewords: 1 | remove: '...' }}{% endcapture %}

{{item.eventdate}}

        {% if item.title %}
        {% if myFirstWord < now %}

{{item.title }}

        {% else %}

{{item.title }}

        {% endif %}

        {% endif %}

    {% endfor %}


text:
using Xunit;

namespace Jint.Tests.Ecma
{
    public class Test_12_12 : EcmaTest
    {
        [Fact]
        [Trait("Category", "12.12")]
        public void LabelledStatementsAreOnlyUsedInConjunctionWithLabelledBreakAndContinueStatements()
        {
			RunTest(@"TestCases/ch12/12.12/S12.12_A1_T1.js", false);
        }

    }
}


text:
{%- if site.just-comments -%}

{%- endif -%}


text:
package org.apache.hadoop.mapred.lib.aggregate;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;

/**
 * This class implements a value aggregator that sums up
 * a sequence of long values.
 */
@InterfaceAudience.Public
@InterfaceStability.Stable
public class LongValueSum
    extends org.apache.hadoop.mapreduce.lib.aggregate.LongValueSum
    implements ValueAggregator<String> {
}


text:
using UnityEngine;

namespace Assets.Scripts {
	public class Singleton<T> : MonoBehaviour where T : MonoBehaviour {

		protected static T _instance;
		public static T Instance {
			get {
				if (_instance == null) {
					_instance = FindObjectOfType<T>();
					if (_instance == null) {
						Debug.LogError("No instance of singleton " + typeof(T) + " found!");
					}
				}
				return _instance;
			}
		}

	}
}


text:
import os
import shutil
import unittest

from django import conf
from django.test import TestCase
from django.utils import six
from django.utils._os import upath

@unittest.skipIf(
    six.PY2,
    'Python 2 cannot import the project template because '
    'django/conf/project_template doesn\'t have an __init__.py file.'
)
class TestStartProjectSettings(TestCase):
    def setUp(self):
        # Ensure settings.py exists
        project_dir = os.path.join(
            os.path.dirname(upath(conf.__file__)),
            'project_template',
            'project_name',
        )
        template_settings_py = os.path.join(project_dir, 'settings.py-tpl')
        test_settings_py = os.path.join(project_dir, 'settings.py')
        shutil.copyfile(template_settings_py, test_settings_py)
        self.addCleanup(os.remove, test_settings_py)

    def test_middleware_headers(self):
        """
        Ensure headers sent by the default MIDDLEWARE don't inadvertently
        change. For example, we never want "Vary: Cookie" to appear in the list
        since it prevents the caching of responses.
        """
        from django.conf.project_template.project_name.settings import MIDDLEWARE

        with self.settings(
            MIDDLEWARE=MIDDLEWARE,
            ROOT_URLCONF='project_template.urls',
        ):
            response = self.client.get('/empty/')
            headers = sorted(response.serialize_headers().split(b'\r\n'))
            self.assertEqual(headers, [
                b'Content-Type: text/html; charset=utf-8',
                b'X-Frame-Options: SAMEORIGIN',
            ])


text:
var gulp = require('gulp');
var ghPages = require('gulp-gh-pages');
var paths = require('../config').paths;

// this task runs the build-sfx
// then runs deploy-gh-pages which publishes the ./dist folder to gh-pages branch
gulp.task('deploy-pages', ['deploy-gh-pages']);

// then runs deploy-gh-pages which publishes the ./dist folder to gh-pages branch
gulp.task('deploy-gh-pages', ['production'], function() {
  return gulp.src(paths.dest+'/**/*')
    .pipe(ghPages());
});


text:
'''
generics classes with common base.
'''
class A:
	def __init__(self, x:int):
		let self.x : int = x
		let self.z : int = 0

	def some_subclass( self, o:A, s:bool ) -> self:
		#if s:
		#	## forces the return type to be self, if the result from this method is an assignment
		#	## then a switch is generated, and the function body is put into each case,
		#	## this allow methods to work on the returned instance.
		#	return go.type_assert(o, self)
		#else:
		## TODO fixme
		return self

	def bar(self) -> int:
		return self.x

class B(A):
	def __init__(self):
		A.__init__(self, 10)
		let self.z : int = 1

	def bar(self) ->int:
		#print('calling B.bar')
		#print(self.__class__)
		return self.x + self.z

class C(A):
	def __init__(self):
		A.__init__(self, 100)
		let self.z : int = 100
		let self.w : int = 1

	def bar(self) ->int:
		#print('calling C.bar')
		#print(self.__class__)
		return self.x + self.z + self.w

def my_generic( g:A ) ->int:
	return g.bar()

def main():
	a = A( 1000 )
	b = B()
	c = C()

	assert a.x == a.bar()

	x = my_generic( a )
	assert a.x == x

	y = my_generic( b )
	assert y==11

	z = my_generic( c )
	assert z==201

	assert b.z==1
	assert c.z==100

	## calling a method that has returns multiple subclasses with the result assigned to variable
	## will generate a switch that enables methods
	#w = 0
	## tests returning self
	bb = b.some_subclass(b, false)
	w = bb.bar()
	assert w==y
	cc = c.some_subclass(b, false)
	w = cc.bar()
	assert w==z

	## tests returning the other subclass type
	ccc = b.some_subclass(c, true)
	w = ccc.bar()
	assert w==z

	bbb = c.some_subclass(b, true)
	w = bbb.bar()
	assert w==y

	## Gotchas ##

	## calls B.bar(), my_generic still works when b returns self,
	## if C is returned, then my_generic breaks.
	w = my_generic( b.some_subclass(c, false) )
	#print(w)
	assert w == y

	## reassignment to bb type of *B should be allowed, because this works at runtime, but goc throws an error,
	## because it thinks that c.some_subclass can only return *C, and `bb` above got retyped as *B.
	#bb = c.some_subclass(b, true)
	d = c.some_subclass(b, true)
	w = d.bar()
	assert w==y

	print('----------no panics----------')


text:
@interface WJLrcView : DRNRealTimeBlurView

@property (nonatomic, copy) NSString *lrcname;

@property (nonatomic, assign) NSTimeInterval currentTime;

@end


text:
<!doctype html>

    <title>Code coverage report for lib/waterline/query/adapters.js</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="../../../prettify.css" />
    <link rel="stylesheet" href="../../../base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      all files / lib/waterline/query/ adapters.js

        100%
        Statements
        17/17

        83.33%
        Branches
        10/12

        100%
        Functions
        4/4

        100%
        Lines
        15/15

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

3×
266×

266×

267×

267×

1210×

1131×

324×
116×
116×

208×

5×

5×

5×
5×

/**
 * Mixes Custom Non-CRUD Adapter Methods into the prototype.
 */

module.exports = function() {
  var self = this;

  Object.keys(this.connections).forEach(function(conn) {

    var adapter = self.connections[conn]._adapter || {};

    Object.keys(adapter).forEach(function(key) {

      // Ignore the Identity Property
      if (['identity', 'tableName'].indexOf(key) >= 0) return;

      // Don't override keys that already exists
      if (self[key]) return;

      // Don't override a property, only functions
      if (typeof adapter[key] != 'function') {
        self[key] = adapter[key];
        return;
      }

      // Apply the Function with passed in args and set this.identity as
      // the first argument
      self[key] = function() {

        var tableName = self.tableName || self.identity;

        // If this is the teardown method, just pass in the connection name,
        // otherwise pass the connection and the tableName
        var defaultArgs = key === 'teardown' ? [conn] : [conn, tableName];

        // Concat self.identity with args (must massage arguments into a proper array)
        // Use a normalized _tableName set in the core module.
        var args = defaultArgs.concat(Array.prototype.slice.call(arguments));
        return adapter[key].apply(self, args);
      };
    });
  });

};

  Code coverage
  generated by istanbul at Fri Mar 18 2016 12:26:23 GMT-0500 (CDT)


text:
var app = module.exports = require('railway').createServer();

if (!module.parent) {
    var port = process.env.PORT || 3000
    app.listen(port);
    console.log("Railway server listening on port %d within %s environment", port, app.settings.env);
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DoubleKeyDictionary.cs" company="Helix 3D Toolkit">
//   http://helixtoolkit.codeplex.com, license: MIT
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace HelixToolkit.Wpf
{
    using System;
    using System.Collections;
    using System.Collections.Generic;

    /// <summary>
    /// A double key dictionary.
    /// </summary>
    /// <typeparam name="K">
    /// The first key type.
    /// </typeparam>
    /// <typeparam name="T">
    /// The second key type.
    /// </typeparam>
    /// <typeparam name="V">
    /// The value type.
    /// </typeparam>
    /// <remarks>
    /// See http://noocyte.wordpress.com/2008/02/18/double-key-dictionary/
    /// A Remove method was added.
    /// </remarks>
    public class DoubleKeyDictionary<K, T, V> : IEnumerable<DoubleKeyPairValue<K, T, V>>,
                                                IEquatable<DoubleKeyDictionary<K, T, V>>
    {
        /// <summary>
        /// The m_inner dictionary.
        /// </summary>
        private Dictionary<T, V> m_innerDictionary;

        /// <summary>
        /// Initializes a new instance of the <see cref="DoubleKeyDictionary{K,T,V}"/> class.
        /// </summary>
        public DoubleKeyDictionary()
        {
            this.OuterDictionary = new Dictionary<K, Dictionary<T, V>>();
        }

        /// <summary>
        /// Gets or sets OuterDictionary.
        /// </summary>
        private Dictionary<K, Dictionary<T, V>> OuterDictionary { get; set; }

        /// <summary>
        /// Gets or sets the value with the specified indices.
        /// </summary>
        /// <value></value>
        public V this[K index1, T index2]
        {
            get
            {
                return this.OuterDictionary[index1][index2];
            }

            set
            {
                this.Add(index1, index2, value);
            }
        }

        /// <summary>
        /// Clears this dictionary.
        /// </summary>
        public void Clear()
        {
            OuterDictionary.Clear();
            if (m_innerDictionary!=null)
                m_innerDictionary.Clear();
        }

        /// <summary>
        /// Adds the specified key.
        /// </summary>
        /// <param name="key1">
        /// The key1.
        /// </param>
        /// <param name="key2">
        /// The key2.
        /// </param>
        /// <param name="value">
        /// The value.
        /// </param>
        public void Add(K key1, T key2, V value)
        {
            if (this.OuterDictionary.ContainsKey(key1))
            {
                if (this.m_innerDictionary.ContainsKey(key2))
                {
                    this.OuterDictionary[key1][key2] = value;
                }
                else
                {
                    this.m_innerDictionary = this.OuterDictionary[key1];
                    this.m_innerDictionary.Add(key2, value);
                    this.OuterDictionary[key1] = this.m_innerDictionary;
                }
            }
            else
            {
                this.m_innerDictionary = new Dictionary<T, V>();
                this.m_innerDictionary[key2] = value;
                this.OuterDictionary.Add(key1, this.m_innerDictionary);
            }
        }

        /// <summary>
        /// Determines whether the specified dictionary contains the key.
        /// </summary>
        /// <param name="index1">
        /// The index1.
        /// </param>
        /// <param name="index2">
        /// The index2.
        /// </param>
        /// <returns>
        /// <c>true</c> if the specified index1 contains key; otherwise, <c>false</c>.
        /// </returns>
        public bool ContainsKey(K index1, T index2)
        {
            if (!this.OuterDictionary.ContainsKey(index1))
            {
                return false;
            }

            if (!this.OuterDictionary[index1].ContainsKey(index2))
            {
                return false;
            }

            return true;
        }

        /// <summary>
        /// Equalses the specified other.
        /// </summary>
        /// <param name="other">
        /// The other.
        /// </param>
        /// <returns>
        /// The equals.
        /// </returns>
        public bool Equals(DoubleKeyDictionary<K, T, V> other)
        {
            if (this.OuterDictionary.Keys.Count != other.OuterDictionary.Keys.Count)
            {
                return false;
            }

            bool isEqual = true;

            foreach (var innerItems in this.OuterDictionary)
            {
                if (!other.OuterDictionary.ContainsKey(innerItems.Key))
                {
                    isEqual = false;
                }

                if (!isEqual)
                {
                    break;
                }

                // here we can be sure that the key is in both lists,
                // but we need to check the contents of the inner dictionary
                Dictionary<T, V> otherInnerDictionary = other.OuterDictionary[innerItems.Key];
                foreach (var innerValue in innerItems.Value)
                {
                    if (!otherInnerDictionary.ContainsValue(innerValue.Value))
                    {
                        isEqual = false;
                    }

                    if (!otherInnerDictionary.ContainsKey(innerValue.Key))
                    {
                        isEqual = false;
                    }
                }

                if (!isEqual)
                {
                    break;
                }
            }

            return isEqual;
        }

        /// <summary>
        /// Gets the enumerator.
        /// </summary>
        /// <returns>
        /// </returns>
        public IEnumerator<DoubleKeyPairValue<K, T, V>> GetEnumerator()
        {
            foreach (var outer in this.OuterDictionary)
            {
                foreach (var inner in outer.Value)
                {
                    yield return new DoubleKeyPairValue<K, T, V>(outer.Key, inner.Key, inner.Value);
                }
            }
        }

        /// <summary>
        /// Removes the specified key.
        /// </summary>
        /// <param name="key1">
        /// The key1.
        /// </param>
        /// <param name="key2">
        /// The key2.
        /// </param>
        public void Remove(K key1, T key2)
        {
            this.OuterDictionary[key1].Remove(key2);
            if (this.OuterDictionary[key1].Count == 0)
            {
                this.OuterDictionary.Remove(key1);
            }
        }

        /// <summary>
        /// Returns an enumerator that iterates through a collection.
        /// </summary>
        /// <returns>
        /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
        /// </returns>
        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

    }

    /// <summary>
    /// Represents two keys and a value.
    /// </summary>
    /// <typeparam name="K">
    /// First key type.
    /// </typeparam>
    /// <typeparam name="T">
    /// Second key type.
    /// </typeparam>
    /// <typeparam name="V">
    /// Value type.
    /// </typeparam>
    public class DoubleKeyPairValue<K, T, V>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="DoubleKeyPairValue{K,T,V}"/> class.
        /// </summary>
        /// <param name="key1">
        /// The key1.
        /// </param>
        /// <param name="key2">
        /// The key2.
        /// </param>
        /// <param name="value">
        /// The value.
        /// </param>
        public DoubleKeyPairValue(K key1, T key2, V value)
        {
            this.Key1 = key1;
            this.Key2 = key2;
            this.Value = value;
        }

        /// <summary>
        /// Gets or sets the key1.
        /// </summary>
        /// <value>The key1.</value>
        public K Key1 { get; set; }

        /// <summary>
        /// Gets or sets the key2.
        /// </summary>
        /// <value>The key2.</value>
        public T Key2 { get; set; }

        /// <summary>
        /// Gets or sets the value.
        /// </summary>
        /// <value>The value.</value>
        public V Value { get; set; }

        /// <summary>
        /// Returns a <see cref="System.String"/> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            return this.Key1 + " - " + this.Key2 + " - " + this.Value;
        }

    }
}


text:
[back to README](../README.md)
# Documents
Documents are the root objects for a request body (post, patch) or response body (`Enm\JsonApi\Model\Document\DocumentInterface`).

A document contains "data" (the resources) and can contain meta information, errors, links and related resources ("includes").

## Document Serializer
The document serializer (a class implementing `Enm\JsonApi\Serializer\DocumentSerializerInterface`) is responsible for turning
document objects (and their resources) into a php array in JSON API structure which can be JSON encoded and returned as response.
The default serializer should be a good choice but it's also possible to use a custom serializer.

The default serializer will remove empty "data" if "errors" or "meta" is available. It will also remove empty data in
relationship if "meta" or "links" is available for a relationship.
If empty data should be retained, the serializer offers the option `keepEmptyData` as first constructor argument.

## Document Deserializer
The document deserializer (a class implementing `Enm\JsonApi\Serializer\DocumentDeserializerInterface`) is responsible
for turning php arrays into document objects (and their resources).
The default deserializer should be a good choice but it's also possible to use a custom deserializer.

*****

[prev: Links](../docs/04-links.md) | [back to README](../README.md) | [next: Errors](../docs/06-errors.md)


text:
package org.deeplearning4j.nn.conf;

import lombok.*;
import org.deeplearning4j.nn.conf.graph.GraphVertex;
import org.deeplearning4j.nn.conf.graph.LayerVertex;
import org.deeplearning4j.nn.conf.graph.MergeVertex;
import org.deeplearning4j.nn.conf.inputs.InputType;
import org.deeplearning4j.nn.conf.layers.BaseLayer;
import org.deeplearning4j.nn.conf.layers.BasePretrainNetwork;
import org.deeplearning4j.nn.conf.layers.Layer;
import org.deeplearning4j.nn.conf.layers.OutputLayer;
import org.deeplearning4j.nn.conf.memory.MemoryReport;
import org.deeplearning4j.nn.conf.memory.NetworkMemoryReport;
import org.nd4j.linalg.activations.Activation;
import org.nd4j.linalg.activations.IActivation;
import org.nd4j.shade.jackson.databind.JsonNode;
import org.nd4j.shade.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.Serializable;
import java.util.*;

/**
 * ComputationGraphConfiguration is a configuration object for neural networks with arbitrary connection structure.
 * It is analogous to {@link MultiLayerConfiguration}, but allows considerably greater flexibility for the network
 * architecture.

 * Specifically, the network architecture is a directed acyclic graph, where each vertex in the graph is a {@link GraphVertex},
 * which may for example be a layer or a vertex/object that defines arbitrary forward and backward pass functionality.

 * Note that the ComputationGraph may have an arbitrary number of inputs (multiple independent inputs, possibly of different
 * types), and an arbitrary number of outputs (for example, multiple {@link OutputLayer} instances.
 * Typical usage:

 * {@code ComputationGraphConfiguration conf = new NeuralNetConfiguration.Builder()....graphBuilder()...build();}
 *
 * @author Alex Black
 */
@Data
@EqualsAndHashCode
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@NoArgsConstructor
public class ComputationGraphConfiguration implements Serializable, Cloneable {
    private static Logger log = LoggerFactory.getLogger(ComputationGraphConfiguration.class);

    protected Map<String, GraphVertex> vertices = new LinkedHashMap<>();
    protected Map<String, List<String>> vertexInputs = new LinkedHashMap<>();

    @Getter
    @Setter
    protected WorkspaceMode trainingWorkspaceMode;

    @Getter
    @Setter
    protected WorkspaceMode inferenceWorkspaceMode;

    @Getter
    @Setter
    protected CacheMode cacheMode;

    /**
     * List of inputs to the network, by name
     */
    protected List<String> networkInputs;

    /**
     * List of network outputs, by name
     */
    protected List<String> networkOutputs;

    protected boolean pretrain = false;
    protected boolean backprop = true;
    protected BackpropType backpropType = BackpropType.Standard;
    protected int tbpttFwdLength = 20;
    protected int tbpttBackLength = 20;

    protected NeuralNetConfiguration defaultConfiguration;

    //Counter for the number of parameter updates so far
    // This is important for learning rate schedules, for example, and is stored here to ensure it is persisted
    // for Spark and model serialization
    protected int iterationCount = 0;

    //Counter for the number of epochs completed so far. Used for per-epoch schedules
    protected int epochCount = 0;

    /**
     * @return JSON representation of configuration
     */
    public String toYaml() {
        ObjectMapper mapper = NeuralNetConfiguration.mapperYaml();
        synchronized (mapper) {
            try {
                return mapper.writeValueAsString(this);
            } catch (org.nd4j.shade.jackson.core.JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * Create a neural net configuration from json
     *
     * @param json the neural net configuration from json
     * @return {@link ComputationGraphConfiguration}
     */
    public static ComputationGraphConfiguration fromYaml(String json) {
        ObjectMapper mapper = NeuralNetConfiguration.mapperYaml();
        try {
            return mapper.readValue(json, ComputationGraphConfiguration.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @return JSON representation of computation graph configuration
     */
    public String toJson() {
        //As per MultiLayerConfiguration.toJson()
        ObjectMapper mapper = NeuralNetConfiguration.mapper();
        synchronized (mapper) {
            //JSON mappers are supposed to be thread safe: however, in practice they seem to miss fields occasionally
            //when writeValueAsString is used by multiple threads. This results in invalid JSON. See issue #3243
            try {
                return mapper.writeValueAsString(this);
            } catch (org.nd4j.shade.jackson.core.JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * Create a computation graph configuration from json
     *
     * @param json the neural net configuration from json
     * @return {@link ComputationGraphConfiguration}
     */
    public static ComputationGraphConfiguration fromJson(String json) {
        //As per MultiLayerConfiguration.fromJson()
        ObjectMapper mapper = NeuralNetConfiguration.mapper();
        ComputationGraphConfiguration conf;
        try {
            conf = mapper.readValue(json, ComputationGraphConfiguration.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //To maintain backward compatibility after activation function refactoring (configs generated with v0.7.1 or earlier)
        // Previously: enumeration used for activation functions. Now: use classes
        int layerCount = 0;
        Map<String, GraphVertex> vertexMap = conf.getVertices();
        JsonNode vertices = null;
        for (Map.Entry<String, GraphVertex> entry : vertexMap.entrySet()) {
            if (!(entry.getValue() instanceof LayerVertex)) {
                continue;
            }

            LayerVertex lv = (LayerVertex) entry.getValue();
            if (lv.getLayerConf() != null && lv.getLayerConf().getLayer() != null) {
                Layer layer = lv.getLayerConf().getLayer();

                if (layer instanceof BaseLayer && ((BaseLayer) layer).getActivationFn() == null) {
                    String layerName = layer.getLayerName();

                    try {
                        if (vertices == null) {
                            JsonNode jsonNode = mapper.readTree(json);
                            vertices = jsonNode.get("vertices");
                        }

                        JsonNode vertexNode = vertices.get(layerName);
                        JsonNode layerVertexNode = vertexNode.get("LayerVertex");
                        if (layerVertexNode == null || !layerVertexNode.has("layerConf")
                                        || !layerVertexNode.get("layerConf").has("layer")) {
                            continue;
                        }
                        JsonNode layerWrapperNode = layerVertexNode.get("layerConf").get("layer");

                        if (layerWrapperNode == null || layerWrapperNode.size() != 1) {
                            continue;
                        }

                        JsonNode layerNode = layerWrapperNode.elements().next();
                        JsonNode activationFunction = layerNode.get("activationFunction"); //Should only have 1 element: "dense", "output", etc

                        if (activationFunction != null) {
                            IActivation ia = Activation.fromString(activationFunction.asText()).getActivationFunction();
                            ((BaseLayer) layer).setActivationFn(ia);
                        }

                    } catch (IOException e) {
                        log.warn("Layer with null ActivationFn field or pre-0.7.2 activation function detected: could not parse JSON",
                                        e);
                    }
                }
            }
        }

        return conf;
    }

    @Override
    public String toString() {
        return toJson();
    }

    @Override
    public ComputationGraphConfiguration clone() {
        ComputationGraphConfiguration conf = new ComputationGraphConfiguration();

        conf.vertices = new LinkedHashMap<>();
        for (Map.Entry<String, GraphVertex> entry : this.vertices.entrySet()) {
            conf.vertices.put(entry.getKey(), entry.getValue().clone());
        }

        conf.vertexInputs = new LinkedHashMap<>();
        for (Map.Entry<String, List<String>> entry : this.vertexInputs.entrySet()) {
            conf.vertexInputs.put(entry.getKey(), new ArrayList<>(entry.getValue()));
        }

        conf.networkInputs = new ArrayList<>();

        conf.networkInputs = new ArrayList<>(this.networkInputs);
        conf.networkOutputs = new ArrayList<>(this.networkOutputs);

        conf.pretrain = pretrain;
        conf.backprop = backprop;
        conf.backpropType = backpropType;
        conf.tbpttFwdLength = tbpttFwdLength;
        conf.tbpttBackLength = tbpttBackLength;
        conf.defaultConfiguration = defaultConfiguration.clone();
        conf.trainingWorkspaceMode = trainingWorkspaceMode;
        conf.inferenceWorkspaceMode = inferenceWorkspaceMode;
        conf.cacheMode = this.cacheMode;
        conf.defaultConfiguration.cacheMode = this.cacheMode;

        return conf;
    }

    /**
     * Check the configuration, make sure it is valid
     *
     * @throws IllegalStateException if configuration is not valid
     */
    public void validate() {
        if (networkInputs == null || networkInputs.size() < 1) {
            throw new IllegalStateException(
                            "Invalid configuration: network has no inputs. Use .addInputs(String...) to label (and give an ordering to) the network inputs");
        }
        if (networkOutputs == null || networkOutputs.size() < 1) {
            throw new IllegalStateException(
                            "Invalid configuration: network has no outputs. Use .setOutput(String...) to specify (and give an ordering to) the output vertices");
        }

        //Check uniqueness of names for inputs, layers, GraphNodes
        for (String s : networkInputs) {
            if (vertices.containsKey(s)) {
                throw new IllegalStateException("Invalid configuration: name \"" + s
                                + "\" is present in both network inputs and graph vertices/layers");
            }
        }

        //Check: each layer & node has at least one input
        for (Map.Entry<String, List<String>> e : vertexInputs.entrySet()) {
            String nodeName = e.getKey();
            if (e.getValue() == null || e.getValue().isEmpty()) {
                throw new IllegalStateException("Invalid configuration: vertex \"" + nodeName + "\" has no inputs");
            }
            for (String inputName : e.getValue()) {
                if (!vertices.containsKey(inputName) && !networkInputs.contains(inputName)) {
                    throw new IllegalStateException("Invalid configuration: Vertex \"" + nodeName + "\" has input \""
                                    + inputName + "\" that does not exist");
                }
            }
        }

        //Check output names:
        for (String s : networkOutputs) {
            if (!vertices.containsKey(s)) {
                throw new IllegalStateException(
                                "Invalid configuration: Output name \"" + s + "\" is not a valid vertex");
            }
        }

        //Check for no graph cycles: done in ComputationGraph.init()
    }

    /**
     * Add preprocessors automatically, given the specified types of inputs for the network. Inputs are specified using the
     * {@link InputType} class, in the same order in which the inputs were defined in the original configuration.

     * For example, in a network with two inputs: a convolutional input (28x28x1 images) and feed forward inputs, use
     * {@code .addPreProcessors(InputType.convolutional(1,28,28),InputType.feedForward())}.

     * For the CNN->Dense and CNN->RNN transitions, the nIns on the Dense/RNN layers will also be added automatically.
     * NOTE: This method will be called automatically when using the
     * {@link GraphBuilder#setInputTypes(InputType...)} functionality.
     * See that method for details.
     */
    public void addPreProcessors(InputType... inputTypes) {

        if (inputTypes == null || inputTypes.length != networkInputs.size()) {
            throw new IllegalArgumentException(
                            "Invalid number of InputTypes: cannot add preprocessors if number of InputType "
                                            + "objects differs from number of network inputs");
        }

        //Now: need to do essentially a forward pass through the network, to work out what type of preprocessors to add
        //To do this: need to know what the output types are for each GraphVertex.

        //Do topological sort
        List<String> topologicalOrdering = topologicalOrdering();

        //Now, given the topological sort: do equivalent of forward pass
        Map<String, InputType> vertexOutputs = new HashMap<>();
        int currLayerIdx = -1;
        for (String s : topologicalOrdering) {
            int inputIdx = networkInputs.indexOf(s);
            if (inputIdx != -1) {
                vertexOutputs.put(s, inputTypes[inputIdx]);
                continue;
            }

            GraphVertex gv = vertices.get(s);

            List<InputType> inputTypeList = new ArrayList<>();

            if (gv instanceof LayerVertex) {
                //Add preprocessor, if necessary:
                String in = vertexInputs.get(s).get(0);
                InputType layerInput = vertexOutputs.get(in);
                inputTypeList.add(layerInput);

                LayerVertex lv = (LayerVertex) gv;
                Layer l = lv.getLayerConf().getLayer();

                //Preprocessors - add if necessary
                if (lv.getPreProcessor() == null) {
                    //But don't override preprocessors that are manually defined; if none has been defined,
                    //add the appropriate preprocessor for this input type/layer combination
                    InputPreProcessor preproc = l.getPreProcessorForInputType(layerInput);
                    lv.setPreProcessor(preproc);
                }

                //Set nIn value for layer (if not already set)
                InputType afterPreproc = layerInput;
                if (lv.getPreProcessor() != null) {
                    InputPreProcessor ip = lv.getPreProcessor();
                    afterPreproc = ip.getOutputType(layerInput);
                }
                l.setNIn(afterPreproc, false);

                currLayerIdx++;
            } else {
                List<String> inputs = vertexInputs.get(s);
                if (inputs != null) {
                    for (String inputVertexName : inputs) {
                        inputTypeList.add(vertexOutputs.get(inputVertexName));
                    }
                }
            }

            InputType outputFromVertex =
                            gv.getOutputType(currLayerIdx, inputTypeList.toArray(new InputType[inputTypeList.size()]));
            vertexOutputs.put(s, outputFromVertex);
        }
    }

    private Map<String, List<String>> verticesOutputTo() {
        Map<String, List<String>> verticesOutputTo = new HashMap<>(); //Key: vertex. Values: vertices that this node is an input for
        for (Map.Entry<String, GraphVertex> entry : vertices.entrySet()) {
            String vertexName = entry.getKey();
            List<String> vertexInputNames;
            vertexInputNames = vertexInputs.get(vertexName);

            if (vertexInputNames == null)
                continue;

            //Build reverse network structure:
            for (String s : vertexInputNames) {
                List<String> list = verticesOutputTo.get(s);
                if (list == null) {
                    list = new ArrayList<>();
                    verticesOutputTo.put(s, list);
                }
                list.add(vertexName); //Edge: s -> vertexName
            }
        }

        return verticesOutputTo;
    }

    private List<String> topologicalOrdering() {
        //First step: build network in reverse order (i.e., define map of a -> list(b) instead of list(a) -> b)
        Map<String, List<String>> verticesOutputTo = verticesOutputTo();
        LinkedList<String> noIncomingEdges = new LinkedList<>(networkInputs); //Set of all nodes with no incoming edges
        List<String> topologicalOrdering = new ArrayList<>();

        Map<String, Set<String>> inputEdges = new HashMap<>();
        for (Map.Entry<String, List<String>> entry : vertexInputs.entrySet()) {
            inputEdges.put(entry.getKey(), new HashSet<>(entry.getValue()));
        }

        while (!noIncomingEdges.isEmpty()) {
            String next = noIncomingEdges.removeFirst();
            topologicalOrdering.add(next);

            //Remove edges next -> vertexOuputsTo[...] from graph;
            List<String> nextEdges = verticesOutputTo.get(next);

            if (nextEdges != null && !nextEdges.isEmpty()) {
                for (String s : nextEdges) {
                    Set<String> set = inputEdges.get(s);
                    set.remove(next);
                    if (set.isEmpty()) {
                        noIncomingEdges.add(s); //No remaining edges for vertex i -> add to list for processing
                    }
                }
            }
        }

        //If any edges remain in the graph: graph has cycles:
        for (Map.Entry<String, Set<String>> entry : inputEdges.entrySet()) {
            Set<String> set = entry.getValue();
            if (set == null)
                continue;
            if (!set.isEmpty())
                throw new IllegalStateException(
                                "Invalid configuration: cycle detected in graph. Cannot calculate topological ordering with graph cycle ("
                                                + "cycle includes vertex \"" + entry.getKey() + "\")");
        }

        return topologicalOrdering;
    }

    /**
     * Get a {@link MemoryReport} for the given computation graph configuration. This is used to estimate the
     * memory requirements for the given network configuration and input
     *
     * @param inputTypes Input types for the network
     * @return Memory report for the network
     */
    public NetworkMemoryReport getMemoryReport(InputType... inputTypes) {

        Map<String, MemoryReport> memoryReportMap = new LinkedHashMap<>();
        List<String> topologicalOrdering = topologicalOrdering();

        Map<String, InputType> vertexOutputs = new HashMap<>();
        int currLayerIdx = -1;
        for (String s : topologicalOrdering) {
            int inputIdx = networkInputs.indexOf(s);
            if (inputIdx != -1) {
                vertexOutputs.put(s, inputTypes[inputIdx]);
                continue;
            }

            GraphVertex gv = vertices.get(s);

            List<InputType> inputTypeList = new ArrayList<>();

            if (gv instanceof LayerVertex) {
                //Add preprocessor, if necessary:
                String in = vertexInputs.get(s).get(0);
                InputType layerInput = vertexOutputs.get(in);
                inputTypeList.add(layerInput);
                currLayerIdx++;
            } else {
                List<String> inputs = vertexInputs.get(s);
                if (inputs != null) {
                    for (String inputVertexName : inputs) {
                        inputTypeList.add(vertexOutputs.get(inputVertexName));
                    }
                }
            }

            InputType outputFromVertex =
                            gv.getOutputType(currLayerIdx, inputTypeList.toArray(new InputType[inputTypeList.size()]));
            vertexOutputs.put(s, outputFromVertex);

            MemoryReport mr = gv.getMemoryReport(inputTypeList.toArray(new InputType[inputTypeList.size()]));

            memoryReportMap.put(s, mr);
        }

        return new NetworkMemoryReport(memoryReportMap, ComputationGraphConfiguration.class, "ComputationGraph",
                        inputTypes);
    }

    @Data
    public static class GraphBuilder {
        protected Map<String, GraphVertex> vertices = new LinkedHashMap<>();

        /**
         * Key: graph node. Values: input to that node
         */
        protected Map<String, List<String>> vertexInputs = new LinkedHashMap<>();

        protected List<String> networkInputs = new ArrayList<>();
        protected List<InputType> networkInputTypes = new ArrayList<>();
        protected List<String> networkOutputs = new ArrayList<>();

        protected boolean pretrain = false;
        protected boolean backprop = true;
        protected BackpropType backpropType = BackpropType.Standard;
        protected int tbpttFwdLength = 20;
        protected int tbpttBackLength = 20;

        protected Map<String, InputPreProcessor> inputPreProcessors = new LinkedHashMap<>();

        protected NeuralNetConfiguration.Builder globalConfiguration;

        public GraphBuilder(NeuralNetConfiguration.Builder globalConfiguration) {
            this.globalConfiguration = globalConfiguration;
        }

        public GraphBuilder(ComputationGraphConfiguration newConf, NeuralNetConfiguration.Builder globalConfiguration) {

            ComputationGraphConfiguration clonedConf = newConf.clone();

            this.vertices = clonedConf.getVertices();
            this.vertexInputs = clonedConf.getVertexInputs();

            this.networkInputs = clonedConf.getNetworkInputs();
            this.networkOutputs = clonedConf.getNetworkOutputs();

            this.pretrain = clonedConf.isPretrain();
            this.backprop = clonedConf.isBackprop();
            this.backpropType = clonedConf.getBackpropType();
            this.tbpttFwdLength = clonedConf.getTbpttFwdLength();
            this.tbpttBackLength = clonedConf.getTbpttBackLength();
            this.globalConfiguration = globalConfiguration;
            //this.getGlobalConfiguration().setSeed(clonedConf.getDefaultConfiguration().getSeed());
        }

        /**
         * Specify the processors for a given layer
         * These are used at each layer for doing things like normalization and shaping of input.

         * Note: preprocessors can also be defined using the {@link #addLayer(String, Layer, InputPreProcessor, String...)} method.
         *
         * @param layer     the name of the layer that this preprocessor will be used with
         * @param processor the preprocessor to use for the specified layer
         */
        public GraphBuilder inputPreProcessor(String layer, InputPreProcessor processor) {
            inputPreProcessors.put(layer, processor);
            return this;
        }

        /**
         * Whether to do back prop (standard supervised learning) or not
         *
         * @param backprop whether to do back prop or not
         */
        public GraphBuilder backprop(boolean backprop) {
            this.backprop = backprop;
            return this;
        }

        /**
         * Whether to do layerwise pre training or not
         *
         * @param pretrain whether to do pre train or not
         */
        public GraphBuilder pretrain(boolean pretrain) {
            this.pretrain = pretrain;
            return this;
        }

        /**
         * The type of backprop. Default setting is used for most networks (MLP, CNN etc),
         * but optionally truncated BPTT can be used for training recurrent neural networks.
         * If using TruncatedBPTT make sure you set both tBPTTForwardLength() and tBPTTBackwardLength()
         *
         * @param type Type of backprop. Default: BackpropType.Standard
         */
        public GraphBuilder backpropType(BackpropType type) {
            this.backpropType = type;
            return this;
        }

        /**
         * When doing truncated BPTT: how many steps of forward pass should we do
         * before doing (truncated) backprop?

         * Only applicable when doing backpropType(BackpropType.TruncatedBPTT)

         * Typically tBPTTForwardLength parameter is same as the tBPTTBackwardLength parameter,
         * but may be larger than it in some circumstances (but never smaller)

         * Ideally your training data time series length should be divisible by this
         * This is the k1 parameter on pg23 of
         * http://www.cs.utoronto.ca/~ilya/pubs/ilya_sutskever_phd_thesis.pdf
         *
         * @param forwardLength Forward length > 0, >= backwardLength
         */
        public GraphBuilder tBPTTForwardLength(int forwardLength) {
            this.tbpttFwdLength = forwardLength;
            return this;
        }

        /**
         * When doing truncated BPTT: how many steps of backward should we do?

         * Only applicable when doing backpropType(BackpropType.TruncatedBPTT)

         * This is the k2 parameter on pg23 of
         * http://www.cs.utoronto.ca/~ilya/pubs/ilya_sutskever_phd_thesis.pdf
         *
         * @param backwardLength <= forwardLength
         */
        public GraphBuilder tBPTTBackwardLength(int backwardLength) {
            this.tbpttBackLength = backwardLength;
            return this;
        }

        /**
         * Add a layer, with no {@link InputPreProcessor}, with the specified name and specified inputs.
         *
         * @param layerName   Name/label of the layer to add
         * @param layer       The layer configuration
         * @param layerInputs Inputs to this layer (must be 1 or more). Inputs may be other layers, GraphVertex objects,
         *                    on a combination of the two.
         * @see #addLayer(String, Layer, InputPreProcessor, String...)
         */
        public GraphBuilder addLayer(String layerName, Layer layer, String... layerInputs) {
            return addLayer(layerName, layer, null, layerInputs);
        }

        /**
         * Add a layer, with no {@link InputPreProcessor}, with the specified name and specified inputs.
         *
         * @param layerName   Name/label of the layer to add
         * @param layer       The layer configuration
         * @param layerInputs Inputs to this layer (must be 1 or more). Inputs may be other layers, GraphVertex objects,
         *                    on a combination of the two.
         * @see #addLayer(String, Layer, InputPreProcessor, String...)
         */
        public GraphBuilder layer(String layerName, Layer layer, String... layerInputs) {
            return addLayer(layerName, layer, null, layerInputs);
        }

        /**
         * Add a layer and an {@link InputPreProcessor}, with the specified name and specified inputs.
         *
         * @param layerName    Name/label of the layer to add
         * @param layer        The layer configuration
         * @param preProcessor The InputPreProcessor to use with this layer.
         * @param layerInputs  Inputs to this layer (must be 1 or more). Inputs may be other layers, GraphVertex objects,
         *                     on a combination of the two.
         */
        public GraphBuilder addLayer(String layerName, Layer layer, InputPreProcessor preProcessor,
                        String... layerInputs) {
            NeuralNetConfiguration.Builder builder = globalConfiguration.clone();
            builder.layer(layer);
            addVertex(layerName, new LayerVertex(builder.build(), preProcessor), layerInputs);
            layer.setLayerName(layerName);
            return this;
        }

        /**
         * Add a layer and an {@link InputPreProcessor}, with the specified name and specified inputs.
         *
         * @param layerName    Name/label of the layer to add
         * @param layer        The layer configuration
         * @param preProcessor The InputPreProcessor to use with this layer.
         * @param layerInputs  Inputs to this layer (must be 1 or more). Inputs may be other layers, GraphVertex objects,
         *                     on a combination of the two.
         */
        public GraphBuilder layer(String layerName, Layer layer, InputPreProcessor preProcessor,
                                     String... layerInputs) {
            return addLayer(layerName, layer, preProcessor, layerInputs);
        }

        /**
         * Intended for use with the transfer learning API. Users discouraged from employing it directly.
         * Removes the specified vertex from the vertices list, it's connections and associated preprocessor
         * If the vertex removed is an output vertex it will also be removed from the list of outputs
         * @param vertexName Name of the vertex to remove
         */
        public GraphBuilder removeVertex(String vertexName) {
            removeVertex(vertexName, true);
            return this;
        }

        /**
         * Intended for use with the transfer learning API. Users discouraged from employing it directly.
         * Removes the specified vertex from the vertices list,
         * Removes it's connections (associated preprocessor and if an output also removes it from list of outputs) if "removeConnections" is specified as true
         * Specifying as false can leave the graph in an invalid state with references to vertices that donot exist unless a new vertex is added back in with the same name
         * @param removeConnections Specify true to remove connections
         * @param vertexName Name of the vertex to remove
         */
        public GraphBuilder removeVertex(String vertexName, boolean removeConnections) {
            vertices.remove(vertexName);
            vertexInputs.remove(vertexName);
            if (networkInputs.contains(vertexName)) {
                networkInputs.remove(vertexName);
            }
            if (removeConnections) {
                if (networkOutputs.contains(vertexName)) {
                    networkOutputs.remove(vertexName);
                }
                for (Map.Entry<String, List<String>> entry : this.vertexInputs.entrySet()) {
                    List inputs = entry.getValue();
                    if (inputs.contains(vertexName)) {
                        inputs.remove(vertexName);
                    }
                }
                if (inputPreProcessors.containsKey(vertexName)) {
                    inputPreProcessors.remove(vertexName);
                }
            }
            return this;
        }

        /**
         * Specify the inputs to the network, and their associated labels.
         *
         * @param inputNames The names of the inputs. This also defines their order
         */
        public GraphBuilder addInputs(String... inputNames) {
            Collections.addAll(networkInputs, inputNames);
            return this;
        }

        /**
         * Specify the inputs to the network, and their associated labels.
         *
         * @param inputNames The names of the inputs. This also defines their order
         */
        public GraphBuilder addInputs(Collection<String> inputNames) {
            networkInputs.addAll(inputNames);
            return this;
        }

        /**Specify the types of inputs to the network, so that:

         * (a) preprocessors can be automatically added, and

         * (b) the nIns (input size) for each layer can be automatically calculated and set

         * The order here is the same order as .addInputs(). Thus, if you do .addInputs("a","b") and .setInputTypes(InputType.feedForward(),
         * InputType.convolutional(1,28,28)) then the input labelled "a" is a feed forward input, whereas the input labelled "b" in a CNN
         * input, with 28x28x1 images as input.

         * Note: Using setInputTypes is not always necessary, but can be especially helpful for example with CNNs such that
         * the calculations on input/ouput sizes (width, height, depth, etc) don't need to be done manually.

         * Note 2: If a preprocessor is manually added for a given layer, it will not be overridden by the automatic
         * addition of preprocessors.
         * Note 3: If a layer has an nIn set manually, this will not be overridden
         */
        public GraphBuilder setInputTypes(InputType... inputTypes) {
            if (inputTypes != null && inputTypes.length > 0)
                Collections.addAll(networkInputTypes, inputTypes);
            return this;
        }

        /**
         * Set the network output labels. These should be the names of the OutputLayer instances in the network
         *
         * @param outputNames The names of the output layers. This also defines their order.
         */
        public GraphBuilder setOutputs(String... outputNames) {
            networkOutputs.clear();
            Collections.addAll(networkOutputs, outputNames);

            return this;
        }

        /**
         * Add a {@link GraphVertex} to the network configuration. A GraphVertex defines forward and backward pass methods,
         * and can contain a {@link LayerVertex}, a {@link org.deeplearning4j.nn.conf.graph.ElementWiseVertex} to do element-wise
         * addition/subtraction, a {@link MergeVertex} to combine/concatenate the activations out of multiple layers or vertices,
         * a {@link org.deeplearning4j.nn.conf.graph.SubsetVertex} to select a subset of the activations out of another layer/GraphVertex.

         * Custom GraphVertex objects (that extend the abstract {@link GraphVertex} class) may also be used.
         *
         * @param vertexName   The name of the GraphVertex to add
         * @param vertex       The GraphVertex to add
         * @param vertexInputs The inputs/activations to this GraphVertex
         */
        public GraphBuilder addVertex(String vertexName, GraphVertex vertex, String... vertexInputs) {
            vertices.put(vertexName, vertex);

            //Automatically insert a MergeNode if this vertex can only take 1 input (layer vertices, etc)
            if (vertex.maxVertexInputs() == 1 && vertexInputs != null && vertexInputs.length > 1) {
                String mergeName = vertexName + "-merge";
                addVertex(mergeName, new MergeVertex(), vertexInputs);
                this.vertexInputs.put(vertexName, Collections.singletonList(mergeName));
            } else if (vertexInputs != null) {
                this.vertexInputs.put(vertexName, Arrays.asList(vertexInputs));
            }
            return this;
        }

        /**
         * Create the ComputationGraphConfiguration from the Builder pattern
         */
        public ComputationGraphConfiguration build() {

            ComputationGraphConfiguration conf = new ComputationGraphConfiguration();
            conf.backprop = backprop;
            conf.pretrain = pretrain;
            conf.backpropType = backpropType;
            conf.tbpttBackLength = tbpttBackLength;
            conf.tbpttFwdLength = tbpttFwdLength;

            conf.networkInputs = networkInputs;
            conf.networkOutputs = networkOutputs;

            conf.vertices = this.vertices;
            conf.vertexInputs = this.vertexInputs;
            conf.trainingWorkspaceMode = globalConfiguration.trainingWorkspaceMode;
            conf.inferenceWorkspaceMode = globalConfiguration.inferenceWorkspaceMode;
            conf.cacheMode = globalConfiguration.cacheMode;

            conf.defaultConfiguration = globalConfiguration.build();
            conf.getDefaultConfiguration().setPretrain(pretrain);

            //Add preprocessors that were defined separately to the Layers to which they belong
            for (Map.Entry<String, InputPreProcessor> entry : inputPreProcessors.entrySet()) {
                GraphVertex gv = vertices.get(entry.getKey());
                if (gv instanceof LayerVertex) {
                    LayerVertex lv = (LayerVertex) gv;
                    lv.setPreProcessor(entry.getValue());
                } else {
                    throw new IllegalStateException(
                                    "Invalid configuration: InputPreProcessor defined for GraphVertex \""
                                                    + entry.getKey() + "\", but this vertex is not a LayerVertex");
                }

            }

            for (Map.Entry<String, GraphVertex> gv : vertices.entrySet()) {
                if (gv.getValue() instanceof LayerVertex) {
                    LayerVertex lv = (LayerVertex) gv.getValue();
                    Layer l = lv.getLayerConf().getLayer();
                    if (l instanceof BasePretrainNetwork)
                        lv.getLayerConf().setPretrain(pretrain);
                }

            }

            conf.validate(); //throws exception for invalid configuration

            //Automatically add preprocessors, set nIns for CNN->dense transitions, etc
            if (!networkInputTypes.isEmpty()) {
                conf.addPreProcessors(networkInputTypes.toArray(new InputType[networkInputs.size()]));
            }

            return conf;
        }
    }
}


text:
<?php
if (!defined('ABSPATH')) exit;

$email_id = (int) $_GET['id'];
$module = NewsletterStatistics::instance();

$email = $module->get_email($email_id);
?>

    <?php include NEWSLETTER_DIR . '/tnp-header.php' ?>

Reached subscribers for "<?php echo esc_html($email->subject); ?>"

<a href="admin.php?page=newsletter_statistics_view&id=<?php echo $email->id ?>" class="button-primary">Back to the dashboard

            <img src="<?php echo plugins_url('newsletter') ?>/statistics/images/users.png">

    <?php include NEWSLETTER_DIR . '/tnp-footer.php' ?>


text:
extern "C" {
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>
}

#include "libkfsClient/KfsClient.h"
#include "tools/KfsShell.h"

#include <boost/lexical_cast.hpp>

using std::cout;
using std::endl;
using std::vector;
using std::string;

using namespace KFS;

int
KFS::tools::handlePwd(const vector<string> &args)
{
    if ((args.size() >= 1) && (args[0] == "--help")) {
        cout << "Usage: pwd " << endl;
        return 0;
    }

    KfsClientPtr kfsClient = getKfsClientFactory()->GetClient();

    string pwd = kfsClient->GetCwd();

    cout << pwd << endl;
    return 0;
}


text:
Getting Started {#start}
========================

<!---
 ! Copyright (c) 2013-2021, Intel Corporation
 !
 ! Redistribution and use in source and binary forms, with or without
 ! modification, are permitted provided that the following conditions are met:
 !
 !  * Redistributions of source code must retain the above copyright notice,
 !    this list of conditions and the following disclaimer.
 !  * Redistributions in binary form must reproduce the above copyright notice,
 !    this list of conditions and the following disclaimer in the documentation
 !    and/or other materials provided with the distribution.
 !  * Neither the name of Intel Corporation nor the names of its contributors
 !    may be used to endorse or promote products derived from this software
 !    without specific prior written permission.
 !
 ! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 ! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 ! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 ! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 ! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 ! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 ! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 ! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 ! POSSIBILITY OF SUCH DAMAGE.
 !-->

This chapter gives a brief introduction into the sample tools using one of
the tests as example.  It assumes that you are already familiar with
Intel(R) Processor Trace (Intel PT) and that you already built the decoder
library and the sample tools.

For detailed information about Intel PT, please refer to the respective
chapter in Volume 3 of the Intel Software Developer's Manual at
https://www.intel.com/sdm.

Start by compiling the loop-tnt test.  It consists of a small assembly program
with interleaved Intel PT directives:

	$ pttc test/src/loop-tnt.ptt
	loop-tnt-ptxed.exp
	loop-tnt-ptdump.exp

This produces the following output files:

	loop-tnt.lst          a yasm assembly listing file
	loop-tnt.bin          a raw binary file
	loop-tnt.pt           a Intel PT file
	loop-tnt-ptxed.exp    the expected ptxed output
	loop-tnt-ptdump.exp   the expected ptdump output

The latter two files are generated based on the `@pt .exp(<tool>)` directives
found in the `.ptt` file.  They are used for automated testing.  See
script/test.bash for details on that.

Use `ptdump` to dump the Intel PT packets:

	$ ptdump loop-tnt.pt
	0000000000000000  psb
	0000000000000010  fup        3: 0x0000000000100000, ip=0x0000000000100000
	0000000000000017  mode.exec  cs.d=0, cs.l=1 (64-bit mode)
	0000000000000019  psbend
	000000000000001b  tnt8       !!.
	000000000000001c  tip.pgd    3: 0x0000000000100013, ip=0x0000000000100013

The ptdump tool takes an Intel PT file as input and dumps the packets in
human-readable form.  The number on the very left is the offset into the Intel
PT packet stream in hex.  This is followed by the packet opcode and payload.

Use `ptxed` for reconstructing the execution flow.  For this, you need the Intel
PT file as well as the corresponding binary image.  You need to specify the load
address given by the org directive in the .ptt file when using a raw binary
file.

	$ ptxed --pt loop-tnt.pt --raw loop-tnt.bin:0x100000
	0x0000000000100000  mov rax, 0x0
	0x0000000000100007  jmp 0x10000d
	0x000000000010000d  cmp rax, 0x1
	0x0000000000100011  jle 0x100009
	0x0000000000100009  add rax, 0x1
	0x000000000010000d  cmp rax, 0x1
	0x0000000000100011  jle 0x100009
	0x0000000000100009  add rax, 0x1
	0x000000000010000d  cmp rax, 0x1
	0x0000000000100011  jle 0x100009
	[disabled]

Ptxed prints disassembled instructions in execution order as well as status
messages enclosed in brackets.


text:
package main

import (
	"fmt"
	"encoding/json"

	"github.com/kuzzleio/sdk-go/protocol/websocket"
	"github.com/kuzzleio/sdk-go/kuzzle"
	"github.com/kuzzleio/sdk-go/types"
)

func main() {
	[snippet-code]
	k.Server.Now(nil)
	fmt.Println("Everything is ok")
}


text:
"use strict";

function StateController() {

    var _map = null;
    var _this = this;

    _this.left_side = $("#left_side");
    _this.right_side = $("#right_side");
    _this.remove_button = $('.mapplic-remove-button');
    _this.new_button = $('.mapplic-new-button');
    _this.mzoom_buttons = $('.mzoom_buttons');
    _this.map_creating = $('#map_creating');
    _this.map_editing = $('#map_editing');
    _this.map_removing = $('#map_removing');
    _this.main_map = $('.main_map'); /*qwwqq*/
    _this.svg_overlay = $('#svg_overlay');
    _this.area_order_button = $('.area_order_button');
    _this.edit_button = $('.mapplic-edit-button');
    _this.masked = $('#masked');

    _this.setMode = function (mode) {

        // Должен быть учёт, из какого состояния пришли в состояние рисования, и возвращаться в него
        //      * При рисовании, находясь внутри здания, возвращаться в 'edit_building'
        //      * При рисовании, находясь внутри площади, возвращаться в 'edit_area'
        // За исключением ситуации, когда начали редактировать, находясь на карте
        if (mode == 'editing' && _map.prev_mode != 'viewing') {
            mode = _map.prev_mode;
        }

        console.log('<StateController.setMode> Переводим карту в режим: mode = ' + mode);

        _map.prev_mode = _map.mode;
        _map.mode = mode;

        //<editor-fold desc="Впишем режим в cssClass контейнера карты">
        // NOTE: этот код коррелирует с [x9cs7]. Возможно, нужен рефакторинг
        _map.container.removeClass("viewing");
        _map.container.removeClass("editing");
        _map.container.removeClass("creating");
        _map.container.removeClass("removing");
        _map.container.removeClass("view_building");
        _map.container.removeClass("edit_building");
        _map.container.removeClass("view_area");
        _map.container.removeClass("edit_area");
        _map.container.removeClass("view_floor");
        _map.container.removeClass("edit_floor");
        _map.container.addClass(mode);
        //</editor-fold>

        _this.checkMode();
    };

    _this.checkMode = function () {

        //<editor-fold desc="Предварительно проверим, все ли участники доступны">
        if (_this.new_button.length == 0) _this.new_button = $('.mapplic-new-button');
        if (_this.remove_button.length == 0) _this.remove_button = $('.mapplic-remove-button');
        if (_this.edit_button.length == 0) _this.edit_button = $('.mapplic-edit-button');
        if (_this.right_side.length == 0) _this.right_side = $('#right_side');
        if (_this.left_side.length == 0) _this.left_side = $('#left_side');
        if (_this.mzoom_buttons.length == 0) _this.mzoom_buttons = $('.mzoom_buttons');
        if (_this.map_creating.length == 0) _this.map_creating = $('#map_creating');
        if (_this.map_editing.length == 0) _this.map_editing = $('#map_editing');
        if (_this.map_removing.length == 0) _this.map_removing = $('#map_removing');
        if (_this.main_map.length == 0) _this.main_map = $('.main_map'); /*qwwqq*/
        if (_this.svg_overlay.length == 0) _this.svg_overlay = $('#svg_overlay');
        if (_this.area_order_button.length == 0) _this.area_order_button = $('.area_order_button');
        if (_this.masked.length == 0) _this.masked = $("#masked");
        //</editor-fold>

        switch (_map.mode) {

            // перешли в состояние редактирования карты
            case "editing":
                //<editor-fold desc="...">

                console.log("<StateController.setMode> <ожидается рисование полигонов Зданий или их привязка>.");

                // спрячем надписи "цена за метр" и адрес с телефоном
                _this.left_side.css("top", -300);
                _this.right_side.css("top", -300);

                // покажем кнопку "добавить фигуру"
                OpacityButtonsUtils.show(_this.new_button);
                _map.new_button_klass.resetState();

                // покажем кнопку "удалить фигуру"
                OpacityButtonsUtils.show(_this.remove_button);

                // спрячем статусную область
                _this.map_creating.css('display', 'none');
                _this.map_editing.css('display', 'block');
                _this.map_removing.css('display', 'none');

                // покажем кнопку "связать здание с полигоном"
                _map.building_link_button_klass.show();

                // покажем кнопки, присущие этому режиму
                _this.mzoom_buttons.css('opacity', '1');

                _this.main_map.css('opacity', '1');

                _map.save_button_klass.show();
                _map.save_button_klass.check_and_enable();

                // скроем подсказки - сколько свободных площадей где есть
                _map.hide_free_areas_hint();

                //Показать все админские лейблы.
                _map.admin_label_show_all();

                // скроем форму поиска
                _map.search_gui_klass.position_hide();

                //</editor-fold>
            break;

            // перешли в состояние просмотра карты, видны все здания с крышами
            case "viewing":
                //<editor-fold desc="...">
                //clog("_this.left_side.data('init') = " + _this.left_side.data('init'));

                // покажем надписи "цена за метр" и адрес с телефоном
                if (_this.left_side.data('init') == undefined) {
                    _this.left_side.data('init', _this.left_side.css("top"));
                }
                if (_this.right_side.data('init') == undefined) {
                    _this.right_side.data('init', _this.right_side.css("top"));
                }
                _this.left_side.css("top", _this.left_side.data('init'));
                _this.right_side.css("top", _this.right_side.data('init'));

                // спрячем кнопки редактора
                OpacityButtonsUtils.hide(_this.new_button);
                OpacityButtonsUtils.hide(_this.remove_button);
                _this.map_creating.css('display', 'none');
                _this.map_editing.css('display', 'none');
                _this.map_removing.css('display', 'none');

                // скроем кнопку "связать здание с полигоном"
                if (_map.building_link_button_klass != null) {
                    _map.building_link_button_klass.hide();
                }

                // покажем кнопки zoom
                _this.mzoom_buttons.css('opacity', '1');

                // покажем главную карту(?)
                _this.main_map.css('opacity', '1');

                // скроем svg_overlay слой, который нужен только когда внутри здания
                _this.svg_overlay.css('display', 'none');

                // скроем слой, в котором рисуем анимацию по маске, который нужен только когда внутри здания\площади
                _this.masked.addClass('hiddn');

                // спрячем инфу о здании
                _map.building_info_klass.hide();

                // скроем кнопку "забронировать площадь"
                _this.area_order_button.css('display', 'none');

                // скроем кнопку "обратно на карту"
                _map.back_to_map_button_klass.hide();

                // актуально, когда входим в это состояние
                // из здания\площади, нажав кнопку "обратно на карту"
                _map.edit_button_klass.setState('viewing', true); // [a1x7]

                if (_map.save_button_klass) {
                    _map.save_button_klass.hide();
                }

                // покажем подсказки - сколько свободных площадей где есть
                _map.show_free_areas_hint();

                //Скрыть все админские лейблы.
                _map.admin_label_hide_all();

                // форму поиска покажем в исходном (нормальном) состоянии
                if (_map.search_gui_klass != null) {
                    _map.search_gui_klass.position_init();
                }

                //</editor-fold>
            break;

            // перешли в состояние рисования полигона
            case "creating":
                //<editor-fold desc="...">
                //_this.mzoom_buttons.css('opacity', '0');
                _this.map_creating.css('display', 'block');
                _this.map_editing.css('display', 'none');
                _this.map_removing.css('display', 'none');

                _this.main_map.css('opacity', '1');
                //</editor-fold>
            break;

            // перешли в состояние удаления полигона
            case "removing":
                //<editor-fold desc="...">
                //_this.mzoom_buttons.css('opacity', '0');
                _this.map_creating.css('display', 'none');
                _this.map_editing.css('display', 'none');
                _this.map_removing.css('display', 'block');

                _this.main_map.css('opacity', '1');

                _map.save_button_klass.hide();
                _map.floor_link_button_klass.hide();
                _map.update_json_klass.hide();

                // прячем кнопку "создать полигон"
                OpacityButtonsUtils.hide(_this.new_button);
                OpacityButtonsUtils.hide(_this.remove_button);
                OpacityButtonsUtils.hide(_this.edit_button);
                //</editor-fold>
            break;

            // вошли в здание
            case "view_building":
                //<editor-fold desc="...">
                // покажем кнопку "обратно на карту"
                _map.back_to_map_button_klass.show();

                // скроем кнопку "связать здание с полигоном"
                _map.building_link_button_klass.hide();

                // спрячем надписи "цена за метр" и адрес с телефоном
                _this.left_side.css("top", -300);
                _this.right_side.css("top", -300);

                //_this.main_map.css('opacity','0.7');
                _this.svg_overlay.css('display', 'block');

                // покажем инфо-панель
                _map.building_info_klass.show();

                _this.masked.addClass('hiddn');

                _this.area_order_button.css('display', 'none');
                _map.edit_button_klass.setState('view_building', true); // [a1x7]
                if (_map.current_building != undefined) _map.current_building.resetOverlayZindex();
                _map.save_button_klass.hide();

                OpacityButtonsUtils.hide(_this.new_button);
                OpacityButtonsUtils.hide(_this.remove_button);

                _this.mzoom_buttons.css('opacity', '1');

                // скроем подсказки - сколько свободных площадей где есть
                _map.hide_free_areas_hint();

                // сдвинем форму поиска так, чтобы её не загораживала инфо-панель
                _map.search_gui_klass.position_inside();

                //</editor-fold>
            break;

            // редактируем, находясь в здании
            case "edit_building":
                //<editor-fold desc="...">
                // спрячем кнопку "обратно на карту"
                _map.back_to_map_button_klass.hide();

                // покажем кнопку "связать здание с полигоном"
                _map.building_link_button_klass.show();

                // т.к. этот слой используется испключительно в помощь при рисовании обводки площадей
                // и перехватывает клики при dnd, то тут он нам не нужен
                _this.svg_overlay.css('display', 'none');

                // заодно поменяем z-index слоёв с колоннами и слоя с svg
                // полигонами площадей, чтобы можно было добраться мышкой
                // до этих полигонов и редактировать их
                if (_map.current_building != undefined) _map.current_building.changeOverlayZindex();

                // покажем кнопку "добавить фигуру"
                OpacityButtonsUtils.show(_this.new_button);
                _map.new_button_klass.resetState();

                // покажем кнопку "удалить фигуру"
                OpacityButtonsUtils.show(_this.remove_button);

                // покажем кнопку "ред"
                OpacityButtonsUtils.show(_this.edit_button);

                // спрячем инфу о здании
                _map.building_info_klass.hide();

                // спрячем статус строку "вы создаёте полигон"
                _this.map_creating.css('display', 'none');
                _this.map_removing.css('display', 'none');

                // покажем, возможно спрятанные, zoom кнопки
                _this.mzoom_buttons.css('opacity', '1');

                _map.save_button_klass.show();
                _map.save_button_klass.check_and_enable();

                // скроем форму поиска
                _map.search_gui_klass.position_hide();

                //</editor-fold>
            break;

            // вошли в площадь
            case "view_area":
                //<editor-fold desc="...">

                // покажем кнопку "обратно на карту"
                _map.back_to_map_button_klass.show();

                //
                _this.masked.removeClass('hiddn');

                // выдвигаем инфо-панель
                _map.building_info_klass.show();

                // TODO:: реализовать показ кнопки 'оставить заявку'
                //<editor-fold desc="// спозиционируем и покажем кнопку 'оставить заявку'">
                //var t = _this.building_info.height() + _this.building_info.offset().top;
                //var tt = _this.building_info.css("left");
                //var tq = (_this.building_info.width() + 40) + "px";
                //_this.area_order_button.css("top", t + "px");
                _this.area_order_button.css("bottom","400px");
                //_this.area_order_button.css("left", tt);
                //_this.area_order_button.css("width", tq);
                //_this.area_order_button.css('display', 'block');
                //</editor-fold>

                _map.edit_button_klass.setState('view_area', true); // [a1x7]

                // скроем кнопку "связать площадь с полигоном"
                _map.area_link_button_klass.hide();

                OpacityButtonsUtils.hide(_this.new_button);
                OpacityButtonsUtils.hide(_this.remove_button);

                _this.mzoom_buttons.css('opacity', '1');
                //</editor-fold>
            break;

            // начали редактировать площадь
            case 'edit_area':
                //<editor-fold desc="...">
                // спрячем кнопку "обратно на карту"
                _map.back_to_map_button_klass.hide();

                // покажем кнопку "связать площадь с полигоном"
                _map.area_link_button_klass.show();

                // покажем кнопку "сохранить изменения"
                _map.save_button_klass.show();

                // спрячем кнопку "создать полигон"
                OpacityButtonsUtils.hide(_this.new_button);

                // покажем кнопку "ред"
                OpacityButtonsUtils.show(_this.edit_button);

                _map.edit_button_klass.setState('edit_area', true); // [a1x7]

                // спрячем инфу о здании
                _map.building_info_klass.hide();

                // скроем форму поиска
                _map.search_gui_klass.position_hide();

                //</editor-fold>
            break;

            // вошли на этаж
            case "view_floor":
                //<editor-fold desc="...">

                // спрячем надписи "цена за метр" и адрес с телефоном
                _this.left_side.css("top", -300);
                _this.right_side.css("top", -300);

                //_this.main_map.css('opacity','0.7');

                // т.к. этот слой используется испключительно в помощь при рисовании обводки площадей и перехватывает клики при dnd, то тут он нам не нужен
                _this.svg_overlay.css('display', 'block');

                // выдвигаем инфо-панель
                _map.building_info_klass.show();

                // покажем кнопку "обратно на карту"
                _map.back_to_map_button_klass.show();

                // прячем masked слой - а там что (запомятовал)?
                _this.masked.addClass('hiddn');

                // скроем кнопку "связать этаж с полигоном" (которая видна при выходе из режима редактирования этажа)
                _map.floor_link_button_klass.hide();

                // прячем кнопку "отправить заявку на аренду площади"
                _this.area_order_button.css('display', 'none');

                // кнопку "редактировать" переводим в СООТВЕТСТВУЮЩЕЕ состояние
                _map.edit_button_klass.setState('eb_view_floor', true); // [a1x7]

                // сбросим z-index (пояснение "что это" см. в комментах к resetOverlayZindex)
                //if (_map.current_building != undefined) _map.current_building.resetOverlayZindex();

                // спрячем кнопку "сохранить"
                _map.save_button_klass.hide();

                // спрячем кнопки "добавить полигон" и "удалить полигон"
                OpacityButtonsUtils.hide(_this.new_button);
                OpacityButtonsUtils.hide(_this.remove_button);

                // покажем zoom кнопки
                _this.mzoom_buttons.css('opacity', '1');

                // скроем подсказки - сколько свободных площадей где есть
                _map.hide_free_areas_hint();

                // сдвинем форму поиска так, чтобы её не загораживала инфо-панель
                _map.search_gui_klass.position_inside();

                //</editor-fold>
            break;

            // начали редактировать этаж
            case 'edit_floor':
                //<editor-fold desc="...">

                console.log("<StateController.setMode> <Ожидается рисование полигонов Площадей>.");

                // спрячем кнопку "обратно на карту"
                _map.back_to_map_button_klass.hide();

                // покажем кнопку "связать Этаж с полигоном"
                _map.floor_link_button_klass.show();

                // т.к. этот слой используется испключительно в помощь при рисовании обводки площадей и перехватывает клики при dnd, то тут он нам не нужен
                _this.svg_overlay.css('display', 'none');

                // заодно поменяем z-index слоёв с колоннами и слоя с svg полигонами площадей, чтобы можно было добраться мышкой до этих полигонов и редактировать их
                if (_map.current_building != undefined) _map.current_building.changeOverlayZindex();

                // покажем кнопку "добавить фигуру"
                OpacityButtonsUtils.show(_this.new_button);
                _map.new_button_klass.resetState();

                // покажем кнопку "удалить фигуру"
                OpacityButtonsUtils.show(_this.remove_button);

                // покажем кнопку "ред"
                OpacityButtonsUtils.show(_this.edit_button);

                // спрячем инфу о здании
                _map.building_info_klass.hide();

                // спрячем статус строки "вы создаёте полигон" и ...
                _this.map_creating.css('display', 'none');
                _this.map_removing.css('display', 'none');

                // покажем, возможно спрятанные, zoom кнопки
                _this.mzoom_buttons.css('opacity', '1');

                // покажем кнопку "сохранить"
                _map.save_button_klass.show();
                _map.save_button_klass.check_and_enable();

                // скроем форму поиска
                _map.search_gui_klass.position_hide();

                _map.update_json_klass.show();

                //</editor-fold>
            break;

        }
    };

    _this.init = function (link_to_map) {
        _map = link_to_map;
    }

}