text:
<?php

use yii\db\Migration;
use DevGroup\DataStructure\models\ApplicablePropertyModels;
use DevGroup\DataStructure\behaviors\HasProperties;
use DevGroup\DataStructure\traits\PropertiesTrait;
use yii\helpers\Console;

class m160520_133649_add_lang_id extends Migration
{
    public function up()
    {
        $apl = ApplicablePropertyModels::find()->select('class_name')->column();
        foreach ($apl as $class) {
            /**
             * @var \yii\db\ActiveRecord | HasProperties | PropertiesTrait $class
             */
            $eavTable = $class::eavTable();
            $schema = Yii::$app->db->getTableSchema($eavTable);
            if (false === isset($schema->columns['language_id'])) {
                $this->addColumn(
                    $eavTable,
                    'language_id',
                    $this->integer()->notNull()->defaultValue(0)
                );
            }
        }
    }

    public function down()
    {
        $apl = ApplicablePropertyModels::find()->select('class_name')->column();
        foreach ($apl as $class) {
            /**
             * @var \yii\db\ActiveRecord | HasProperties | PropertiesTrait $class
             */
            $eavTable = $class::eavTable();
            $schema = Yii::$app->db->getTableSchema($eavTable);
            if (true === isset($schema->columns['language_id'])) {
                $this->dropColumn($eavTable, 'language_id');
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package jsettlers.logic.buildings.military.occupying;

import jsettlers.common.buildings.IBuildingOccupier;
import jsettlers.common.buildings.OccupierPlace;
import jsettlers.common.movable.IMovable;
import jsettlers.logic.buildings.military.IBuildingOccupyableMovable;

import java.io.Serializable;

/**
 * Created by Andreas Eberle on 03.07.2017.
 */
final class TowerOccupier implements IBuildingOccupier, Serializable {
	final OccupierPlace place;
	final IBuildingOccupyableMovable soldier;

	TowerOccupier(OccupierPlace place, IBuildingOccupyableMovable soldier) {
		this.place = place;
		this.soldier = soldier;
	}

	@Override
	public OccupierPlace getPlace() {
		return place;
	}

	@Override
	public IMovable getMovable() {
		return soldier.getMovable();
	}

	public IBuildingOccupyableMovable getSoldier() {
		return soldier;
	}
}


text:
module Rx {
    export module internals {
        export interface EmptyError extends Error { message: string; }
        export interface EmptyErrorStatic { new (): EmptyError; }

        export interface ObjectDisposedError extends Error { message: string; }
        export interface ObjectDisposedErrorStatic { new (): ObjectDisposedError; }

        export interface ArgumentOutOfRangeError extends Error { message: string; }
        export interface ArgumentOutOfRangeErrorStatic { new (): ArgumentOutOfRangeError; }

        export interface NotSupportedError extends Error { message: string; }
        export interface NotSupportedErrorStatic { new (): NotSupportedError; }

        export interface NotImplementedError extends Error { message: string; }
        export interface NotImplementedErrorStatic { new (): NotImplementedError; }
    }

    export module helpers {
        export var notImplemented: () => internals.NotImplementedError;
        export var notSupported: () => internals.NotSupportedError;
    }
}


text:
package com.hp.hpl.jena.n3;

import java.io.* ;
import com.hp.hpl.jena.JenaRuntime ;

/** Simple class that provides output with moving left margin.
 *  Does not cope with tabs or newlines in output strings.
 *
 * @author		Andy Seaborne
 * @version 	$Id: N3IndentedWriter.java,v 1.1 2009/06/29 08:55:32 castagna Exp $
 */

// Not robust/complete enough for public use
public class N3IndentedWriter
{
	String lineSeparator = JenaRuntime.getLineSeparator() ;

	Writer writer ;
	int column ;
	int row ;
	int currentIndent ;

	public N3IndentedWriter(Writer w)
	{
		writer = w ;
		column = 0 ;
		row = 0 ;
		currentIndent = 0 ;
	}

    public Writer getWriter() { return writer ; }

	public int getRow() { return row ; }
	public int getCol() { return column ; }
	public int getIndent() { return currentIndent ; }

	public void incIndent(int x) { currentIndent += x ; }
	public void decIndent(int x) { currentIndent -= x ; }
	public void setIndent(int x) { currentIndent = x ; }

	public void print(String s)
	{
		try { writer.write(s); column += s.length() ; }
		catch (java.io.IOException ex) {}
	}

	public void println(String s)
	{
		try { writer.write(s);	println() ; }
		catch (java.io.IOException ex) { }
	}

	public void println()
	{
		try {
			writer.write(lineSeparator);
			writer.flush() ;
			column = 0 ;
			row++ ;
			padTo() ;
		}
		catch (java.io.IOException ex) { }
	}

	public void padTo() throws IOException
	{
		StringBuffer sBuff = new StringBuffer() ;
		for ( int i = 0 ; i < currentIndent ; i++ )
			writer.write(' ') ;
		column = column + currentIndent ;
	}

	public void flush() { try { writer.flush() ; } catch (IOException ioEx) {} }
	public void close() { try { writer.close() ; } catch (IOException ioEx) {} }

}

/*
 *  (c) Copyright 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Hewlett-Packard Development Company, LP
 *  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
 */


text:
using System;
using System.Drawing;

namespace MurphyPA.H2D.TestApp
{
    /// <summary>
    /// LogHandler.
    /// </summary>
    public delegate void LogHandler (Color foreColor, string fmt, params object[] args);
}


text:
from .PBXResolver import *
from .PBX_Constants import *

class PBX_Base(object):

    def __init__(self, lookup_func, dictionary, project, identifier):
        # default 'name' property of a PBX object is the type
        self.name = self.__class__.__name__;
        # this is the identifier for this object
        self.identifier = str(identifier);
        # set of any referenced identifiers on this object
        self.referencedIdentifiers = set();

    def __attrs(self):
        return (self.identifier);

    def __repr__(self):
        return '(%s : %s : %s)' % (type(self), self.name, self.identifier);

    def __eq__(self, other):
        return isinstance(other, type(self)) and self.identifier == other.identifier;

    def __hash__(self):
        return hash(self.__attrs());

    def resolve(self, type, item_list):
        return filter(lambda item: isinstance(item, type), item_list);

    def fetchObjectFromProject(self, lookup_func, identifier, project):
        find_object = project.objectForIdentifier(identifier);
        if find_object == None:
            result = lookup_func(project.contents[kPBX_objects][identifier]);
            if result[0] == True:
                find_object = result[1](lookup_func, project.contents[kPBX_objects][identifier], project, identifier);
                project.objects.add(find_object);
        return find_object;

    def parseProperty(self, prop_name, lookup_func, dictionary, project, is_array):
        dict_item = dictionary[prop_name];
        if is_array == True:
            property_list = [];
            for item in dict_item:
                self.referencedIdentifiers.add(item);
                find_object = self.fetchObjectFromProject(lookup_func, item, project);
                property_list.append(find_object);
            return property_list;
        else:
            self.referencedIdentifiers.add(dict_item);
            return self.fetchObjectFromProject(lookup_func, dict_item, project);


text:
<?xml version="1.0"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.3//EN"
               "http://www.oasis-open.org/docbook/xml/4.3/docbookx.dtd"
[
  <!ENTITY version SYSTEM "version.xml">
]>
<book id="index" xmlns:xi="http://www.w3.org/2003/XInclude">
  <bookinfo>
    <title>libmount Reference Manual</title>
    <releaseinfo>for libmount version &version;</releaseinfo>
    <copyright>
      <year>2010-2015</year>
      <holder>Karel Zak <kzak@redhat.com></holder>
    </copyright>
  </bookinfo>

  <part id="gtk">
    <title>libmount Overview</title>
    <partintro>
    <para>
The libmount library is used to parse /etc/fstab, /etc/mtab and
/proc/self/mountinfo files, manage the mtab file, evaluate mount options, etc.
    </para>
    <para>
The library is part of the util-linux package since version 2.18 and is
available from ftp://ftp.kernel.org/pub/linux/utils/util-linux/.
    </para>
  </partintro>
 </part>

  <part>
    <title>High-level API</title>
    <xi:include href="xml/context.xml"/>
    <xi:include href="xml/context-mount.xml"/>
    <xi:include href="xml/context-umount.xml"/>
  </part>
  <part>
    <title>Files parsing</title>
    <xi:include href="xml/table.xml"/>
    <xi:include href="xml/fs.xml"/>
  </part>
  <part>
    <title>Tables management</title>
    <xi:include href="xml/lock.xml"/>
    <xi:include href="xml/update.xml"/>
    <xi:include href="xml/monitor.xml"/>
    <xi:include href="xml/tabdiff.xml"/>
  </part>
  <part>
    <title>Mount options</title>
    <xi:include href="xml/optstr.xml"/>
    <xi:include href="xml/optmap.xml"/>
  </part>
  <part>
    <title>Misc</title>
    <xi:include href="xml/init.xml"/>
    <xi:include href="xml/cache.xml"/>
    <xi:include href="xml/iter.xml"/>
    <xi:include href="xml/utils.xml"/>
    <xi:include href="xml/version-utils.xml"/>
  </part>
  <index id="api-index">
    <title>API Index</title>
    <xi:include href="xml/api-index-full.xml"><xi:fallback /></xi:include>
  </index>
</book>


text:
/*================================================================================
  code generated by: java2cpp
  author: Zoran Angelov, mailto://baldzar@gmail.com
  class: javax.xml.parsers.DocumentBuilder
================================================================================*/

#ifndef J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_JAVAX_XML_PARSERS_DOCUMENTBUILDER_HPP_DECL
#define J2CPP_JAVAX_XML_PARSERS_DOCUMENTBUILDER_HPP_DECL

namespace j2cpp { namespace org { namespace w3c { namespace dom { class Document; } } } }
namespace j2cpp { namespace org { namespace w3c { namespace dom { class DOMImplementation; } } } }
namespace j2cpp { namespace org { namespace xml { namespace sax { class ErrorHandler; } } } }
namespace j2cpp { namespace org { namespace xml { namespace sax { class EntityResolver; } } } }
namespace j2cpp { namespace org { namespace xml { namespace sax { class InputSource; } } } }
namespace j2cpp { namespace java { namespace lang { class String; } } }
namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace java { namespace io { class File; } } }
namespace j2cpp { namespace java { namespace io { class InputStream; } } }
namespace j2cpp { namespace javax { namespace xml { namespace validation { class Schema; } } } }

#include <java/io/File.hpp>
#include <java/io/InputStream.hpp>
#include <java/lang/Object.hpp>
#include <java/lang/String.hpp>
#include <javax/xml/validation/Schema.hpp>
#include <org/w3c/dom/DOMImplementation.hpp>
#include <org/w3c/dom/Document.hpp>
#include <org/xml/sax/EntityResolver.hpp>
#include <org/xml/sax/ErrorHandler.hpp>
#include <org/xml/sax/InputSource.hpp>

namespace j2cpp {

namespace javax { namespace xml { namespace parsers {

	class DocumentBuilder;
	class DocumentBuilder
		: public object<DocumentBuilder>
	{
	public:

		J2CPP_DECLARE_CLASS

		J2CPP_DECLARE_METHOD(0)
		J2CPP_DECLARE_METHOD(1)
		J2CPP_DECLARE_METHOD(2)
		J2CPP_DECLARE_METHOD(3)
		J2CPP_DECLARE_METHOD(4)
		J2CPP_DECLARE_METHOD(5)
		J2CPP_DECLARE_METHOD(6)
		J2CPP_DECLARE_METHOD(7)
		J2CPP_DECLARE_METHOD(8)
		J2CPP_DECLARE_METHOD(9)
		J2CPP_DECLARE_METHOD(10)
		J2CPP_DECLARE_METHOD(11)
		J2CPP_DECLARE_METHOD(12)
		J2CPP_DECLARE_METHOD(13)
		J2CPP_DECLARE_METHOD(14)

		explicit DocumentBuilder(jobject jobj)
		: object<DocumentBuilder>(jobj)
		{
		}

		operator local_ref<java::lang::Object>() const;

		void reset();
		local_ref< org::w3c::dom::Document > parse(local_ref< java::io::InputStream >  const&);
		local_ref< org::w3c::dom::Document > parse(local_ref< java::io::InputStream >  const&, local_ref< java::lang::String >  const&);
		local_ref< org::w3c::dom::Document > parse(local_ref< java::lang::String >  const&);
		local_ref< org::w3c::dom::Document > parse(local_ref< java::io::File >  const&);
		local_ref< org::w3c::dom::Document > parse(local_ref< org::xml::sax::InputSource >  const&);
		jboolean isNamespaceAware();
		jboolean isValidating();
		void setEntityResolver(local_ref< org::xml::sax::EntityResolver >  const&);
		void setErrorHandler(local_ref< org::xml::sax::ErrorHandler >  const&);
		local_ref< org::w3c::dom::Document > newDocument();
		local_ref< org::w3c::dom::DOMImplementation > getDOMImplementation();
		local_ref< javax::xml::validation::Schema > getSchema();
		jboolean isXIncludeAware();
	}; //class DocumentBuilder

} //namespace parsers
} //namespace xml
} //namespace javax

} //namespace j2cpp

#endif //J2CPP_JAVAX_XML_PARSERS_DOCUMENTBUILDER_HPP_DECL

#else //J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_JAVAX_XML_PARSERS_DOCUMENTBUILDER_HPP_IMPL
#define J2CPP_JAVAX_XML_PARSERS_DOCUMENTBUILDER_HPP_IMPL

namespace j2cpp {

javax::xml::parsers::DocumentBuilder::operator local_ref<java::lang::Object>() const
{
	return local_ref<java::lang::Object>(get_jobject());
}

void javax::xml::parsers::DocumentBuilder::reset()
{
	return call_method<
		javax::xml::parsers::DocumentBuilder::J2CPP_CLASS_NAME,
		javax::xml::parsers::DocumentBuilder::J2CPP_METHOD_NAME(1),
		javax::xml::parsers::DocumentBuilder::J2CPP_METHOD_SIGNATURE(1),
		void
	>(get_jobject());
}

local_ref< org::w3c::dom::Document > javax::xml::parsers::DocumentBuilder::parse(local_ref< java::io::InputStream > const &a0)
{
	return call_method<
		javax::xml::parsers::DocumentBuilder::J2CPP_CLASS_NAME,
		javax::xml::parsers::DocumentBuilder::J2CPP_METHOD_NAME(2),
		javax::xml::parsers::DocumentBuilder::J2CPP_METHOD_SIGNATURE(2),
		local_ref< org::w3c::dom::Document >
	>(get_jobject(), a0);
}

local_ref< org::w3c::dom::Document > javax::xml::parsers::DocumentBuilder::parse(local_ref< java::io::InputStream > const &a0, local_ref< java::lang::String > const &a1)
{
	return call_method<
		javax::xml::parsers::DocumentBuilder::J2CPP_CLASS_NAME,
		javax::xml::parsers::DocumentBuilder::J2CPP_METHOD_NAME(3),
		javax::xml::parsers::DocumentBuilder::J2CPP_METHOD_SIGNATURE(3),
		local_ref< org::w3c::dom::Document >
	>(get_jobject(), a0, a1);
}

local_ref< org::w3c::dom::Document > javax::xml::parsers::DocumentBuilder::parse(local_ref< java::lang::String > const &a0)
{
	return call_method<
		javax::xml::parsers::DocumentBuilder::J2CPP_CLASS_NAME,
		javax::xml::parsers::DocumentBuilder::J2CPP_METHOD_NAME(4),
		javax::xml::parsers::DocumentBuilder::J2CPP_METHOD_SIGNATURE(4),
		local_ref< org::w3c::dom::Document >
	>(get_jobject(), a0);
}

local_ref< org::w3c::dom::Document > javax::xml::parsers::DocumentBuilder::parse(local_ref< java::io::File > const &a0)
{
	return call_method<
		javax::xml::parsers::DocumentBuilder::J2CPP_CLASS_NAME,
		javax::xml::parsers::DocumentBuilder::J2CPP_METHOD_NAME(5),
		javax::xml::parsers::DocumentBuilder::J2CPP_METHOD_SIGNATURE(5),
		local_ref< org::w3c::dom::Document >
	>(get_jobject(), a0);
}

local_ref< org::w3c::dom::Document > javax::xml::parsers::DocumentBuilder::parse(local_ref< org::xml::sax::InputSource > const &a0)
{
	return call_method<
		javax::xml::parsers::DocumentBuilder::J2CPP_CLASS_NAME,
		javax::xml::parsers::DocumentBuilder::J2CPP_METHOD_NAME(6),
		javax::xml::parsers::DocumentBuilder::J2CPP_METHOD_SIGNATURE(6),
		local_ref< org::w3c::dom::Document >
	>(get_jobject(), a0);
}

jboolean javax::xml::parsers::DocumentBuilder::isNamespaceAware()
{
	return call_method<
		javax::xml::parsers::DocumentBuilder::J2CPP_CLASS_NAME,
		javax::xml::parsers::DocumentBuilder::J2CPP_METHOD_NAME(7),
		javax::xml::parsers::DocumentBuilder::J2CPP_METHOD_SIGNATURE(7),
		jboolean
	>(get_jobject());
}

jboolean javax::xml::parsers::DocumentBuilder::isValidating()
{
	return call_method<
		javax::xml::parsers::DocumentBuilder::J2CPP_CLASS_NAME,
		javax::xml::parsers::DocumentBuilder::J2CPP_METHOD_NAME(8),
		javax::xml::parsers::DocumentBuilder::J2CPP_METHOD_SIGNATURE(8),
		jboolean
	>(get_jobject());
}

void javax::xml::parsers::DocumentBuilder::setEntityResolver(local_ref< org::xml::sax::EntityResolver > const &a0)
{
	return call_method<
		javax::xml::parsers::DocumentBuilder::J2CPP_CLASS_NAME,
		javax::xml::parsers::DocumentBuilder::J2CPP_METHOD_NAME(9),
		javax::xml::parsers::DocumentBuilder::J2CPP_METHOD_SIGNATURE(9),
		void
	>(get_jobject(), a0);
}

void javax::xml::parsers::DocumentBuilder::setErrorHandler(local_ref< org::xml::sax::ErrorHandler > const &a0)
{
	return call_method<
		javax::xml::parsers::DocumentBuilder::J2CPP_CLASS_NAME,
		javax::xml::parsers::DocumentBuilder::J2CPP_METHOD_NAME(10),
		javax::xml::parsers::DocumentBuilder::J2CPP_METHOD_SIGNATURE(10),
		void
	>(get_jobject(), a0);
}

local_ref< org::w3c::dom::Document > javax::xml::parsers::DocumentBuilder::newDocument()
{
	return call_method<
		javax::xml::parsers::DocumentBuilder::J2CPP_CLASS_NAME,
		javax::xml::parsers::DocumentBuilder::J2CPP_METHOD_NAME(11),
		javax::xml::parsers::DocumentBuilder::J2CPP_METHOD_SIGNATURE(11),
		local_ref< org::w3c::dom::Document >
	>(get_jobject());
}

local_ref< org::w3c::dom::DOMImplementation > javax::xml::parsers::DocumentBuilder::getDOMImplementation()
{
	return call_method<
		javax::xml::parsers::DocumentBuilder::J2CPP_CLASS_NAME,
		javax::xml::parsers::DocumentBuilder::J2CPP_METHOD_NAME(12),
		javax::xml::parsers::DocumentBuilder::J2CPP_METHOD_SIGNATURE(12),
		local_ref< org::w3c::dom::DOMImplementation >
	>(get_jobject());
}

local_ref< javax::xml::validation::Schema > javax::xml::parsers::DocumentBuilder::getSchema()
{
	return call_method<
		javax::xml::parsers::DocumentBuilder::J2CPP_CLASS_NAME,
		javax::xml::parsers::DocumentBuilder::J2CPP_METHOD_NAME(13),
		javax::xml::parsers::DocumentBuilder::J2CPP_METHOD_SIGNATURE(13),
		local_ref< javax::xml::validation::Schema >
	>(get_jobject());
}

jboolean javax::xml::parsers::DocumentBuilder::isXIncludeAware()
{
	return call_method<
		javax::xml::parsers::DocumentBuilder::J2CPP_CLASS_NAME,
		javax::xml::parsers::DocumentBuilder::J2CPP_METHOD_NAME(14),
		javax::xml::parsers::DocumentBuilder::J2CPP_METHOD_SIGNATURE(14),
		jboolean
	>(get_jobject());
}

J2CPP_DEFINE_CLASS(javax::xml::parsers::DocumentBuilder,"javax/xml/parsers/DocumentBuilder")
J2CPP_DEFINE_METHOD(javax::xml::parsers::DocumentBuilder,0,"<init>","()V")
J2CPP_DEFINE_METHOD(javax::xml::parsers::DocumentBuilder,1,"reset","()V")
J2CPP_DEFINE_METHOD(javax::xml::parsers::DocumentBuilder,2,"parse","(Ljava/io/InputStream;)Lorg/w3c/dom/Document;")
J2CPP_DEFINE_METHOD(javax::xml::parsers::DocumentBuilder,3,"parse","(Ljava/io/InputStream;Ljava/lang/String;)Lorg/w3c/dom/Document;")
J2CPP_DEFINE_METHOD(javax::xml::parsers::DocumentBuilder,4,"parse","(Ljava/lang/String;)Lorg/w3c/dom/Document;")
J2CPP_DEFINE_METHOD(javax::xml::parsers::DocumentBuilder,5,"parse","(Ljava/io/File;)Lorg/w3c/dom/Document;")
J2CPP_DEFINE_METHOD(javax::xml::parsers::DocumentBuilder,6,"parse","(Lorg/xml/sax/InputSource;)Lorg/w3c/dom/Document;")
J2CPP_DEFINE_METHOD(javax::xml::parsers::DocumentBuilder,7,"isNamespaceAware","()Z")
J2CPP_DEFINE_METHOD(javax::xml::parsers::DocumentBuilder,8,"isValidating","()Z")
J2CPP_DEFINE_METHOD(javax::xml::parsers::DocumentBuilder,9,"setEntityResolver","(Lorg/xml/sax/EntityResolver;)V")
J2CPP_DEFINE_METHOD(javax::xml::parsers::DocumentBuilder,10,"setErrorHandler","(Lorg/xml/sax/ErrorHandler;)V")
J2CPP_DEFINE_METHOD(javax::xml::parsers::DocumentBuilder,11,"newDocument","()Lorg/w3c/dom/Document;")
J2CPP_DEFINE_METHOD(javax::xml::parsers::DocumentBuilder,12,"getDOMImplementation","()Lorg/w3c/dom/DOMImplementation;")
J2CPP_DEFINE_METHOD(javax::xml::parsers::DocumentBuilder,13,"getSchema","()Ljavax/xml/validation/Schema;")
J2CPP_DEFINE_METHOD(javax::xml::parsers::DocumentBuilder,14,"isXIncludeAware","()Z")

} //namespace j2cpp

#endif //J2CPP_JAVAX_XML_PARSERS_DOCUMENTBUILDER_HPP_IMPL

#endif //J2CPP_INCLUDE_IMPLEMENTATION


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

/**
 * @fileoverview Controllers for the exploration editor page and the editor
 *               help tab in the navbar.
 */

oppia.constant('INTERACTION_SPECS', GLOBALS.INTERACTION_SPECS);
oppia.constant('GADGET_SPECS', GLOBALS.GADGET_SPECS);
oppia.constant('PANEL_SPECS', GLOBALS.PANEL_SPECS);

oppia.controller('ExplorationEditor', [
  '$scope', '$http', '$window', '$rootScope', '$log', '$timeout',
  'explorationData', 'editorContextService', 'explorationTitleService',
  'explorationCategoryService', 'explorationGadgetsService',
  'explorationObjectiveService', 'explorationLanguageCodeService',
  'explorationRightsService', 'explorationInitStateNameService',
  'explorationTagsService', 'editabilityService', 'explorationStatesService',
  'routerService', 'graphDataService', 'stateEditorTutorialFirstTimeService',
  'explorationParamSpecsService', 'explorationParamChangesService',
  'explorationWarningsService', '$templateCache', 'explorationContextService',
  'explorationAdvancedFeaturesService',
  function(
      $scope, $http, $window, $rootScope, $log, $timeout,
      explorationData, editorContextService, explorationTitleService,
      explorationCategoryService, explorationGadgetsService,
      explorationObjectiveService, explorationLanguageCodeService,
      explorationRightsService, explorationInitStateNameService,
      explorationTagsService, editabilityService, explorationStatesService,
      routerService, graphDataService, stateEditorTutorialFirstTimeService,
      explorationParamSpecsService, explorationParamChangesService,
      explorationWarningsService, $templateCache, explorationContextService,
      explorationAdvancedFeaturesService) {
    $scope.editabilityService = editabilityService;
    $scope.editorContextService = editorContextService;

    $scope.areGadgetsEnabled = (
      explorationAdvancedFeaturesService.areGadgetsEnabled);

    /**********************************************************
     * Called on initial load of the exploration editor page.
     *********************************************************/
    $rootScope.loadingMessage = 'Loading';

    $scope.explorationId = explorationContextService.getExplorationId();
    $scope.explorationUrl = '/create/' + $scope.explorationId;
    $scope.explorationDataUrl = '/createhandler/data/' + $scope.explorationId;
    $scope.explorationDownloadUrl = (
      '/createhandler/download/' + $scope.explorationId);
    $scope.revertExplorationUrl = (
      '/createhandler/revert/' + $scope.explorationId);

    $scope.getTabStatuses = routerService.getTabStatuses;

    /********************************************
    * Methods affecting the graph visualization.
    ********************************************/
    $scope.areExplorationWarningsVisible = false;
    $scope.toggleExplorationWarningVisibility = function() {
      $scope.areExplorationWarningsVisible = (
        !$scope.areExplorationWarningsVisible);
    };

    $scope.$on('refreshGraph', function() {
      graphDataService.recompute();
      explorationWarningsService.updateWarnings();
    });

    $scope.getExplorationUrl = function(explorationId) {
      return explorationId ? ('/explore/' + explorationId) : '';
    };

    // Initializes the exploration page using data from the backend. Called on
    // page load.
    $scope.initExplorationPage = function(successCallback) {
      explorationData.getData().then(function(data) {
        explorationStatesService.init(data.states);

        explorationTitleService.init(data.title);
        explorationCategoryService.init(data.category);
        explorationGadgetsService.init(data.skin_customizations);
        explorationObjectiveService.init(data.objective);
        explorationLanguageCodeService.init(data.language_code);
        explorationInitStateNameService.init(data.init_state_name);
        explorationTagsService.init(data.tags);
        explorationParamSpecsService.init(data.param_specs);
        explorationParamChangesService.init(data.param_changes || []);

        $scope.explorationTitleService = explorationTitleService;
        $scope.explorationCategoryService = explorationCategoryService;
        $scope.explorationGadgetsService = explorationGadgetsService;
        $scope.explorationObjectiveService = explorationObjectiveService;
        $scope.explorationRightsService = explorationRightsService;
        $scope.explorationInitStateNameService = (
          explorationInitStateNameService);

        $scope.currentUserIsAdmin = data.is_admin;
        $scope.currentUserIsModerator = data.is_moderator;

        $scope.currentUser = data.user;
        $scope.currentVersion = data.version;

        explorationAdvancedFeaturesService.init(data);
        explorationRightsService.init(
          data.rights.owner_names, data.rights.editor_names,
          data.rights.viewer_names, data.rights.status,
          data.rights.cloned_from, data.rights.community_owned,
          data.rights.viewable_if_private);

        if (GLOBALS.can_edit) {
          editabilityService.markEditable();
        }

        graphDataService.recompute();

        if (!editorContextService.getActiveStateName() ||
            !explorationStatesService.getState(
              editorContextService.getActiveStateName())) {
          editorContextService.setActiveStateName(
            explorationInitStateNameService.displayed);
        }

        if (!routerService.isLocationSetToNonStateEditorTab() &&
            !data.states.hasOwnProperty(
              routerService.getCurrentStateFromLocationPath())) {
          routerService.navigateToMainTab();
        }

        explorationWarningsService.updateWarnings();

        $scope.$broadcast('refreshStatisticsTab');
        $scope.$broadcast('refreshVersionHistory', {
          forceRefresh: true
        });

        if (explorationStatesService.getState(
              editorContextService.getActiveStateName())) {
          $scope.$broadcast('refreshStateEditor');
        }

        if (successCallback) {
          successCallback();
        }

        stateEditorTutorialFirstTimeService.init(
          data.show_state_editor_tutorial_on_load);
      });
    };

    $scope.initExplorationPage();

    $scope.$on('initExplorationPage', function(unusedEvtData, successCallback) {
      $scope.initExplorationPage(successCallback);
    });

    var _ID_TUTORIAL_STATE_CONTENT = '#tutorialStateContent';
    var _ID_TUTORIAL_STATE_INTERACTION = '#tutorialStateInteraction';
    var _ID_TUTORIAL_PREVIEW_TAB = '#tutorialPreviewTab';
    var _ID_TUTORIAL_SAVE_BUTTON = '#tutorialSaveButton';

    $scope.EDITOR_TUTORIAL_OPTIONS = [{
      type: 'title',
      heading: 'Tutorial',
      text: (
        'Creating an Oppia exploration is easy! ' +
        'Click \'Next\' to learn how to use the exploration editor.

 ' +
        'You might also find these resources helpful for creating your ' +
        'exploration: ' +
        '
' +
        '
' +
        '' +
        '        Walkthrough of the Oppia Editor' +
        '
' +
        '
' +
        '' + // jscs:disable maximumLineLength
        '        Planning Your Exploration' +
        '
' +
        '
' +
        '        Exploration Design Tips' +
        '
' +
        '
')
    }, {
      type: 'function',
      fn: function(isGoingForward) {
        $('html, body').animate({
          scrollTop: (isGoingForward ? 0 : 20)
        }, 1000);
      }
    }, {
      type: 'element',
      selector: _ID_TUTORIAL_STATE_CONTENT,
      heading: 'Content',
      text: (
        'An Oppia exploration is a conversation between a tutor and a ' +
        'learner that is divided into several \'cards\'.

' +
        'The first part of a card is the content. Here, you can set ' +
        'the scene and ask the learner a question.'),
      placement: 'bottom'
    }, {
      type: 'function',
      fn: function(isGoingForward) {
        var idToScrollTo = (
          isGoingForward ? _ID_TUTORIAL_STATE_INTERACTION :
          _ID_TUTORIAL_STATE_CONTENT);
        $('html, body').animate({
          scrollTop: angular.element(idToScrollTo).offset().top - 200
        }, 1000);
      }
    }, {
      type: 'title',
      heading: 'Interaction',
      text: (
        'After telling Oppia what to say, choose how you want the learner to ' +
        'respond by selecting an interaction type.' +
        'Then, based on the learner\'s response, you can tell Oppia how to ' +
        'reply by creating a response.')
    }, {
      type: 'function',
      fn: function(isGoingForward) {
        var positionToScrollTo = (
          isGoingForward ? 0 :
          angular.element(_ID_TUTORIAL_STATE_INTERACTION).offset().top - 200);
        $('html, body').animate({
          scrollTop: positionToScrollTo
        }, 1000);
      }
    }, {
      type: 'element',
      selector: _ID_TUTORIAL_PREVIEW_TAB,
      heading: 'Preview',
      text: (
        'At any time, you can click the preview button to play through ' +
        'your exploration.'),
      placement: 'bottom'
    }, {
      type: 'element',
      selector: _ID_TUTORIAL_SAVE_BUTTON,
      heading: 'Save',
      text: (
        'When you\'re done making changes, ' +
        'be sure to save your work.

' +
        'That\'s the end of the tour! If you run into any issues, feel free ' +
        'to post in the site forum.'),
      placement: 'bottom'
    }];

    // Replace the ng-joyride template with one that uses <[...]> interpolators
    // instead of/ {{...}} interpolators.
    var ngJoyrideTemplate = $templateCache.get('ng-joyride-title-tplv1.html');
    ngJoyrideTemplate = ngJoyrideTemplate.replace(
      /\{\{/g, '<[').replace(/\}\}/g, ']>');
    $templateCache.put('ng-joyride-title-tplv1.html', ngJoyrideTemplate);

    $scope.onLeaveTutorial = function() {
      editabilityService.onEndTutorial();
      $scope.$apply();
      stateEditorTutorialFirstTimeService.markTutorialFinished();
      $scope.tutorialInProgress = false;
    };

    $scope.tutorialInProgress = false;
    $scope.startTutorial = function() {
      routerService.navigateToMainTab();

      // The $timeout wrapper is needed for all components on the page to load,
      // otherwise elements within ng-if's are not guaranteed to be present on
      // the page.
      $timeout(function() {
        editabilityService.onStartTutorial();
        $scope.tutorialInProgress = true;
      });
    };

    $scope.$on('openEditorTutorial', $scope.startTutorial);
  }
]);

oppia.controller('EditorNavigation', [
  '$scope', '$rootScope', '$timeout', 'routerService',
  'explorationRightsService', 'explorationWarningsService',
  'threadDataService',
  function(
    $scope, $rootScope, $timeout, routerService,
    explorationRightsService, explorationWarningsService, threadDataService) {
    $scope.postTutorialHelpPopoverIsShown = false;

    $scope.$on('openPostTutorialHelpPopover', function() {
      $scope.postTutorialHelpPopoverIsShown = true;
      // Without this, the popover does not trigger.
      $scope.$apply();
      $timeout(function() {
        $scope.postTutorialHelpPopoverIsShown = false;
      }, 5000);
    });

    // This method is here because the trigger for the tutorial is in the site
    // navbar. It broadcasts an event to tell the exploration editor to open the
    // editor tutorial.
    $scope.openEditorTutorial = function() {
      $rootScope.$broadcast('openEditorTutorial');
    };

    $scope.countWarnings = explorationWarningsService.countWarnings;
    $scope.getWarnings = explorationWarningsService.getWarnings;
    $scope.hasCriticalWarnings = explorationWarningsService.hasCriticalWarnings;

    $scope.explorationRightsService = explorationRightsService;
    $scope.getTabStatuses = routerService.getTabStatuses;
    $scope.selectMainTab = routerService.navigateToMainTab;
    $scope.selectPreviewTab = routerService.navigateToPreviewTab;
    $scope.selectSettingsTab = routerService.navigateToSettingsTab;
    $scope.selectStatsTab = routerService.navigateToStatsTab;
    $scope.selectHistoryTab = routerService.navigateToHistoryTab;
    $scope.selectFeedbackTab = routerService.navigateToFeedbackTab;
    $scope.getOpenThreadsCount = threadDataService.getOpenThreadsCount;
  }
]);

oppia.controller('EditorNavbarBreadcrumb', [
  '$scope', 'explorationTitleService', 'routerService',
  function($scope, explorationTitleService, routerService) {
    $scope.navbarTitle = null;
    $scope.$on('explorationPropertyChanged', function() {
      var _MAX_TITLE_LENGTH = 20;
      $scope.navbarTitle = explorationTitleService.savedMemento;
      if ($scope.navbarTitle.length > _MAX_TITLE_LENGTH) {
        $scope.navbarTitle = (
          $scope.navbarTitle.substring(0, _MAX_TITLE_LENGTH - 3) + '...');
      }
    });

    var _TAB_NAMES_TO_HUMAN_READABLE_NAMES = {
      main: 'Edit',
      preview: 'Preview',
      settings: 'Settings',
      stats: 'Statistics',
      history: 'History',
      feedback: 'Feedback'
    };

    $scope.getCurrentTabName = function() {
      if (!routerService.getTabStatuses()) {
        return '';
      } else {
        return _TAB_NAMES_TO_HUMAN_READABLE_NAMES[
          routerService.getTabStatuses().active];
      }
    };
  }
]);

oppia.controller('ExplorationSaveAndPublishButtons', [
  '$scope', '$http', '$rootScope', '$window', '$timeout', '$modal',
  'alertsService', 'changeListService', 'focusService', 'routerService',
  'explorationData', 'explorationRightsService', 'editabilityService',
  'explorationWarningsService', 'siteAnalyticsService',
  function(
      $scope, $http, $rootScope, $window, $timeout, $modal,
      alertsService, changeListService, focusService, routerService,
      explorationData, explorationRightsService, editabilityService,
      explorationWarningsService, siteAnalyticsService) {
    // Whether or not a save action is currently in progress.
    $scope.isSaveInProgress = false;
    // Whether or not a discard action is currently in progress.
    $scope.isDiscardInProgress = false;
    // The last 'save' or 'discard' action. Can be null (no such action has
    // been performed yet), 'save' (the last action was a save) or 'discard'
    // (the last action was a discard).
    $scope.lastSaveOrDiscardAction = null;

    $scope.isPrivate = function() {
      return explorationRightsService.isPrivate();
    };

    $scope.isExplorationLockedForEditing = function() {
      return changeListService.isExplorationLockedForEditing();
    };
    $scope.isEditableOutsideTutorialMode = function() {
      return editabilityService.isEditableOutsideTutorialMode();
    };
    $scope.countWarnings = function() {
      return explorationWarningsService.countWarnings();
    };

    $scope.discardChanges = function() {
      var confirmDiscard = confirm('Do you want to discard your changes?');
      if (confirmDiscard) {
        alertsService.clearWarnings();
        $rootScope.$broadcast('externalSave');

        $scope.isDiscardInProgress = true;
        changeListService.discardAllChanges();
        alertsService.addSuccessMessage('Changes discarded.');
        $rootScope.$broadcast('initExplorationPage', function() {
          $scope.lastSaveOrDiscardAction = 'discard';
          $scope.isDiscardInProgress = false;
        });
      }
    };

    $scope.getChangeListLength = function() {
      return changeListService.getChangeList().length;
    };

    $scope.isExplorationSaveable = function() {
      return (
        $scope.isExplorationLockedForEditing() &&
        !$scope.isSaveInProgress && (
          ($scope.isPrivate() &&
            !explorationWarningsService.hasCriticalWarnings()) ||
          (!$scope.isPrivate() &&
            explorationWarningsService.countWarnings() === 0)
        )
      );
    };

    $window.addEventListener('beforeunload', function(e) {
      if ($scope.isExplorationLockedForEditing()) {
        var confirmationMessage = (
          'You have unsaved changes which will be lost if you leave the page.');
        (e || $window.event).returnValue = confirmationMessage;
        return confirmationMessage;
      }
    });

    $scope.isPublic = function() {
      return explorationRightsService.isPublic();
    };

    $scope.showPublishExplorationModal = function() {
      $scope.publishModalIsOpening = true;
      alertsService.clearWarnings();
      var modalInstance = $modal.open({
        templateUrl: 'modals/publishExploration',
        backdrop: true,
        controller: [
          '$scope', '$modalInstance', function($scope, $modalInstance) {
            $scope.publish = $modalInstance.close;

            $scope.cancel = function() {
              $modalInstance.dismiss('cancel');
              alertsService.clearWarnings();
            };
          }]
      });

      modalInstance.result.then(function() {
        explorationRightsService.saveChangeToBackend({
          is_public: true
        });
        siteAnalyticsService.registerPublishExplorationEvent(
          explorationData.explorationId);
      });

      modalInstance.opened.then(function() {
        $scope.publishModalIsOpening = false;
      });
    };

    $scope.getPublishExplorationButtonTooltip = function() {
      if (explorationWarningsService.countWarnings() > 0) {
        return 'Please resolve the warnings before publishing.';
      } else if ($scope.isExplorationLockedForEditing()) {
        return 'Please save your changes before publishing.';
      } else {
        return 'Publish to Gallery';
      }
    };

    $scope.getSaveButtonTooltip = function() {
      if (explorationWarningsService.hasCriticalWarnings() > 0) {
        return 'Please resolve the warnings.';
      } else if ($scope.isPrivate()) {
        return 'Save Draft';
      } else {
        return 'Publish Changes';
      }
    };

    // This flag is used to ensure only one save exploration modal can be open
    // at any one time.
    var _modalIsOpen = false;

    $scope.saveChanges = function() {
      // This flag is used to change text of save button to "Loading..." to
      // add indication for user that something is happening.
      $scope.saveModalIsOpening = true;

      routerService.savePendingChanges();

      $scope.changeListSummaryUrl = (
        '/createhandler/change_list_summary/' + explorationData.explorationId);

      $http.post($scope.changeListSummaryUrl, {
        change_list: changeListService.getChangeList(),
        version: explorationData.data.version
      }).success(function(data) {
        if (data.error) {
          alertsService.addWarning(data.error);
          return;
        }

        var explorationPropertyChanges = (
          data.summary.exploration_property_changes);
        var statePropertyChanges = data.summary.state_property_changes;
        var changedStates = data.summary.changed_states;
        var addedStates = data.summary.added_states;
        var deletedStates = data.summary.deleted_states;
        var gadgetPropertyChanges = data.summary.gadget_property_changes;
        var changedGadgets = data.summary.changed_gadgets;
        var addedGadgets = data.summary.added_gadgets;
        var deletedGadgets = data.summary.deleted_gadgets;
        var warningMessage = data.warning_message;

        var changesExist = (
          !$.isEmptyObject(explorationPropertyChanges) ||
          !$.isEmptyObject(statePropertyChanges) ||
          !$.isEmptyObject(gadgetPropertyChanges) ||
          changedStates.length > 0 ||
          changedGadgets.length > 0 ||
          addedStates.length > 0 ||
          addedGadgets.length > 0 ||
          deletedStates.length > 0 ||
          deletedGadgets.length > 0);

        if (!changesExist) {
          alertsService.addWarning('Your changes cancel each other out, ' +
            'so nothing has been saved.');
          $scope.saveModalIsOpening = false;
          changeListService.discardAllChanges();
          return;
        }

        if (!explorationRightsService.isPrivate() && warningMessage) {
          // If the exploration is not private, warnings should be fixed before
          // it can be saved.
          alertsService.addWarning(warningMessage);
          return;
        }

        alertsService.clearWarnings();

        // If the modal is open, do not open another one.
        if (_modalIsOpen) {
          return;
        }

        var modalInstance = $modal.open({
          templateUrl: 'modals/saveExploration',
          backdrop: true,
          resolve: {
            explorationPropertyChanges: function() {
              return explorationPropertyChanges;
            },
            statePropertyChanges: function() {
              return statePropertyChanges;
            },
            changedStates: function() {
              return changedStates;
            },
            addedStates: function() {
              return addedStates;
            },
            deletedStates: function() {
              return deletedStates;
            },
            gadgetPropertyChanges: function() {
              return gadgetPropertyChanges;
            },
            changedGadgets: function() {
              return changedGadgets;
            },
            addedGadgets: function() {
              return addedGadgets;
            },
            deletedGadgets: function() {
              return deletedGadgets;
            },
            isExplorationPrivate: function() {
              return explorationRightsService.isPrivate();
            }
          },
          controller: [
            '$scope', '$modalInstance', 'explorationPropertyChanges',
            'statePropertyChanges', 'changedStates', 'addedStates',
            'deletedStates', 'gadgetPropertyChanges', 'changedGadgets',
            'addedGadgets', 'deletedGadgets', 'isExplorationPrivate',
            function($scope, $modalInstance, explorationPropertyChanges,
                     statePropertyChanges, changedStates, addedStates,
                     deletedStates, gadgetPropertyChanges, changedGadgets,
                     addedGadgets, deletedGadgets, isExplorationPrivate) {
              $scope.explorationPropertyChanges = explorationPropertyChanges;
              $scope.statePropertyChanges = statePropertyChanges;
              $scope.changedStates = changedStates;
              $scope.addedStates = addedStates;
              $scope.deletedStates = deletedStates;
              $scope.gadgetPropertyChanges = gadgetPropertyChanges;
              $scope.changedGadgets = changedGadgets;
              $scope.addedGadgets = addedGadgets;
              $scope.deletedGadgets = deletedGadgets;
              $scope.isExplorationPrivate = isExplorationPrivate;

              // For reasons of backwards compatibility, the following keys
              // should not be changed.
              // TODO(sll): The keys for this dict already appear in
              // EditorServices.changeListService; consider deduplicating.
              var EXP_BACKEND_NAMES_TO_HUMAN_NAMES = {
                category: 'Category',
                init_state_name: 'First card',
                language_code: 'Language',
                objective: 'Objective',
                param_changes: 'Initial parameter changes',
                param_specs: 'Parameter specifications',
                tags: 'Tags',
                title: 'Title'
              };

              // For reasons of backwards compatibility, the following keys
              // should not be changed.
              var EXP_PROPERTIES_WHICH_ARE_SIMPLE_STRINGS = {
                category: true,
                init_state_name: true,
                objective: true,
                title: true
              };

              // For reasons of backwards compatibility, the following keys
              // should not be changed.
              var STATE_BACKEND_NAMES_TO_HUMAN_NAMES = {
                answer_groups: 'Responses',
                confirmed_unclassified_answers: (
                  'Confirmed unclassified answers'),
                content: 'Content',
                default_outcome: 'Default outcome',
                fallbacks: 'Fallbacks',
                name: 'Card name',
                param_changes: 'Parameter changes',
                widget_customization_args: 'Interaction customizations',
                widget_id: 'Interaction type'
              };

              // For reasons of backwards compatibility, the following keys
              // should not be changed.
              var GADGET_BACKEND_NAMES_TO_HUMAN_NAMES = {
                gadget_customization_args: 'Gadget customizations',
                gadget_visibility: 'Gadget visibility between states',
                name: 'Gadget name'
              };

              // An ordered list of state properties that determines the order
              // in which to show them in the save confirmation modal.
              // For reasons of backwards compatibility, the following keys
              // should not be changed.
              // TODO(sll): Implement this fully. Currently there is no sorting.
              $scope.ORDERED_STATE_PROPERTIES = [
                'name', 'param_changes', 'content', 'widget_id',
                'widget_customization_args', 'answer_groups',
                'default_outcome', 'fallbacks'
              ];

              $scope.explorationChangesExist = !$.isEmptyObject(
                $scope.explorationPropertyChanges);
              $scope.stateChangesExist = !$.isEmptyObject(
                $scope.statePropertyChanges);
              $scope.gadgetChangesExist = !$.isEmptyObject(
                $scope.gadgetPropertyChanges);

              var getLongFormPropertyChange = function(
                  humanReadableName, changeInfo) {
                return (
                  humanReadableName + ' (from \'' + changeInfo.old_value +
                  '\' to \'' + changeInfo.new_value + '\')');
              };

              $scope.formatExplorationPropertyChange = function(
                  propertyName, changeInfo) {
                if (EXP_PROPERTIES_WHICH_ARE_SIMPLE_STRINGS[propertyName]) {
                  return getLongFormPropertyChange(
                    EXP_BACKEND_NAMES_TO_HUMAN_NAMES[propertyName],
                    changeInfo);
                } else {
                  return EXP_BACKEND_NAMES_TO_HUMAN_NAMES[propertyName];
                }
              };

              $scope.formatStatePropertyChange = function(
                  propertyName, changeInfo) {
                if (propertyName == 'name') {
                  return getLongFormPropertyChange(
                    STATE_BACKEND_NAMES_TO_HUMAN_NAMES[propertyName],
                    changeInfo);
                } else {
                  return STATE_BACKEND_NAMES_TO_HUMAN_NAMES[propertyName];
                }
              };

              $scope.formatGadgetPropertyChange = function(
                  propertyName, changeInfo) {
                if (propertyName == 'name') {
                  return getLongFormPropertyChange(
                    GADGET_BACKEND_NAMES_TO_HUMAN_NAMES[propertyName],
                    changeInfo);
                } else {
                  return GADGET_BACKEND_NAMES_TO_HUMAN_NAMES[propertyName];
                }
              };

              $scope.formatStateList = function(stateList) {
                return stateList.join('; ');
              };

              $scope.formatGadgetList = function(gadgetList) {
                return gadgetList.join('; ');
              };

              $scope.save = function(commitMessage) {
                $modalInstance.close(commitMessage);
              };
              $scope.cancel = function() {
                $modalInstance.dismiss('cancel');
                alertsService.clearWarnings();
              };
            }
          ]
        });

        // Modal is Opened
        _modalIsOpen = true;
        $scope.saveModalIsOpening = false;

        modalInstance.opened.then(function() {
          // The $timeout seems to be needed in order to give the modal time to
          // render.
          $timeout(function() {
            focusService.setFocus('saveChangesModalOpened');
          });
        });

        modalInstance.result.then(function(commitMessage) {
          $scope.isSaveInProgress = true;
          _modalIsOpen = false;

          var changeList = changeListService.getChangeList();
          explorationData.save(changeList, commitMessage, function() {
            changeListService.discardAllChanges();
            $rootScope.$broadcast('initExplorationPage');
            $rootScope.$broadcast('refreshVersionHistory', {
              forceRefresh: true
            });
            alertsService.addSuccessMessage('Changes saved.');
            $scope.lastSaveOrDiscardAction = 'save';
            $scope.isSaveInProgress = false;
          }, function() {
            $scope.isSaveInProgress = false;
          });

          if ($scope.isPrivate()) {
            siteAnalyticsService.registerCommitChangesToPrivateExplorationEvent(
              explorationData.explorationId);
          } else {
            siteAnalyticsService.registerCommitChangesToPublicExplorationEvent(
              explorationData.explorationId);
          }
        }, function() {
          _modalIsOpen = false;
        });
      });
    };
  }
]);


text:
package com.intel.bluetooth;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;

import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;

/**
 * This is Common class to solve JNI call backs problem
 *
 *

 * Your application should not use this class directly.
 *
 */
class SearchServicesThread extends Thread {

	private static int transIDGenerator = 0;

	private static Hashtable threads = new Hashtable();

	private BluetoothStack stack;

	private SearchServicesRunnable serachRunnable;

	private int transID;

	private int[] attrSet;

	private Vector servicesRecords = new Vector();

	UUID[] uuidSet;

	private RemoteDevice device;

	private DiscoveryListener listener;

	private BluetoothStateException startException;

	private boolean started = false;

	private boolean finished = false;

	private boolean terminated = false;

	private Object serviceSearchStartedEvent = new Object();

	private static synchronized int nextThreadNum() {
		return ++transIDGenerator;
	}

	private SearchServicesThread(int transID, BluetoothStack stack, SearchServicesRunnable serachRunnable,
			int[] attrSet, UUID[] uuidSet, RemoteDevice device, DiscoveryListener listener) {
		super("SearchServicesThread-" + transID);
		this.stack = stack;
		this.serachRunnable = serachRunnable;
		this.transID = transID;
		this.attrSet = attrSet;
		this.listener = listener;
		this.uuidSet = uuidSet;
		this.device = device;
	}

	/**
	 * Start Services Search and wait for startException or
	 * searchServicesStartedCallback
	 */
	static int startSearchServices(BluetoothStack stack, SearchServicesRunnable searchRunnable, int[] attrSet,
			UUID[] uuidSet, RemoteDevice device, DiscoveryListener listener) throws BluetoothStateException {
		SearchServicesThread t;
		synchronized (threads) {
			int runningCount = countRunningSearchServicesThreads(stack);
			int concurrentAllow = Integer.valueOf(stack.getLocalDeviceProperty(BluetoothConsts.PROPERTY_BLUETOOTH_SD_TRANS_MAX)).intValue();
			if (runningCount >= concurrentAllow) {
				throw new BluetoothStateException("Already running " + runningCount + " service discovery transactions");
			}
			t = (new SearchServicesThread(nextThreadNum(), stack, searchRunnable, attrSet, uuidSet, device, listener));
			threads.put(new Integer(t.getTransID()), t);
		}
		// In case the BTStack hangs, exit JVM anyway
		UtilsJavaSE.threadSetDaemon(t);
		synchronized (t.serviceSearchStartedEvent) {
			t.start();
			while (!t.started && !t.finished) {
				try {
					t.serviceSearchStartedEvent.wait();
				} catch (InterruptedException e) {
					return 0;
				}
				if (t.startException != null) {
					throw t.startException;
				}
			}
		}
		if (t.started) {
			return t.getTransID();
		} else {
			// This is arguable according to JSR-82 we can probably return 0...
			throw new BluetoothStateException();
		}
	}

	private static int countRunningSearchServicesThreads(BluetoothStack stack) {
		int count = 0;
		for (Enumeration en = threads.elements(); en.hasMoreElements();) {
			SearchServicesThread t = (SearchServicesThread) en.nextElement();
			if (t.stack == stack) {
				count++;
			}
		}
		return count;
	}

	static SearchServicesThread getServiceSearchThread(int transID) {
		return (SearchServicesThread) threads.get(new Integer(transID));
	}

	public void run() {
		int respCode = DiscoveryListener.SERVICE_SEARCH_ERROR;
		try {
			BlueCoveImpl.setThreadBluetoothStack(stack);
			respCode = serachRunnable.runSearchServices(this, attrSet, uuidSet, device, listener);
		} catch (BluetoothStateException e) {
			startException = e;
			return;
		} finally {
			finished = true;
			unregisterThread();
			synchronized (serviceSearchStartedEvent) {
				serviceSearchStartedEvent.notifyAll();
			}
			DebugLog.debug("runSearchServices ends", getTransID());
			if (started) {
				Utils.j2meUsagePatternDellay();
				listener.serviceSearchCompleted(getTransID(), respCode);
			}
		}
	}

	private void unregisterThread() {
		synchronized (threads) {
			threads.remove(new Integer(getTransID()));
		}
	}

	public void searchServicesStartedCallback() {
		DebugLog.debug("searchServicesStartedCallback", getTransID());
		started = true;
		synchronized (serviceSearchStartedEvent) {
			serviceSearchStartedEvent.notifyAll();
		}
	}

	int getTransID() {
		return this.transID;
	}

	boolean setTerminated() {
		if (isTerminated()) {
			return false;
		}
		terminated = true;
		unregisterThread();
		return true;
	}

	boolean isTerminated() {
		return terminated;
	}

	RemoteDevice getDevice() {
		return this.device;
	}

	DiscoveryListener getListener() {
		return this.listener;
	}

	void addServicesRecords(ServiceRecord servRecord) {
		this.servicesRecords.addElement(servRecord);
	}

	Vector getServicesRecords() {
		return this.servicesRecords;
	}

	public int[] getAttrSet() {
		final int[] requiredAttrIDs = new int[] { BluetoothConsts.ServiceRecordHandle,
				BluetoothConsts.ServiceClassIDList, BluetoothConsts.ServiceRecordState, BluetoothConsts.ServiceID,
				BluetoothConsts.ProtocolDescriptorList };
		if (this.attrSet == null) {
			return requiredAttrIDs;
		}
		// Append unique attributes from attrSet
		int len = requiredAttrIDs.length + this.attrSet.length;
		for (int i = 0; i < this.attrSet.length; i++) {
			for (int k = 0; k < requiredAttrIDs.length; k++) {
				if (requiredAttrIDs[k] == this.attrSet[i]) {
					len--;
					break;
				}
			}
		}

		int[] allIDs = new int[len];
		System.arraycopy(requiredAttrIDs, 0, allIDs, 0, requiredAttrIDs.length);
		int appendPosition = requiredAttrIDs.length;
		nextAttribute: for (int i = 0; i < this.attrSet.length; i++) {
			for (int k = 0; k < requiredAttrIDs.length; k++) {
				if (requiredAttrIDs[k] == this.attrSet[i]) {
					continue nextAttribute;
				}
			}
			allIDs[appendPosition] = this.attrSet[i];
			appendPosition++;
		}
		return allIDs;
	}

}


text:
title: Installing therubyracer on macOS Catalina
date: 2020-01-14
layout: post
categories: developing
---

Source: [libv8 fails to build on Catalina 10.15 #282](https://github.com/rubyjs/libv8/issues/282#issuecomment-568538097)

Another one of those troublesome gems, here is my definite guide to installing `therubyracer`, along with an older v8 from brew.

    env \
      CXX=clang++ \
      GYPFLAGS=-Dmac_deployment_target=10.9 \
    gem install libv8 --version 3.16.14.19


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

namespace CamadaDados.Entidades
{
    public class Pedido_Produto
    {
        private int pedido_produtoId;
        private int produtoId;
        private float valor;
        private int quantidade;
        private int pedidoId;
        private int adicional_comidaId;

        public Pedido_Produto()
        {
            this.pedido_produtoId = 0;
            this.produtoId = 0;
            this.valor = 0;
            this.quantidade = 0;
            this.pedidoId = 0;
            this.adicional_comidaId = 0;
        }

        public Pedido_Produto(int pedido_produtoId, int produtoId, float valor, int quantidade, int pedidoId, int adicional_comidaId)
        {
            this.pedido_produtoId = pedido_produtoId;
            this.produtoId = produtoId;
            this.valor = valor;
            this.quantidade = quantidade;
            this.pedidoId = pedidoId;
            this.adicional_comidaId = adicional_comidaId;
        }

        public int getPedido_produtoId()
        {
            return this.pedido_produtoId;
        }

        public void setPedido_produtoId(int pedido_produtoId)
        {
            this.pedido_produtoId = pedido_produtoId;
        }

        public int getProdutoId()
        {
            return this.produtoId;
        }

        public void setProdutoId(int produtoId)
        {
            this.produtoId = produtoId;
        }

        public float getValor()
        {
            return this.valor;
        }

        public void setValor(float valor)
        {
            this.valor = valor;
        }

        public int getQuantidade()
        {
            return this.quantidade;
        }

        public void setQuantidade(int quantidade)
        {
            this.quantidade = quantidade;
        }

        public int getPedidoId()
        {
            return this.pedidoId;
        }

        public void setPedidoId(int pedidoId)
        {
            this.pedidoId = pedidoId;
        }

        public int getAdicional_comidaId()
        {
            return this.adicional_comidaId;
        }

        public void setAdicional_comidaId(int adicional_comidaId)
        {
            this.adicional_comidaId = adicional_comidaId;
        }
    }
}


text:
package com.vincent.filepicker.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;

import com.vincent.filepicker.Constant;
import com.vincent.filepicker.DividerGridItemDecoration;
import com.vincent.filepicker.R;
import com.vincent.filepicker.adapter.OnSelectStateListener;
import com.vincent.filepicker.adapter.VideoPickAdapter;
import com.vincent.filepicker.filter.FileFilter;
import com.vincent.filepicker.filter.callback.FilterResultCallback;
import com.vincent.filepicker.filter.entity.Directory;
import com.vincent.filepicker.filter.entity.VideoFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Vincent Woo
 * Date: 2016/10/21
 * Time: 14:02
 */

public class VideoPickActivity extends BaseActivity {
    public static final String THUMBNAIL_PATH = "FilePick";

    public static final String IS_NEED_CAMERA = "IsNeedCamera";

    public static final int DEFAULT_MAX_NUMBER = 9;
    public static final int COLUMN_NUMBER = 3;
    private int mMaxNumber;
    private int mCurrentNumber = 0;
    private Toolbar mTbImagePick;
    private RecyclerView mRecyclerView;
    private VideoPickAdapter mAdapter;
    private boolean isNeedCamera;
    private ArrayList<VideoFile> mSelectedList = new ArrayList<>();
    private ProgressBar mProgressBar;

    @Override
    void permissionGranted() {
        loadData();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_video_pick);

        mMaxNumber = getIntent().getIntExtra(Constant.MAX_NUMBER, DEFAULT_MAX_NUMBER);
        isNeedCamera = getIntent().getBooleanExtra(IS_NEED_CAMERA, false);
        initView();

        super.onCreate(savedInstanceState);
    }

    private void initView() {
        mTbImagePick = (Toolbar) findViewById(R.id.tb_video_pick);
        mTbImagePick.setTitle(mCurrentNumber + "/" + mMaxNumber);
        setSupportActionBar(mTbImagePick);
        mTbImagePick.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mRecyclerView = (RecyclerView) findViewById(R.id.rv_video_pick);
        GridLayoutManager layoutManager = new GridLayoutManager(this, COLUMN_NUMBER);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.addItemDecoration(new DividerGridItemDecoration(this));

        mAdapter = new VideoPickAdapter(this, isNeedCamera, mMaxNumber);
        mRecyclerView.setAdapter(mAdapter);

        mAdapter.setOnSelectStateListener(new OnSelectStateListener<VideoFile>() {
            @Override
            public void OnSelectStateChanged(boolean state, VideoFile file) {
                if (state) {
                    mSelectedList.add(file);
                    mCurrentNumber++;
                } else {
                    mSelectedList.remove(file);
                    mCurrentNumber--;
                }
                mTbImagePick.setTitle(mCurrentNumber + "/" + mMaxNumber);
            }
        });

        mProgressBar = (ProgressBar) findViewById(R.id.pb_video_pick);
        File folder = new File(getExternalCacheDir().getAbsolutePath() + File.separator + THUMBNAIL_PATH);
        if (!folder.exists()) {
            mProgressBar.setVisibility(View.VISIBLE);
        } else {
            mProgressBar.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Constant.REQUEST_CODE_TAKE_VIDEO:
                if (resultCode == RESULT_OK) {
                    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    File file = new File(mAdapter.mVideoPath);
                    Uri contentUri = Uri.fromFile(file);
                    mediaScanIntent.setData(contentUri);
                    sendBroadcast(mediaScanIntent);

                    loadData();
                }
                break;
        }
    }

    private void loadData() {
        FileFilter.getVideos(this, new FilterResultCallback<VideoFile>() {
            @Override
            public void onResult(List<Directory<VideoFile>> directories) {
                mProgressBar.setVisibility(View.GONE);
                List<VideoFile> list = new ArrayList<>();
                for (Directory<VideoFile> directory : directories) {
                    list.addAll(directory.getFiles());
                }

                for (VideoFile file : mSelectedList) {
                    int index = list.indexOf(file);
                    if (index != -1) {
                        list.get(index).setSelected(true);
                    }
                }

                mAdapter.refresh(list);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_image_pick, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_done) {
            Intent intent = new Intent();
            intent.putParcelableArrayListExtra(Constant.RESULT_PICK_VIDEO, mSelectedList);
            setResult(RESULT_OK, intent);
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}


text:
import EmberObject from '@ember/object';

interface TriggerActionOptions {
    action?: string | undefined;
    target?: EmberObject | undefined;
    actionContext?: EmberObject | undefined;
}

/**
 * Ember.TargetActionSupport is a mixin that can be included in a class to add a triggerAction method
 * with semantics similar to the Handlebars {{action}} helper. In normal Ember usage, the {{action}}
 * helper is usually the best choice. This mixin is most often useful when you are doing more
 * complex event handling in Components.
 */
export default interface TargetActionSupport {
    triggerAction(opts: TriggerActionOptions): boolean;
}


text:
package ch.ninecode.cim

import java.io.UnsupportedEncodingException
import java.net.URLDecoder
import java.util.Properties

import scala.tools.nsc.io.Jar
import scala.util.Random

import org.apache.spark.SparkConf
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.SparkSession
import org.slf4j.Logger
import org.slf4j.LoggerFactory

import ch.ninecode.model.Element

case class CIMDifference (spark: SparkSession, options: CIMDifferenceOptions) extends CIMRDD
{
    implicit val session: SparkSession = spark
    implicit val log: Logger = LoggerFactory.getLogger(getClass)

    val FROMSUFFIX = "_from"
    val TOSUFFIX = "_to"
    val FROMPATTERN = s"%s$FROMSUFFIX"
    val TOPATTERN = s"%s$TOSUFFIX"
    var PATTERN: String = FROMPATTERN

    override def pattern: String = PATTERN

    def readCIM (files: Seq[String], pattern: String): Unit =
    {
        val reader_options = scala.collection.mutable.HashMap[String, String](
            "ch.ninecode.cim.name_template" -> pattern
        )
        options.cimopts.map(pair => reader_options.put(pair._1, pair._2))
        val filelist = files.mkString(",")
        reader_options.put("path", filelist)
        log.info(s"reading CIM files $filelist")
        val elements = session.read.format("ch.ninecode.cim").options(reader_options).load(files: _*)
        log.info(s"${elements.count} elements")
    }

    def nameAndSuffix (pair: (Int, RDD[_])): Option[(String, String)] =
    {
        val (_, rdd) = pair
        val name = rdd.name
        if (name.endsWith(FROMSUFFIX))
            Some((name.substring(0, name.length - FROMSUFFIX.length), FROMSUFFIX))
        else
            if (name.endsWith(TOSUFFIX))
                Some((name.substring(0, name.length - TOSUFFIX.length), TOSUFFIX))
            else
                None
    }

    def execute (): Unit =
    {
        val target = if ("" != options.output) s" ⇒ ${options.output}" else ""
        log.info(s"${options.mode.toString} from ${options.from.mkString(",")} to ${options.to.mkString(",")}$target")
        readCIM(options.from, FROMPATTERN)
        readCIM(options.to, TOPATTERN)

        PATTERN = FROMPATTERN
        val from = getOrElse[Element].keyBy(_.id)
        PATTERN = TOPATTERN
        val to = getOrElse[Element].keyBy(_.id)

        val join = from.fullOuterJoin(to)

        options.mode match
        {
            case Mode.ChangeSet =>
                CIMDifferenceChangeSet(options).execute(join)
            case Mode.HumanReadable =>
                CIMDifferenceRaw(options).execute(join)
            case Mode.Summary =>
                CIMDifferenceSummarize(options).execute(join)
        }
    }
}

object CIMDifference
{
    val properties: Properties =
    {
        val in = this.getClass.getResourceAsStream("/application.properties")
        val p = new Properties()
        p.load(in)
        in.close()
        p
    }
    val APPLICATION_NAME: String = properties.getProperty("artifactId")
    val APPLICATION_VERSION: String = properties.getProperty("version")
    val SPARK: String = properties.getProperty("spark")

    def jarForObject (obj: Object): String =
    {
        // see https://stackoverflow.com/questions/320542/how-to-get-the-path-of-a-running-jar-file
        var ret = obj.getClass.getProtectionDomain.getCodeSource.getLocation.getPath
        try
        {
            ret = URLDecoder.decode(ret, "UTF-8")
        }
        catch
        {
            case e: UnsupportedEncodingException => e.printStackTrace()
        }
        if (!ret.toLowerCase().endsWith(".jar"))
        {
            // as an aid to debugging, make jar in tmp and pass that name
            val name = s"/tmp/${Random.nextInt(99999999)}.jar"
            val writer = new Jar(new scala.reflect.io.File(new java.io.File(name))).jarWriter()
            writer.addDirectory(new scala.reflect.io.Directory(new java.io.File(s"${ret}ch/")), "ch/")
            writer.close()
            ret = name
        }

        ret
    }

    /**
     * Main entry point for the Export program.
     *
     * @param args command line arguments
     */
    def main (args: Array[String])
    {
        val optionparser = new CIMDifferenceOptionsParser(APPLICATION_NAME, APPLICATION_VERSION)

        optionparser.parse(args, CIMDifferenceOptions()) match
        {
            case Some(options) =>
                if (options.valid)
                {
                    if (options.loglevel != LogLevels.OFF)
                    {
                        org.apache.log4j.LogManager.getLogger("ch.ninecode.cim.CIMDifference").setLevel(LogLevels.toLog4j(options.loglevel))
                    }
                    val log = LoggerFactory.getLogger(this.getClass)

                    val configuration = new SparkConf()
                    configuration.setAppName(APPLICATION_NAME)
                    if ("" != options.master)
                        configuration.setMaster(options.master)
                    if (options.sparkopts.nonEmpty)
                        options.sparkopts.map(pair => configuration.set(pair._1, pair._2))
                    // get the necessary jar files to send to the cluster
                    configuration.setJars(Array(jarForObject(new DefaultSource())))
                    // register for Kryo serialization
                    configuration.registerKryoClasses(CIMClasses.list)

                    val session_builder = SparkSession.builder()
                    val session = session_builder.config(configuration).getOrCreate()
                    val version = session.version
                    log.info(s"Spark $version session established")
                    if (version.take(SPARK.length) != SPARK.take(version.length))
                        log.warn(s"Spark version ($version) does not match the version ($SPARK) used to build $APPLICATION_NAME")

                    try
                    {
                        val diff = new CIMDifference(session, options)
                        diff.execute()
                    }
                    finally
                    {
                        session.stop()
                    }
                }
                if (!options.unittest)
                    sys.exit(0)
            case None =>
                sys.exit(1)
        }
    }
}


text:
#include "GPSWatch_sys_types.h"
#include "TIM_bridge.h"
#include <sys/timeb.h>
#include <time.h>

#define USEC_CONVERT 1000UL

/*---------------------------------------------------------------------
 * Timer "Object" Structure Declaration
 *    [next] is the mechanism used to collect and sequence timers.
 *    Timer instances are strung together in an active (animate)
 *    list and an inactive (inanimate) list.  The next pointer
 *    provides the "hole for the beads".
 *    [expiration] is the system clock time at which this
 *    timer will pop.
 *    [recurrence] is the repeating expiration duration
 *    [event] is the handle of the event that the timer will
 *    generate upon expiration.
 *-------------------------------------------------------------------*/
typedef struct ETimer_s ETimer_t;
struct ETimer_s {
  ETimer_t * next;
  ETimer_time_t expiration;
  ETimer_time_t recurrence;
  Escher_xtUMLEvent_t * event;
  u4_t accesskey;
};

#ifdef USED_TO_ALLOW_PAUSING
static ETimer_time_t start_of_pause = 0;
static bool paused = false;
#endif
static ETimer_time_t tinit = 0;
static struct timeb systyme;
#if ESCHER_SYS_MAX_XTUML_TIMERS > 0
static ETimer_t swtimers[ ESCHER_SYS_MAX_XTUML_TIMERS ];  /* system.clr color */
static ETimer_t * animate = 0, * inanimate = 0;

static void timer_insert_sorted( ETimer_t * );
static void timer_fire( ETimer_t * const );
static ETimer_t *timer_start( const ETimer_time_t, Escher_xtUMLEvent_t * const );
static bool timer_cancel( ETimer_t * const );
static bool timer_find_and_delete( ETimer_t * const );
#endif   /* if ESCHER_SYS_MAX_XTUML_TIMERS > 0 */
static ETimer_time_t ETimer_msec_time( void );

#if ESCHER_SYS_MAX_XTUML_TIMERS > 0
/*=====================================================================
 * BridgePoint Primitive:
 * <timer_inst_ref_var> = TIM::timer_start(
 *   microseconds:<integer_var>,
 *   event_inst:<event_inst_var> )
 * This bridge starts up an instance of a one-shot xtUML timer.
 *===================================================================*/
Escher_Timer_t *
TIM_timer_start(
  Escher_xtUMLEvent_t * ee_event_inst,
  const Escher_uSec_t ee_microseconds )
{
  /* Insert implementation specific code here.  */
  ETimer_t * t = timer_start( ee_microseconds/USEC_CONVERT, ee_event_inst );
  t->recurrence = 0;
  return (Escher_Timer_t *) t;
}

/*=====================================================================
 * BridgePoint Primitive:
 * <timer_inst_ref_var> = TIM::timer_start_recurring(
 *   microseconds:<integer_var>,
 *   event_inst:<event_inst_var> )
 * This bridge starts up an instance of a recurring xtUML timer.
 *===================================================================*/
Escher_Timer_t *
TIM_timer_start_recurring(
  Escher_xtUMLEvent_t * ee_event_inst,
  const Escher_uSec_t ee_microseconds )
{
  /* Insert implementation specific code here.  */
  ETimer_t * t = timer_start( ee_microseconds/USEC_CONVERT, ee_event_inst );
  t->recurrence = ee_microseconds/USEC_CONVERT;
  return (Escher_Timer_t *) t;
}

/*=====================================================================
 * BridgePoint Primitive:
 * <integer_var> = TIM::timer_remaining_time(
 *   timer_inst_ref:<timer_inst_ref_var> )
 * Return the remaining time of the specified timer.
 *===================================================================*/
Escher_uSec_t
TIM_timer_remaining_time(
  const Escher_Timer_t * const ee_timer_inst_ref )
{
  /* Insert implementation specific code here.  */
  Escher_uSec_t t = 0UL;
  if ( ee_timer_inst_ref != 0 ) {
    t = ETimer_msec_time();
    t = ( ((ETimer_t *) ee_timer_inst_ref)->expiration > t ) ?
      USEC_CONVERT * ( ((ETimer_t *) ee_timer_inst_ref)->expiration - t ) :
      0UL;
  }
  return ( t );
}

/*=====================================================================
 * BridgePoint Primitive:
 * <was_running_flag> = TIM::timer_reset_time(
 *   microseconds:<integer_var>,
 *   timer_inst_ref:<timer_inst_ref_var> )
 * Try to change expiration of an existing timer.
 * If successful, return true.
 *===================================================================*/
bool
TIM_timer_reset_time(
  const Escher_uSec_t ee_microseconds,
  Escher_Timer_t * const ee_timer_inst_ref )
{
  /* Insert implementation specific code here.  */
  ETimer_t * t = (ETimer_t *) ee_timer_inst_ref;
  bool rc = false;
  if ( ( t != 0 ) && ( t->expiration > 0UL ) ) {
    t->expiration = ETimer_msec_time() + ee_microseconds/USEC_CONVERT + 1UL;
    rc = true;
  }
  return ( rc );
}

/*=====================================================================
 * BridgePoint Primitive:
 * <was_running_flag> = TIM::timer_add_time(
 *   microseconds:<integer_var>,
 *   timer_inst_ref:<timer_inst_ref_var> )
 * Try to add time to an existing timer.
 * If successful, return true.
 *===================================================================*/
bool
TIM_timer_add_time(
  const Escher_uSec_t ee_microseconds,
  Escher_Timer_t * const ee_timer_inst_ref )
{
  /* Insert implementation specific code here.  */
  ETimer_t * t = (ETimer_t *) ee_timer_inst_ref;
  bool rc = false;
  if ( ( t != 0 ) && ( t->expiration > 0UL ) ) {
    t->expiration += ee_microseconds/USEC_CONVERT;
    rc = true;
  }
  return ( rc );
}

/*=====================================================================
 * BridgePoint Primitive:
 * <was_running_flag> = TIM::timer_cancel(
 *   timer_inst_ref:<timer_inst_ref_var> )
 * This attempts to cancel the specified timer.
 * Return true if we actually cancelled the timer.
 *===================================================================*/
bool
TIM_timer_cancel(
  Escher_Timer_t * const ee_timer_inst_ref )
{
  /* Insert implementation specific code here.  */
  return timer_cancel( (ETimer_t * const) ee_timer_inst_ref );
}
#endif   /* if ESCHER_SYS_MAX_XTUML_TIMERS > 0 */

/*=====================================================================
 * BridgePoint Primitive:
 * <date_var> = TIM::current_date()
 * Return a variable representing the current calendar date.
 *===================================================================*/
Escher_Date_t
TIM_current_date( void )
{
  /* Insert implementation specific code here.  */
  return ( (Escher_Date_t) time( 0 ) );
}

/*=====================================================================
 * BridgePoint Primitive:
 * <date_var> = TIM::create_date(
 *   day:<integer_var>,
 *   hour:<integer_var>,
 *   minute:<integer_var>,
 *   month:<integer_var>,
 *   second:<integer_var>,
 *   year:<integer_var> )
 * Return a variable representing the calendar date as specified
 * by the input components.
 *===================================================================*/
Escher_Date_t
TIM_create_date(
  const i_t ee_day,
  const i_t ee_hour,
  const i_t ee_minute,
  const i_t ee_month,
  const i_t ee_second,
  const i_t ee_year )
{
  /* Insert implementation specific code here.  */
  Escher_Date_t r = 0;
  struct tm t;
  t.tm_isdst = -1;
  t.tm_mday = ee_day;
  t.tm_hour = ee_hour;
  t.tm_min = ee_minute;
  t.tm_mon = ee_month;
  t.tm_sec = ee_second;
  t.tm_year = ee_year - 1900;      /* not enough space for 100 years */
  r = (Escher_Date_t) mktime( &t );
  return ( r );
}

/*=====================================================================
 * BridgePoint Primitive:
 * <integer_var> = TIM::get_second(
 *   date:<integer_var> )
 * Return the second field of the date variable.
 *===================================================================*/
i_t
TIM_get_second(
  const Escher_Date_t ee_date
)
{
  /* Insert implementation specific code here.  */
  struct tm * tp;
  tp = localtime( &ee_date );
  return ( tp ) ? tp->tm_sec : 0;
}

/*=====================================================================
 * BridgePoint Primitive:
 * <integer_var> = TIM::get_minute(
 *   date:<integer_var> )
 * Return the minute field of the date variable.
 *===================================================================*/
i_t
TIM_get_minute(
  const Escher_Date_t ee_date
)
{
  /* Insert implementation specific code here.  */
  struct tm * tp;
  tp = localtime( &ee_date );
  return ( tp ) ? tp->tm_min : 0;
}

/*=====================================================================
 * BridgePoint Primitive:
 * <integer_var> = TIM::get_hour(
 *   date:<integer_var> )
 * Return the hour field of the date variable.
 *===================================================================*/
i_t
TIM_get_hour(
  const Escher_Date_t ee_date
)
{
  /* Insert implementation specific code here.  */
  struct tm * tp;
  tp = localtime( &ee_date );
  return ( tp ) ? tp->tm_hour : 0;
}

/*=====================================================================
 * BridgePoint Primitive:
 * <integer_var> = TIM::get_day(
 *   date:<integer_var> )
 * Return the day field of the date variable.
 *===================================================================*/
i_t
TIM_get_day(
  const Escher_Date_t ee_date
)
{
  /* Insert implementation specific code here.  */
  struct tm * tp;
  tp = localtime( &ee_date );
  return ( tp ) ? tp->tm_mday : 0;
}

/*=====================================================================
 * BridgePoint Primitive:
 * <integer_var> = TIM::get_month(
 *   date:<integer_var> )
 * Return the month field of the date variable.
 *===================================================================*/
i_t
TIM_get_month(
  const Escher_Date_t ee_date
)
{
  /* Insert implementation specific code here.  */
  struct tm * tp;
  tp = localtime( &ee_date );
  return ( tp ) ? tp->tm_mon : 0;
}

/*=====================================================================
 * BridgePoint Primitive:
 * <integer_var> = TIM::get_year(
 *   date:<integer_var> )
 * Return the year field of the date variable.
 *===================================================================*/
i_t
TIM_get_year(
  const Escher_Date_t ee_date
)
{
  /* Insert implementation specific code here.  */
  struct tm * tp;
  tp = localtime( &ee_date );
  return ( tp ) ? tp->tm_year + 1900 : 0;
}

/*=====================================================================
 * BridgePoint Primitive:
 * <timestamp_var> = TIM::current_clock()
 * This bridge returns a system dependent time value.
 *===================================================================*/
Escher_TimeStamp_t
TIM_current_clock( void )
{
  /* Insert implementation specific code here.  */
  return ( ETimer_msec_time() );
}

/* Routines below are implementation specific.  Modify to taste.     */

#if ESCHER_SYS_MAX_XTUML_TIMERS > 0

/*---------------------------------------------------------------------
 * Get a timer instance from the inanimate list, provide the
 * expiration time and insert it into its proper location among
 * the currently ticking timers.
 *-------------------------------------------------------------------*/
static ETimer_t *
timer_start(
  const ETimer_time_t duration,
  Escher_xtUMLEvent_t * const event
)
{
  ETimer_t * t;
  t = inanimate;
  if ( t != 0 ) {
    inanimate = inanimate->next;
    t->event = event;
    /*---------------------------------------------------------------*/
    /* Calculate the timer expiration time.                          */
    /* Note:  Add one to the duration to make sure that delay is     */
    /* at least as long as duration.                                 */
    /*---------------------------------------------------------------*/
    t->expiration = ETimer_msec_time() + duration + 1UL;
    timer_insert_sorted( t );
  }
  return ( t );
}

/*---------------------------------------------------------------------
 * Insert a timer into the list of ticking timers maintaining
 * an order that fires timers chronologically.
 *-------------------------------------------------------------------*/
static void
timer_insert_sorted(
  ETimer_t * t
)
{
  if ( animate == 0 ) {                              /* empty list   */
    t->next = 0;
    animate = t;
  } else {
    ETimer_time_t poptime = t->expiration;
    if ( poptime <= animate->expiration ) {          /* before head  */
      t->next = animate;
      animate = t;
    } else {                                         /* find bigger  */
      ETimer_t * prev = animate;
      ETimer_t * cursor;
      while ( ( cursor = prev->next ) != 0 ) {
        if ( poptime <= cursor->expiration ) {
          break;
        }
        prev = cursor;
      }
      prev->next = t;                                /* link in      */
      t->next = cursor;
    }
  }
}

/*---------------------------------------------------------------------
 * Try to find a ticking timer and move to the non-ticking list.
 *-------------------------------------------------------------------*/
static bool
timer_find_and_delete( ETimer_t * const t )
{
  bool rc = false;
  if ( ( t != 0 ) && ( animate != 0 ) ) {
    /*---------------------------------------------------------------*/
    /* Check to see if the timer has already been reset.  This       */
    /* check is probabilistic; it could have a hole if multitasked.  */
    /* We need to try to unlink and see if we actually unlinked.     */
    /* Attempt to remove the timer from the list of running timers.  */
    /* If we succeed, then we can cancel/delete the timer.  If the   */
    /* timer is not in the list, then there is no point in           */
    /* attempting to do any more.                                    */
    /*---------------------------------------------------------------*/
    if ( t == animate ) {
      animate = animate->next;
    } else {
      ETimer_t * prev = animate;
      ETimer_t * cursor;
      while ( ( cursor = prev->next ) != t ) {           /* find */
        if ( cursor == 0 ) {
          return ( false );
        }
        prev = cursor;
      }
      prev->next = t->next;                             /* unlink */
    }
    t->expiration = 0; /* in case anyone tries to read the handle */
    t->next = inanimate;
    inanimate = t;
    rc = true;
  }
  return rc;
}

/*---------------------------------------------------------------------
 * Cancel the given timer if possible.
 *-------------------------------------------------------------------*/
static bool
timer_cancel(
  ETimer_t * const t
)
{
  bool rc; Escher_xtUMLEvent_t * e;
  rc = timer_find_and_delete( t );
  e = t->event;
  if ( true == rc ) {
    if ( 0 != e ) {
      Escher_DeletextUMLEvent( e );
    }
  }
  return ( rc );
}

/*---------------------------------------------------------------------
 * Generate delayed event to the application.
 * Deactivate fired timer.
 *-------------------------------------------------------------------*/
static void
timer_fire(
  ETimer_t * const t
)
{
  t->expiration = ( t->recurrence == 0 ) ? 0 : t->expiration + t->recurrence;
  Escher_SendEvent( t->event );
  if ( 0 != t->recurrence ) {
    Escher_xtUMLEvent_t * e = Escher_AllocatextUMLEvent();
    Escher_memmove( e, t->event, sizeof( Escher_xtUMLEvent_t ) );
    t->event = e;
    animate = animate->next;      /* Remove from front of list.    */
    timer_insert_sorted( t );
  } else {
  animate = animate->next;        /* Remove from active list.      */
  t->next = inanimate;            /* Connect to inactive list.     */
  inanimate = t;
  }
}
#endif   /* if ESCHER_SYS_MAX_XTUML_TIMERS > 0 */

/*---------------------------------------------------------------------
 * This is the low level mechanism for monotonically increasing
 * at a constant rate.  Substitute code here to read some
 * sort of hardware timer.
 *-------------------------------------------------------------------*/
static ETimer_time_t
ETimer_msec_time( void )
{
  ETimer_time_t t;
  ftime( &systyme );
  t = ( systyme.time * USEC_CONVERT ) + systyme.millitm;
  return ( t - tinit );

}

/*---------------------------------------------------------------------
 * Initialize the tick mechanism and the timer instances.
 *-------------------------------------------------------------------*/
void
TIM_init( void )
{
#if ESCHER_SYS_MAX_XTUML_TIMERS > 0
  u2_t i;
  /*-----------------------------------------------------------------*/
  /* Build the collection (linked list) of timers.                   */
  /*-----------------------------------------------------------------*/
  animate = 0; inanimate = 0;
  for ( i = 0; i < ESCHER_SYS_MAX_XTUML_TIMERS; i++ ) {
    swtimers[ i ].expiration = 0;
    swtimers[ i ].recurrence = 0;
    swtimers[ i ].event = 0;
    swtimers[ i ].next = inanimate;
    inanimate = &swtimers[ i ];
  }
#endif   /* if ESCHER_SYS_MAX_XTUML_TIMERS > 0 */
  ftime( &systyme );            /* Initialize the hardware ticker.   */
  tinit = ( systyme.time * USEC_CONVERT ) + systyme.millitm;
}

/*---------------------------------------------------------------------
 * This is the repetitively invoked timer poller.
 * This routine needs to be run periodically.
 *-------------------------------------------------------------------*/
void
TIM_tick( void )
{
#if ESCHER_SYS_MAX_XTUML_TIMERS > 0
  /*-----------------------------------------------------------------*/
  /* Check to see if there are timers in the ticking timers list.    */
  /*-----------------------------------------------------------------*/
  if ( animate != 0 ) {
    if ( animate->expiration <= ETimer_msec_time() ) {
      timer_fire( animate );
    }
  }
#endif   /* if ESCHER_SYS_MAX_XTUML_TIMERS > 0 */
}

#ifdef USED_TO_ALLOW_PAUSING
/*---------------------------------------------------------------------
 * Pause the tick mechanism such that all timers simply freeze
 * and do not advance toward expiration.  This is used for debug.
 * Record the system time when pause begins.
 *-------------------------------------------------------------------*/
void
TIM_pause( void )
{
  #if ESCHER_SYS_MAX_XTUML_TIMERS > 0
  paused = true;
  start_of_pause = ETimer_msec_time();
  #endif   /* if ESCHER_SYS_MAX_XTUML_TIMERS > 0 */
}

/*---------------------------------------------------------------------
 * Resume the tick mechanism.  Update the expiration time for all
 * ticking timers.
 *-------------------------------------------------------------------*/
void
TIM_resume( void )
{
  #if ESCHER_SYS_MAX_XTUML_TIMERS > 0
  ETimer_t * cursor = animate;
  ETimer_time_t t;      /* difference between now and start of pause */
  t = ETimer_msec_time() - start_of_pause;
  while ( cursor != 0 ) {
    cursor->expiration += t;
    cursor = cursor->next;
  }
  paused = false;
  #endif   /* if ESCHER_SYS_MAX_XTUML_TIMERS > 0 */
}
#endif


text:
import React from 'react'
import PropTypes from 'prop-types'
import {blueA400, grey200, grey600, grey700, redA700} from 'material-ui/styles/colors'
import { connect } from 'react-redux'
import { requestKinds } from '../state/actions/apimodels'
import { routerActions } from 'react-router-redux'
import {Card, CardHeader, CardText} from 'material-ui/Card'
import FilterChip from './FilterChip'
import { withRouter } from 'react-router-dom'
import KindAbbreviation from './KindAbbreviation'
import Chip from 'material-ui/Chip'

const mapStateToProps = function(store) {
  return {
    kinds: store.apimodels.kinds,
  }
}

const mapDispatchToProps = function(dispatch, ownProps) {
  return {
    createResource: function(namespace, kind, name) {
      dispatch(routerActions.push(`/workloads/new?kind=${kind}&namespace=${namespace}&name=${name}`))
    },
    requestKinds: function() {
      dispatch(requestKinds())
    },
  }
}

export default withRouter(connect(mapStateToProps, mapDispatchToProps) (
class ResourceNotFoundPage extends React.Component {

  static propTypes = {
    kind: PropTypes.string.isRequired,
    name: PropTypes.string.isRequired,
    namespace: PropTypes.string.isRequired,
    resourceGroup: PropTypes.string.isRequired,
  }

  constructor(props) {
    super(props);
    if (!props.kinds) {
      props.requestKinds()
    } else {
      this.kubeKind = this.props.kinds[props.kind]
    }
  }

  componentWillReceiveProps = (props) => {
    if (!this.kubeKind && props.kinds) {
      this.kubeKind = props.kinds[props.kind]
    }
  }

  render() {

    let { kind, namespace, name } = this.props

    if (!this.kubeKind) {
      return null
    }

    return (

        <Card className="resource-info" style={{margin: 5}} >
          <CardHeader
            title={
{name}<Chip backgroundColor={redA700} labelColor={grey200} style={{display: 'inline-block', margin: '4px 4px 4px 20px'}}>
              does not exist
            </Chip>
}
            subtitle={

                  <FilterChip prefixStyle={{fontStyle: 'italic', color: grey700}} prefix={'namespace'} suffix={namespace} />
                  <FilterChip prefixStyle={{fontStyle: 'italic', color: grey700}} prefix={'kind'} suffix={kind} />

            }
            avatar={<KindAbbreviation text={this.kubeKind.abbrev} color={this.kubeKind.color}/>}
            titleStyle={{fontSize: '24px', fontWeight: 600, paddingLeft: 10}}
          >
          </CardHeader>
          <CardText style={{
              borderTop: `4px solid ${blueA400}`,
              height: `${window.innerHeight - 275}px`,
              backgroundColor: grey700,
              color: grey600,
              fontWeight: 600,
              textShadow: `rgb(158, 158, 158) -1px -1px 0px, rgb(158, 158, 158) 1px -1px 0px, rgb(158, 158, 158) -1px 1px 0px, rgb(158, 158, 158) 1px 1px 0px`,
              fontSize: '30vw',
              lineHeight: `${window.innerHeight - 260}px`,
              textAlign: 'center',
              marginBottom: -8,
            }}>404'd!!
          </CardText>
        </Card>

    )
  }
}))