text:
package org.apache.flink.connector.kafka.source.enumerator.initializer;

import org.apache.flink.annotation.PublicEvolving;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.split.KafkaPartitionSplit;

import org.apache.kafka.clients.admin.KafkaAdminClient;
import org.apache.kafka.clients.admin.ListConsumerGroupOffsetsOptions;
import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
import org.apache.kafka.clients.consumer.OffsetResetStrategy;
import org.apache.kafka.common.TopicPartition;

import java.io.Serializable;
import java.util.Collection;
import java.util.Map;

/**
 * An interface for users to specify the starting / stopping offset of a {@link
 * KafkaPartitionSplit}.
 *
 * @see ReaderHandledOffsetsInitializer
 * @see SpecifiedOffsetsInitializer
 * @see TimestampOffsetsInitializer
 */
@PublicEvolving
public interface OffsetsInitializer extends Serializable {

    /**
     * Get the initial offsets for the given Kafka partitions. These offsets will be used as either
     * starting offsets or stopping offsets of the Kafka partitions.
     *
     *
If the implementation returns a starting offset which causes {@code
     * OffsetsOutOfRangeException} from Kafka. The {@link OffsetResetStrategy} provided by the
     * {@link #getAutoOffsetResetStrategy()} will be used to reset the offset.
     *
     * @param partitions the Kafka partitions to get the starting offsets.
     * @param partitionOffsetsRetriever a helper to retrieve information of the Kafka partitions.
     * @return A mapping from Kafka partition to their offsets to start consuming from.
     */
    Map<TopicPartition, Long> getPartitionOffsets(
            Collection<TopicPartition> partitions,
            PartitionOffsetsRetriever partitionOffsetsRetriever);

    /**
     * Get the auto offset reset strategy in case the initialized offsets falls out of the range.
     *
     *
The OffsetStrategy is only used when the offset initializer is used to initialize the
     * starting offsets and the starting offsets is out of range.
     *
     * @return An {@link OffsetResetStrategy} to use if the initialized offsets are out of the
     *     range.
     */
    OffsetResetStrategy getAutoOffsetResetStrategy();

    /**
     * An interface that provides necessary information to the {@link OffsetsInitializer} to get the
     * initial offsets of the Kafka partitions.
     */
    interface PartitionOffsetsRetriever {

        /**
         * The group id should be the set for {@link KafkaSource KafkaSource} before invoking this
         * method. Otherwise an {@code IllegalStateException} will be thrown.
         *
         * @see KafkaAdminClient#listConsumerGroupOffsets(String, ListConsumerGroupOffsetsOptions)
         * @throws IllegalStateException if the group id is not set for the {@code KafkaSource}.
         */
        Map<TopicPartition, Long> committedOffsets(Collection<TopicPartition> partitions);

        /** List end offsets for the specified partitions. */
        Map<TopicPartition, Long> endOffsets(Collection<TopicPartition> partitions);

        /** List beginning offsets for the specified partitions. */
        Map<TopicPartition, Long> beginningOffsets(Collection<TopicPartition> partitions);

        /** List offsets matching a timestamp for the specified partitions. */
        Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes(
                Map<TopicPartition, Long> timestampsToSearch);
    }

    // --------------- factory methods ---------------

    /**
     * Get an {@link OffsetsInitializer} which initializes the offsets to the committed offsets. An
     * exception will be thrown at runtime if there is no committed offsets.
     *
     * @return an offset initializer which initialize the offsets to the committed offsets.
     */
    static OffsetsInitializer committedOffsets() {
        return committedOffsets(OffsetResetStrategy.NONE);
    }

    /**
     * Get an {@link OffsetsInitializer} which initializes the offsets to the committed offsets. Use
     * the given {@link OffsetResetStrategy} to initialize the offsets if the committed offsets does
     * not exist.
     *
     * @param offsetResetStrategy the offset reset strategy to use when the committed offsets do not
     *     exist.
     * @return an {@link OffsetsInitializer} which initializes the offsets to the committed offsets.
     */
    static OffsetsInitializer committedOffsets(OffsetResetStrategy offsetResetStrategy) {
        return new ReaderHandledOffsetsInitializer(
                KafkaPartitionSplit.COMMITTED_OFFSET, offsetResetStrategy);
    }

    /**
     * Get an {@link OffsetsInitializer} which initializes the offsets in each partition so that the
     * initialized offset is the offset of the first record whose record timestamp is greater than
     * or equals the give timestamp.
     *
     * @param timestamp the timestamp to start the consumption.
     * @return an {@link OffsetsInitializer} which initializes the offsets based on the given
     *     timestamp.
     * @see KafkaAdminClient#listOffsets(Map)
     */
    static OffsetsInitializer timestamp(long timestamp) {
        return new TimestampOffsetsInitializer(timestamp);
    }

    /**
     * Get an {@link OffsetsInitializer} which initializes the offsets to the earliest available
     * offsets of each partition.
     *
     * @return an {@link OffsetsInitializer} which initializes the offsets to the earliest available
     *     offsets.
     */
    static OffsetsInitializer earliest() {
        return new ReaderHandledOffsetsInitializer(
                KafkaPartitionSplit.EARLIEST_OFFSET, OffsetResetStrategy.EARLIEST);
    }

    /**
     * Get an {@link OffsetsInitializer} which initializes the offsets to the latest offsets of each
     * partition.
     *
     * @return an {@link OffsetsInitializer} which initializes the offsets to the latest offsets.
     */
    static OffsetsInitializer latest() {
        return new ReaderHandledOffsetsInitializer(
                KafkaPartitionSplit.LATEST_OFFSET, OffsetResetStrategy.LATEST);
    }

    /**
     * Get an {@link OffsetsInitializer} which initializes the offsets to the specified offsets.
     *
     * @param offsets the specified offsets for each partition.
     * @return an {@link OffsetsInitializer} which initializes the offsets to the specified offsets.
     */
    static OffsetsInitializer offsets(Map<TopicPartition, Long> offsets) {
        return new SpecifiedOffsetsInitializer(offsets, OffsetResetStrategy.EARLIEST);
    }

    /**
     * Get an {@link OffsetsInitializer} which initializes the offsets to the specified offsets. Use
     * the given {@link OffsetResetStrategy} to initialize the offsets in case the specified offset
     * is out of range.
     *
     * @param offsets the specified offsets for each partition.
     * @param offsetResetStrategy the {@link OffsetResetStrategy} to use when the specified offset
     *     is out of range.
     * @return an {@link OffsetsInitializer} which initializes the offsets to the specified offsets.
     */
    static OffsetsInitializer offsets(
            Map<TopicPartition, Long> offsets, OffsetResetStrategy offsetResetStrategy) {
        return new SpecifiedOffsetsInitializer(offsets, offsetResetStrategy);
    }
}


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/diag/prdf/common/prdfMain_common.C $                  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2013,2020                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

/**
 * @file  prdfMain_common.C
 * @brief PRD code used by external components.
 *
 * This file contains code that is strictly common between FSP and Hostboot. All
 * platform specific code should be in the respective FSP only or Hostboot only
 * files.
 */

#include <prdfMain.H>

#include <CcAutoDeletePointer.h>
#include <prdfErrlUtil.H>
#include <iipResolutionFactory.h>
#include <iipSystem.h>
#include <prdrLoadChipCache.H>  // To flush chip-file cache.
#include <prdfPlatServices.H>
#include <prdfRasServices.H>
#include <prdfRegisterCache.H>
#include <prdfScanFacility.H>
#include <prdfMfgThresholdMgr.H>

#ifdef __HOSTBOOT_RUNTIME
#include <prdfOcmbChipDomain.H>
#endif

#if !defined(__HOSTBOOT_MODULE) && !defined(__HOSTBOOT_RUNTIME)
#include <prdfSdcFileControl.H>
#endif

#include <prdfPlatConfigurator.H>

using namespace TARGETING;

namespace PRDF
{

using namespace PlatServices;

//------------------------------------------------------------------------------
// Forward references
//------------------------------------------------------------------------------

extern void initPlatSpecific();

//------------------------------------------------------------------------------
// Global Variables
//------------------------------------------------------------------------------

System * systemPtr = nullptr;
ErrlSmartPtr g_prd_errlHndl; // inited to nullptr in ctor.
bool g_initialized = false;

//------------------------------------------------------------------------------
// Function definitions
//------------------------------------------------------------------------------

void uninitialize()
{
    PRDF_ENTER( "PRDF::uninitialize()" );

    delete systemPtr;
    systemPtr = nullptr;
    g_initialized = false;

    ScanFacility::Access().reset();

    // Some Resolutions carry state and must be re-created - this call resets
    // what it needs to.
    ResolutionFactory::Access().Reset();

    // clear the MfgThresholdMgr
    MfgThresholdMgr::getInstance()->reset();

    PRDF_EXIT( "PRDF::uninitialize()" );
}

//------------------------------------------------------------------------------

errlHndl_t noLock_initialize()
{
    #define PRDF_FUNC "PRDF::noLock_initialize() "

    PRDF_ENTER( PRDF_FUNC );

    g_prd_errlHndl = nullptr; // This forces any previous errls to be committed

    // Synchronize SCOM access to hardware
    // Start un-synchronized so hardware is accessed
    RegDataCache::getCachedRegisters().flush();

    if(g_initialized == true && systemPtr != nullptr)
    {
        // This means we are being re-initialized (and we were in a good state)
        // so Clean up in preparation for re-build
        PRDF::uninitialize();
    }

    if(g_initialized == false)
    {
        // Initialize the Service Generator
        ServiceGeneratorClass & serviceGenerator =
                    ServiceGeneratorClass::ThisServiceGenerator();
        serviceGenerator.Initialize();

        // Perform platform specific initialization.
        initPlatSpecific();

        CcAutoDeletePointer<Configurator> configuratorPtr
                                          ( new PRDF::PlatConfigurator() );

        errlHndl_t l_errBuild = configuratorPtr->build();//build object model
        if( nullptr != l_errBuild )
        {
            //there is some problem in building RuleMetaData object
            g_prd_errlHndl = l_errBuild;

            //object model is either not build or at best incomplete.We must
            // clean this up .The easiest way is to delete the system which in
            //in turn shall clean up the constituents.
            delete systemPtr;
            systemPtr = nullptr;
            g_initialized = false;
            PRDF_ERR(PRDF_FUNC "failed to buid object model");
        }
        //systemPtr is populated in configurator
        else if( systemPtr != nullptr )
        {
            systemPtr->Initialize(); // Hardware initialization
            g_initialized = true;
        }

        // Flush rule table cache since objects are all built.
        Prdr::LoadChipCache::flushCache();
    }

    #ifdef __HOSTBOOT_RUNTIME

    // Handle R/R scenario.
    TARGETING::MODEL procModel = getChipModel( getMasterProc() );
    if ( MODEL_POWER10 == procModel )
    {
        ((OcmbChipDomain *)systemPtr->GetDomain(OCMB_DOMAIN))->handleRrFo();
    }
    else
    {
        PRDF_ERR( PRDF_FUNC "Master PROC model %d not supported", procModel );
        PRDF_ASSERT(false);
    }

    #endif

    PRDF_EXIT( PRDF_FUNC );

    return (g_prd_errlHndl.release());

    #undef PRDF_FUNC
}

errlHndl_t initialize()
{
    PRDF_ENTER( "PRDF::initialize()" );

    errlHndl_t err = nullptr;

    // will unlock when going out of scope
    PRDF_SYSTEM_SCOPELOCK;

    err = noLock_initialize();

    PRDF_EXIT( "PRDF::initialize()" );

    return err;

}

//------------------------------------------------------------------------------

errlHndl_t main( ATTENTION_VALUE_TYPE i_priAttnType,
                 const AttnList & i_attnList )
{
    PRDF_ENTER( "PRDF::main() Global attnType=%04X", i_priAttnType );

    // These have to be outside of system scope lock
    errlHndl_t retErrl = nullptr;

    { // system scope lock starts ------------------------------------------

    // will unlock when going out of scope
    PRDF_SYSTEM_SCOPELOCK;

    g_prd_errlHndl = nullptr;

    uint32_t rc =  SUCCESS;
    // clears all the chips saved to stack during last analysis
    ServiceDataCollector::clearChipStack();

    if(( g_initialized == false)&&(nullptr ==systemPtr))
    {
        g_prd_errlHndl = noLock_initialize();
        if(g_prd_errlHndl != nullptr) rc = PRD_NOT_INITIALIZED;
    }

    ServiceDataCollector serviceData;
    STEP_CODE_DATA_STRUCT sdc;
    sdc.service_data = &serviceData;
    SYSTEM_DEBUG_CLASS sysdebug;

    sysdebug.Reinitialize(i_attnList); //Refresh sysdebug with latest Attn data

    ////////////////////////////////////////////////////////////////////////////
    // Normalize global attn type (ie 11,12,13,....) to (CHECKSTOP, RECOVERED,
    // SPECIAL..)
    ////////////////////////////////////////////////////////////////////////////

    if ( i_priAttnType == INVALID_ATTENTION_TYPE ||
         i_priAttnType >= END_ATTENTION_TYPE )
    {
        rc = PRD_INVALID_ATTENTION_TYPE;
        PRDF_ERR( "PrdMain: Invalid attention type! Global:%x",
                  i_priAttnType );
        i_priAttnType = RECOVERABLE; // This will prevent RAS service problems
    }

    // link to the right service Generator
    ServiceGeneratorClass & serviceGenerator =
        ServiceGeneratorClass::ThisServiceGenerator();

    // Initialize the SDC error log. Required for GenerateSrcPfa() call below.
    serviceGenerator.createInitialErrl( i_priAttnType );

    // check for something wrong
    if ( g_initialized == false || rc != SUCCESS || systemPtr == nullptr )
    {
        if(rc == SUCCESS)
        {
            rc = PRD_NOT_INITIALIZED;
        }
        PRDF_ERR("PrdMain: PRD failed. RC=%x",rc );
        // we are not going to do an analysis - so fill out the Service Data
        (serviceData.GetErrorSignature())->setSigId(rc);
        serviceData.SetCallout(SP_CODE);
        serviceData.SetCallout( LEVEL2_SUPPORT, MRU_LOW );
        serviceData.SetThresholdMaskId(0); // Sets AT_THRESHOLD, DEGRADED,
                                           // SERVICE_CALL
    }
    else  // do the analysis
    {
        // flush Cache so that SCR reads access hardware
        RegDataCache::getCachedRegisters().flush();

        // The primary attention type must be set before calling Analyze().
        serviceData.setPrimaryAttnType(i_priAttnType);

        // Set the time in which PRD handled the error.
        Timer timeOfError;
        PlatServices::getCurrentTime( timeOfError );
        serviceData.SetTOE( timeOfError );

        ServiceDataCollector l_tempSdc = serviceData;
        l_tempSdc.setPrimaryPass();
        sdc.service_data = &l_tempSdc;

        int32_t analyzeRc = systemPtr->Analyze( sdc );

        if( PRD_SCAN_COMM_REGISTER_ZERO == analyzeRc )
        {
            // So, the first pass has failed. Hence, there are no primary
            // bits set. We must start second pass to see if there are any
            //secondary bits set.
            sdc.service_data = &serviceData;

            #if !defined(__HOSTBOOT_MODULE) && !defined(__HOSTBOOT_RUNTIME)
            ForceSyncAnalysis( l_tempSdc ); // save SDC till end of primary pass
            #endif

            // starting the second pass
            PRDF_INF( "PRDF::main() No bits found set in first pass,"
                      " starting second pass" );
            sysdebug.initAttnPendingtatus( ); //for the second  pass

            if( l_tempSdc.isSecondaryErrFound() )
            {
                sdc.service_data->setSecondaryErrFlag();
            }

            analyzeRc = systemPtr->Analyze( sdc );

            // merging capture data of primary pass with capture data of
            // secondary pass for better FFDC.
            serviceData.GetCaptureData().mergeData(
                                    l_tempSdc.GetCaptureData());

            #if !defined(__HOSTBOOT_MODULE) && !defined(__HOSTBOOT_RUNTIME)
            // save SDC till end of secondary pass
            ForceSyncAnalysis( serviceData );
            #endif
        }
        else
        {
            serviceData = l_tempSdc;
            sdc.service_data = &serviceData;
        }

        // flush Cache to free up the memory
        RegDataCache::getCachedRegisters().flush();
        ScanFacility      & l_scanFac = ScanFacility::Access();
        //delete all the wrapper register objects since these were created
        //just for plugin code
        l_scanFac.ResetPluginRegister();
        if(analyzeRc != SUCCESS && g_prd_errlHndl == nullptr)
        {
            (serviceData.GetErrorSignature())->setErrCode(
                                                    (uint16_t)analyzeRc );
            serviceData.SetCallout( SP_CODE, MRU_MED, NO_GARD );
            serviceData.SetCallout( LEVEL2_SUPPORT, MRU_LOW, NO_GARD );
            serviceData.setServiceCall();
            // We don't want to gard for non-checkstops unless we have a good
            // return code
            if ( CHECK_STOP != serviceData.getPrimaryAttnType() )
            {
                serviceData.clearMruListGard();
            }
        }
    }

    if(g_prd_errlHndl != nullptr)
    {
        PRDF_INF("PRDTRACE: PrdMain: g_prd_errlHndl != nullptr");
        PRDF_ADD_PROCEDURE_CALLOUT( g_prd_errlHndl, MRU_MED, SP_CODE );
        // This is a precautionary step. There is a possibilty that if
        // severity for g_prd_errlHndl is Predictve and there is only
        // SP_CODE callout than it will be changed to tracing event.
        // So adding LEVEL2_SUPPORT to avoid this.
        PRDF_ADD_PROCEDURE_CALLOUT( g_prd_errlHndl, MRU_LOW, LEVEL2_SUPPORT );

        // This forces any previous errls to be committed
        g_prd_errlHndl = nullptr;

        // pw 597903 -- Don't GARD if we got a global error.
        serviceData.clearMruListGard();
    }

    g_prd_errlHndl = serviceGenerator.GenerateSrcPfa( i_priAttnType,
                                                      serviceData );

    // Sleep for 20msec to let attention lines settle if we are at threshold.
    if ( (g_prd_errlHndl == nullptr) && serviceData.IsAtThreshold() )
    {
        PlatServices::milliSleep( 0, 20 );
    }

    retErrl = g_prd_errlHndl.release();

    } // system scope lock ends ------------------------------------------

    PRDF_EXIT( "PRDF::main()" );

    return retErrl;
}

//------------------------------------------------------------------------------

errlHndl_t noLock_refresh()
{
    PRDF_ENTER("PRDF::noLock_refresh()");

    errlHndl_t l_errl = nullptr;

    if((false == g_initialized) || (nullptr == systemPtr))
    {
        l_errl = noLock_initialize();
    }
    else
    {
        // System was built so just check and
        // remove any non-functional chips
        systemPtr->RemoveNonFunctionalChips();
    }

    PRDF_EXIT("PRDF::noLock_refresh()");

    return l_errl;
}

errlHndl_t refresh()
{
    PRDF_ENTER("PRDF::refresh()");

    errlHndl_t l_errl = nullptr;

    // will unlock when going out of scope
    PRDF_SYSTEM_SCOPELOCK;

    l_errl = noLock_refresh();

    PRDF_EXIT("PRDF::refresh()");

    return l_errl;
}

//------------------------------------------------------------------------------

} // end namespace PRDF

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>SideCar: SideCar::Messages::TLoaderRegistry< T >::VersionedLoader Struct Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

SideCar

Main Page

Related Pages

Modules

Namespaces

Data Structures

Files

Data Structures

Class Hierarchy

Data Fields

SideCar

Messages

TLoaderRegistry

VersionedLoader

Public Member Functions

SideCar::Messages::TLoaderRegistry< T >::VersionedLoader Struct Reference

Type-specific definition of the LoaderRegistry::VersionedLoader class.
 More...

#include </Users/howes/src/sidecar/Messages/LoaderRegistry.h>

Inheritance diagram for SideCar::Messages::TLoaderRegistry< T >::VersionedLoader:

<map name="SideCar_1_1Messages_1_1TLoaderRegistry_3_01T_01_4_1_1VersionedLoader_inherit__map" id="SideCar_1_1Messages_1_1TLoaderRegistry_3_01T_01_4_1_1VersionedLoader_inherit__map">
<area shape="rect" id="node2" href="structSideCar_1_1Messages_1_1VoidLoaderRegistry_1_1VersionedVoidLoader.html" title="Pairing of specific version value with a class loader procedure. " alt="" coords="7,5,153,73"/>
</map>
[legend]

Public Member Functions

 	VersionedLoader (VersionType version, TLoader loader)

 Public Member Functions inherited from SideCar::Messages::VoidLoaderRegistry::VersionedVoidLoader

 	VersionedVoidLoader (VersionType version, VoidLoader loader)

bool 	operator< (const VersionedVoidLoader &rhs) const

Additional Inherited Members

 Data Fields inherited from SideCar::Messages::VoidLoaderRegistry::VersionedVoidLoader

VersionType 	version_

VoidLoader 	loader_

Detailed Description

template<typename T>

struct SideCar::Messages::TLoaderRegistry< T >::VersionedLoader

Type-specific definition of the LoaderRegistry::VersionedLoader class.

Definition at line 188 of file LoaderRegistry.h.

The documentation for this struct was generated from the following file:

/Users/howes/src/sidecar/Messages/LoaderRegistry.h

<address class="footer">
Generated by

 1.8.11
</address>


text:
using System.Collections.Generic;
using Azure.Core;
using Azure.ResourceManager.ServiceFabric;

namespace Azure.ResourceManager.ServiceFabric.Models
{
    /// <summary> The list of application type names. </summary>
    internal partial class ServiceFabricApplicationTypeList
    {
        /// <summary> Initializes a new instance of ServiceFabricApplicationTypeList. </summary>
        internal ServiceFabricApplicationTypeList()
        {
            Value = new ChangeTrackingList<ServiceFabricApplicationTypeData>();
        }

        /// <summary> Initializes a new instance of ServiceFabricApplicationTypeList. </summary>
        /// <param name="value"></param>
        /// <param name="nextLink"> URL to get the next set of application type list results if there are any. </param>
        internal ServiceFabricApplicationTypeList(IReadOnlyList<ServiceFabricApplicationTypeData> value, string nextLink)
        {
            Value = value;
            NextLink = nextLink;
        }

        /// <summary> Gets the value. </summary>
        public IReadOnlyList<ServiceFabricApplicationTypeData> Value { get; }
        /// <summary> URL to get the next set of application type list results if there are any. </summary>
        public string NextLink { get; }
    }
}


text:
package de.uni.freiburg.iig.telematik.sewol.context.constraint;

import java.awt.BorderLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import de.invation.code.toval.constraint.AbstractConstraint;
import de.invation.code.toval.constraint.graphic.ConstraintDialog;
import de.invation.code.toval.graphic.dialog.AbstractDialog;
import de.invation.code.toval.graphic.dialog.ExceptionDialog;
import de.invation.code.toval.graphic.dialog.ValueChooserDialog;
import de.invation.code.toval.graphic.renderer.AlternatingRowColorListCellRenderer;
import de.invation.code.toval.validate.CompatibilityException;
import de.invation.code.toval.validate.ParameterException;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.JSplitPane;

public class RoutingConstraintsDialog extends AbstractDialog<ConstraintContext> {

    private static final long serialVersionUID = 9017322681121907900L;

    private static final Dimension MINIMUM_SIZE_LEFT_PANEL = new Dimension(160, 360);
    private static final Dimension MINIMUM_SIZE_RIGHT_PANEL = new Dimension(240, 360);
    private static final Dimension PREFERRED_SIZE = new Dimension(450, 360);

    private JList listActivities = null;
    private JList listConstraints = null;

    private final DefaultListModel modelListActivities = new DefaultListModel();
    private final DefaultListModel modelListConstraints = new DefaultListModel();

    private JButton btnAddConstraint = null;
    private JButton btnEditConstraint = null;
    private JButton btnRemoveConstraint = null;

    private final List<AbstractConstraint<?>> constraints = new ArrayList<>();

    public RoutingConstraintsDialog(Window owner, ConstraintContext context) {
        super(owner, ButtonPanelLayout.CENTERED);
        setDialogObject(context);
        setIncludeCancelButton(false);
    }

    @Override
    protected void addComponents() {
        JPanel leftPanel = new JPanel(new BorderLayout());
        JLabel lblActivities = new JLabel("Activities:");
        leftPanel.add(lblActivities, BorderLayout.PAGE_START);
        JScrollPane activitiesScrollPane = new JScrollPane(getListActivities());
        activitiesScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
        activitiesScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        leftPanel.add(activitiesScrollPane, BorderLayout.CENTER);
        leftPanel.setMinimumSize(MINIMUM_SIZE_LEFT_PANEL);

        JPanel rightPanel = new JPanel(new BorderLayout());
        JLabel lblConstraints = new JLabel("Constraints:");
        rightPanel.add(lblConstraints, BorderLayout.PAGE_START);
        JScrollPane constraintsScrollPane = new JScrollPane(getListConstraints());
        constraintsScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
        constraintsScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        rightPanel.add(constraintsScrollPane, BorderLayout.CENTER);
        rightPanel.setMinimumSize(MINIMUM_SIZE_RIGHT_PANEL);
        JPanel buttons = new JPanel();
        BoxLayout layout = new BoxLayout(buttons, BoxLayout.LINE_AXIS);
        buttons.setLayout(layout);
        buttons.add(Box.createHorizontalGlue());
        buttons.add(getButtonAddConstraint());
        buttons.add(getButtonEditConstraint());
        buttons.add(getButtonRemoveConstraint());
        buttons.add(Box.createHorizontalGlue());
        rightPanel.add(buttons, BorderLayout.PAGE_END);
        updateListConstraints();

        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
        splitPane.setDividerLocation(0.6);
        splitPane.setBorder(BorderFactory.createEmptyBorder());

        mainPanel().setLayout(new BorderLayout());
        mainPanel().add(splitPane, BorderLayout.CENTER);
    }

    @Override
    public Dimension getPreferredSize(){
        return PREFERRED_SIZE;
    }

    private JButton getButtonRemoveConstraint(){
        if(btnRemoveConstraint == null){
            btnRemoveConstraint = new JButton("Remove");
            btnRemoveConstraint.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    String activity = listActivities.getSelectedValue().toString();
                    if (listConstraints.getSelectedValue() != null) {
                        try {
                            getDialogObject().removeRoutingConstraint(activity, constraints.get(listConstraints.getSelectedIndex()));
                        } catch (ParameterException e1) {
                            JOptionPane.showMessageDialog(RoutingConstraintsDialog.this, "Cannot remove constraint from context.", "Internal Error", JOptionPane.ERROR_MESSAGE);
                            return;
                        }
                        updateListConstraints();
                    }
                }
            });
        }
        return btnRemoveConstraint;
    }

    private JButton getButtonEditConstraint(){
        if(btnEditConstraint == null){
            btnEditConstraint = new JButton("Edit");
            btnEditConstraint.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (listConstraints.getSelectedValue() != null) {
                        try{
                        ConstraintDialog.showDialog(RoutingConstraintsDialog.this, constraints.get(listConstraints.getSelectedIndex()));
                        updateListConstraints();
                        } catch(Exception ex){
                            ExceptionDialog.showException(RoutingConstraintsDialog.this, "Internal Exception", ex, true);
                        }
                    }
                }
            });
        }
        return btnEditConstraint;
    }

    private JButton getButtonAddConstraint(){
        if(btnAddConstraint == null){
            btnAddConstraint = new JButton("Add");
            btnAddConstraint.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    String activity = listActivities.getSelectedValue().toString();
                    Set<String> activityAttributes = null;
                    try {
                        activityAttributes = getDialogObject().getDataUsageFor(activity).keySet();
                        if (activityAttributes.isEmpty()) {
                            JOptionPane.showMessageDialog(RoutingConstraintsDialog.this, "Cannot add constraints to activities without data usage.", "Missing data usage", JOptionPane.ERROR_MESSAGE);
                            return;
                        }
                    } catch (ParameterException ex) {
                        JOptionPane.showMessageDialog(RoutingConstraintsDialog.this, "Cannot extract data usage information for activity \"" + activity + "\".", "Internal Error", JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                    List<String> chosenAttributes = null;
                    try {
                        chosenAttributes = ValueChooserDialog.showDialog(RoutingConstraintsDialog.this, "Choose attribute for new constraint", activityAttributes);
                    } catch (Exception e2) {
                        JOptionPane.showMessageDialog(RoutingConstraintsDialog.this, "Cannot launch value chooser dialog dialog.
Reason: " + e2.getMessage() + "", "Internal Exception", JOptionPane.ERROR_MESSAGE);
                    }
                    if (chosenAttributes != null && !chosenAttributes.isEmpty()) {
                        AbstractConstraint<?> newConstraint = null;
                        try{
                            newConstraint = ConstraintDialog.showDialog(RoutingConstraintsDialog.this, chosenAttributes.get(0));
                        } catch(Exception ex){
                            ExceptionDialog.showException(RoutingConstraintsDialog.this, "Internal Exception", ex, true);
                            return;
                        }
                        if (newConstraint != null) {
                            try {
                                getDialogObject().addRoutingConstraint(activity, newConstraint);
                                updateListConstraints();
                            } catch (CompatibilityException e1) {
                                JOptionPane.showMessageDialog(RoutingConstraintsDialog.this, e1.getMessage(), "Incompatible routing constraint", JOptionPane.ERROR_MESSAGE);
                            } catch (ParameterException e1) {
                                JOptionPane.showMessageDialog(RoutingConstraintsDialog.this, e1.getMessage(), "Invalid Argument", JOptionPane.ERROR_MESSAGE);
                            }
                        }
                    }

                }
            });
        }
        return btnAddConstraint;
    }

    private JList getListActivities() {
        if (listActivities == null) {
            listActivities = new JList(modelListActivities);
            listActivities.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            listActivities.setCellRenderer(new AlternatingRowColorListCellRenderer());
            listActivities.setFixedCellHeight(20);
            listActivities.setVisibleRowCount(10);
            listActivities.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            listActivities.setBorder(null);

            for (String activity : getDialogObject().getActivities()) {
                modelListActivities.addElement(activity);
            }

            listActivities.setSelectedIndex(0);

            listActivities.addListSelectionListener(new ListSelectionListener() {
                @Override
                public void valueChanged(ListSelectionEvent e) {
                    if ((e.getValueIsAdjusting() == false) && (listActivities.getSelectedValue() != null)) {
                        updateListConstraints();
                    }
                }
            }
            );
        }
        return listActivities;
    }

    private JList getListConstraints() {
        if (listConstraints == null) {
            listConstraints = new JList(modelListConstraints);
            listConstraints.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            listConstraints.setCellRenderer(new AlternatingRowColorListCellRenderer());
            listConstraints.setFixedCellHeight(20);
            listConstraints.setVisibleRowCount(10);
            listConstraints.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            listConstraints.setBorder(null);
        }
        return listConstraints;
    }

    private void updateListConstraints() {
        constraints.clear();
        modelListConstraints.clear();
        String activity = listActivities.getSelectedValue().toString();

        if (activity != null) {
            if (getDialogObject().hasRoutingConstraints(activity)) {
                constraints.addAll(getDialogObject().getRoutingConstraints(activity));
            }
        }

        for (AbstractConstraint<?> constraint : constraints) {
            modelListConstraints.addElement(constraint.toString());
        }
        if (!modelListConstraints.isEmpty()) {
            listConstraints.setSelectedIndex(0);
        }
    }

    @Override
    protected void setTitle() {
       setTitle("Set Activity Data Usage");
    }

    public static boolean showDialog(Window owner, ConstraintContext context) throws Exception {
        RoutingConstraintsDialog dialog = new RoutingConstraintsDialog(owner, context);
        dialog.setUpGUI();
        return dialog.getDialogObject() != null;
    }

}


text:
module CC::Service::QualityHelper
  def improved?
    remediation_cost < previous_remediation_cost
  end

  def constant_name
    payload["constant_name"]
  end

  def quality_title
    if payload["rating"].present?
      "Refactor #{constant_name} from #{rating} on Code Climate"
    else
      "Refactor #{constant_name} on Code Climate"
    end
  end

  def rating
    with_article(payload["rating"])
  end

  def previous_rating
    with_article(payload["previous_rating"])
  end

  def remediation_cost
    payload.fetch("remediation_cost", 0)
  end

  def previous_remediation_cost
    payload.fetch("previous_remediation_cost", 0)
  end

  def with_article(letter, bold = false)
    letter ||= "?"

    text = bold ? "*#{letter}*" : letter
    if %w[A F].include?(letter.to_s)
      "an #{text}"
    else
      "a #{text}"
    end
  end

  def constant_basename(name)
    if name.include?(".")
      File.basename(name)
    else
      name
    end
  end
end


text:
package org.jboss.weld.ejb.spi;

import org.jboss.weld.bootstrap.api.Service;
import org.jboss.weld.ejb.api.SessionObjectReference;

/**
 * A container should implement this interface to allow Weld to resolve EJB and discover EJBs
 *
 * {@link EjbServices} is a per-BeanDeploymentArchive service.
 *
 * @author Pete Muir
 * @author Marius Bogoevici
 *
 */
public interface EjbServices extends Service {

    /**
     * Request a reference to an EJB session object from the container. If the EJB being resolved is a stateful session bean,
     * the container should ensure the session bean is created before this method returns.
     *
     * @param ejbDescriptor the ejb to resolve
     * @return a reference to the session object
     */
    SessionObjectReference resolveEjb(EjbDescriptor<?> ejbDescriptor);

    /**
     * Provides interceptor binding metadata to the container. This method should be called before any EJB object is created.
     *
     * @param ejbDescriptor the ejb to bound interceptors to
     * @param interceptorBindings the interceptor bindings descriptor
     */
    void registerInterceptors(EjbDescriptor<?> ejbDescriptor, InterceptorBindings interceptorBindings);

}


text:
package com.jetbrains.python.inspections;

import com.jetbrains.python.fixtures.PyTestCase;
import com.jetbrains.python.psi.LanguageLevel;
import org.jetbrains.annotations.NotNull;

/**
 * @author yole
 */
public class PyUnresolvedReferencesInspectionTest extends PyTestCase {
  private static final String TEST_DIRECTORY = "inspections/PyUnresolvedReferencesInspection/";

  public void testSelfReference() {
    doTest();
  }

  public void testUnresolvedImport() {
    doTest();
  }

  public void testStaticMethodParameter() {  // PY-663
    doTest();
  }

  public void testOverridesGetAttr() {  // PY-574
    doTest();
  }

  public void testUndeclaredAttrAssign() {  // PY-906
    doTest();
  }

  public void testSlots() {
    doTest();
  }

  public void testSlotsSubclass() {  // PY-5939
    doTest();
  }

  public void testImportExceptImportError() {
    doTest();
  }

  public void testMro() {  // PY-3989
    doTest();
  }

  public void testConditionalImports() { // PY-983
    doMultiFileTest("a.py");
  }

  public void testHasattrGuard() { // PY-2309
    doTest();
  }

  public void testOperators() {
    doTest();
  }

  // PY-2308
  public void testTypeAssertions() {
    doTest();
  }

  public void testUnresolvedImportedModule() {  // PY-2075
    doTest();
  }

  public void testSuperType() {  // PY-2320
    doTest();
  }

  public void testImportFunction() {  // PY-1896
    doTest();
  }

  public void testSuperclassAsLocal() {  // PY-5427
    doTest();
  }

  public void testImportToContainingFile() {  // PY-4372
    doMultiFileTest("p1/m1.py");
  }

  public void testFromImportToContainingFile() {  // PY-4371
    doMultiFileTest("p1/m1.py");
  }

  public void testFromImportToContainingFile2() {  // PY-5945
    doMultiFileTest("p1/m1.py");
  }

  public void testPropertyType() {  // PY-5915
    doTest();
  }

  // PY-6316
  public void testNestedComprehensions() {
    doTest();
  }

  public void testCompoundDunderAll() {  // PY-6370
    doTest();
  }

  public void testFromPackageImportBuiltin() {
    doMultiFileTest("a.py");
  }

  // PY-2813
  public void testNamespacePackageAttributes() {
    doMultiFileTest("a.py");
  }

  // PY-6548
  public void testDocstring() {
    doTest();
  }

  // PY-6634
  public void testModuleAttribute() {
    doTest();
  }

  // PY-4748
  public void testStubAssignment() {
    doMultiFileTest("a.py");
  }

  // PY-7022
  public void testReturnedQualifiedReferenceUnionType() {
    doMultiFileTest("a.py");
  }

  // PY-2668
  public void testUnusedImportsInPackage() {
    doMultiFileTest("p1/__init__.py");
  }

  // PY-7032
  public void testDocstringArgsAndKwargs() {
    doTest();
  }

  // PY-7136
  public void testUnusedImportWithClassAttributeReassignment() {
    doTest();
  }

  public void testGetattrAttribute() {
    doTest();
  }

  // PY-7173
  public void testDecoratedFunction() {
    doTest();
  }

  // PY-7173
  public void testDecoratedClass() {
    doTest();
  }

  // PY-7043
  public void testDunderPackage() {
    doTest();
  }

  // PY-7214
  public void testBuiltinDerivedClassAttribute() {
    doTest();
  }

  // PY-7244
  public void testAttributesOfGenerics() {
    doTest();
  }

  // PY-5995
  public void testClassInClassBody() {
    doTest();
  }

  // PY-7315
  public void testImportUsedInDocString() {
    doTest();
  }

  // PY-6745
  public void testQualNameAttribute() {
    runWithLanguageLevel(LanguageLevel.PYTHON33, new Runnable() {
      @Override
      public void run() {
        doTest();
      }
    });
  }

  // PY-7389
  public void testComprehensionScope27() {
    runWithLanguageLevel(LanguageLevel.PYTHON27, new Runnable() {
      @Override
      public void run() {
        doTest();
      }
    });
  }

  // PY-7389
  public void testComprehensionScope33() {
    runWithLanguageLevel(LanguageLevel.PYTHON33, new Runnable() {
      @Override
      public void run() {
        doTest();
      }
    });
  }

  // PY-7516
  public void testComprehensionInParameterValue() {
    doTest();
  }

  // PY-6617
  public void testAugAssignmentDefinedInOuterScope() {
    doTest();
  }

  // PY-7301
  public void testUnresolvedBaseClass() {
    doTest();
  }

  // PY-5427
  public void testBaseClassAssignment() {
    doTest();
  }

  // PY-4600
  public void testDynamicAttrsAnnotation() {
    doTest();
  }

  // PY-7708
  public void testXReadLinesForOpen() {
    doTest();
  }

  // PY-8063
  public void testAddForListComprehension() {
    doTest();
  }

  // PY-7805
  public void testUnderscoredBuiltin() {
    doTest();
  }

  // PY-9493
  public void testSuperObjectNew() {
    doTest();
  }

  // PY-7823
  public void testUnresolvedTopLevelInit() {
    doTest();
  }

  // PY-7694
  public void testNegativeAssertType() {
    doTest();
  }

  public void testNegativeIf() {
    doTest();
  }

  // PY-7614
  public void testNoseToolsDynamicMembers() {
    doMultiFileTest("a.py");
  }

  public void testDateTodayReturnType() {
    doMultiFileTest("a.py");
  }

  public void testObjectNewAttributes() {
    doTest();
  }

  // PY-10006
  public void testUnresolvedUnreachable() {
    doTest();
  }

  public void testNullReferenceInIncompleteImport() {
    doMultiFileTest("a.py");
  }

  // PY-10893
  public void testCustomNewReturnInAnotherModule() {
    doMultiFileTest("a.py");
  }

  public void testBytesIORead() {
    doTest();
  }

  private void doTest() {
    myFixture.configureByFile(TEST_DIRECTORY + getTestName(true) + ".py");
    myFixture.enableInspections(PyUnresolvedReferencesInspection.class);
    myFixture.checkHighlighting(true, false, false);
  }

  private void doMultiFileTest(@NotNull String filename) {
    final String testName = getTestName(false);
    myFixture.copyDirectoryToProject(TEST_DIRECTORY + testName, "");
    myFixture.configureFromTempProjectFile(filename);
    myFixture.enableInspections(PyUnresolvedReferencesInspection.class);
    myFixture.checkHighlighting(true, false, false);
  }
}


text:
* [wpmlcore-3738] Fixed issue where in some installations, the Language Switcher was missing from the secondary language menu
* [wpmlcore-3505] Add troubleshooting option `Recreate ST DB Cache tables` to re-run ST upgrade
* [wpmlcore-3494] Removed admin user language feature in sites running WordPress 4.7 or higher and included migration logic while upgrading WP. This is now integrated to WordPress itself.
* [wpmlcore-3399] Added a warning about missing menu items when only one language is configured in the site
* [wpmlcore-3372] Added more API hooks including `wpml_add_string_translation`
* [wpmlcore-3325] Changed the message style in Sync Field Functionality
* [wpmlcore-1448] Redesign of the language switcher (new admin UI, new API)

# Fixes
* [wpmlst-887] Fixed issue while dismissing admin notices from plugin that contains special chars in the title
* [wpmlcore-3682] Fix handling of slashes when copying custom fields
* [wpmlcore-3544] Automatically download WordPress mo files for active languages
* [wpmlcore-3497] Adjusted URL in wp_upload_dir return for when WPML is set up as domain
* [wpmlcore-3479] Fixed issue where language information wasn't saved when posts were created via AJAX call
* [wpmlcore-3471] Fixed compatibility issue when using Google PageSpeed Tools in Apache or Nginx
* [wpmlcore-3451] Prevent double ampersand encoding in language switcher URL
* [wpmlcore-3441] Fixed issue in the WPML notice when adding posts from frontend
* [wpmlcore-3438] Fixed issue with setting static blog page when page is permanently deleted
* [wpmlcore-3434] Fixed WPML_Backend_Request::get_ajax_request_lang
* [wpmlcore-3421] Fixed page template synchronization if template is set to default
* [wpmlcore-3420] Fixed \SitePress::_sync_custom_field to handle serialized data.
* [wpmlcore-3404] Fixed issue when duplicating posts that have comments to be duplicated
* [wpmlcore-3374] Removed the restriction of only English as default language when synchronizing WP menu
* [wpmlcore-3363] Fixed an issue with the browser redirection when using languages with regional variations (e.g. fr-CA).
* [wpmlcore-3361] Fixed a login redirection issue in sites with languages configured as domain
* [wpmlcore-3333] Fixed an issue that was happening when you try to scan strings before completing the wizard. Now it is not allowed
* [wpmlcore-3311] Fixed multisite install compatibility issue with WP 4.6+ using `sunrise`
* [wpmlcore-3266] On multisite, the main site settings are not altered anymore during sub-site setup
* [wpmlcore-3204] Fixed a compatibility issue with Yoast redirections
* [wpmlcore-3199] Removed Snoopy class and use WP_Http class instead.
* [wpmlcore-2968] Fixed a redirection issue Nginx servers with language configured as domain
* [wpmlcore-2884] In some cases (taxonomy, author, date and post type archives), the language switcher custom link for empty translation was not displayed
* [wpmlcore-2849] Fixed issue with cloning non object values for wp_query object.
* [wpmlcore-2692] Added caching for Twig templates.
* [wpmlcore-2565] Fixed a compatibility issue with `get_option('siteurl')` in sites with languages set as domain
* [wpmlcore-2535] Fixed a compatibility issue with `bloginfo('stylesheet_url')` when languages is set as domain
* [wpmlcore-2375] Fixed an URL inconsistency when using `get_page_link`
* [wpmlcore-2289] The language switcher in Twenty Sixteen's footer was cut off
* [wpmlcore-1869] The language switcher in Twenty Fifteen's footer was partially hidden by the sidebar


text:
     <%= DT.text('logs_label') %>

<a target="_blank" href="<%= containerLogsUrl %>" target="_blank"><%= DT.text('all_logs') %>

<a target="_blank" href="<%= containerLogsUrl %>/stdout/?start=-4096" target="_blank"><%= DT.text('stdout_log') %>

<a target="_blank" href="<%= containerLogsUrl %>/stderr/?start=-4096" target="_blank"><%= DT.text('stderr_log') %>

<a target="_blank" href="<%= containerLogsUrl %>/dt.log/?start=-4096" target="_blank"><%= DT.text('dt_log') %>

<a target="_blank" href="<%= containerLogsUrl %>/gc.log/?start=-4096" target="_blank"><%= DT.text('gc_log') %>


text:
var rotSpeed:float=3;
var rotRandomPlus:float=0.5;
var rotTreshold:float=50;

var changeRotMin:float=1;
var changeRotMax:float=2;

var minSpeed:float=0.5;
var maxSpeed:float=2;

var changeSpeedMin:float=0.5;
var changeSpeedMax:float=2;

private var speed:float=0;
private var timeGoesX:float=0;
private var timeGoesY:float=0;
private var timeGoesSpeed:float=0;

private var timeToChangeX:float=0.1;
private var timeToChangeY:float=0.1;
private var timeToChangeSpeed:float=0.1;

private var xDir:boolean=true;
private var yDir:boolean=true;

private var curRotSpeedX:float=0;
private var curRotSpeedY:float=0;

private var lendX:float=0;
private var lendY:float=0;

//********CUSTOM
function RandomizeSpeed ()
{
speed=Random.Range(minSpeed, maxSpeed);
}

function RandomizeXRot () {
var rnd=Random.value*rotRandomPlus;
curRotSpeedX=rotSpeed*rnd;
}

function RandomizeYRot () {
var rnd=Random.value*rotRandomPlus;
curRotSpeedY=rotSpeed*rnd;
}

//********START
function Start () {
RandomizeSpeed ();
if (Random.value>0.5) xDir=!xDir;
if (Random.value>0.5) yDir=!yDir;

timeToChangeY=Random.Range(changeRotMin, changeRotMax);
timeToChangeX=Random.Range(changeRotMin, changeRotMax);
timeToChangeSpeed=Random.Range(changeSpeedMin, changeSpeedMax);

curRotSpeedX=Random.Range((rotSpeed),(rotSpeed+rotRandomPlus));
curRotSpeedY=Random.Range((rotSpeed),(rotSpeed+rotRandomPlus));

}

//********UPDATE
function Update () {

if (xDir==true) lendX+=Time.deltaTime*curRotSpeedX;
if (xDir==false) lendX-=Time.deltaTime*curRotSpeedX;
if (yDir==true) lendY+=Time.deltaTime*curRotSpeedY;
if (yDir==false) lendY-=Time.deltaTime*curRotSpeedY;

if (lendX>rotTreshold)
{
lendX=rotTreshold;
xDir=!xDir;
}

if (lendX>rotTreshold)
{
lendX=-rotTreshold;
xDir=!xDir;
}
if (lendY>rotTreshold)
{
lendY=rotTreshold;
yDir=!yDir;
}

if (lendY>rotTreshold)
{
lendY=-rotTreshold;
yDir=!yDir;
}

transform.Rotate(lendX*Time.deltaTime, lendY*Time.deltaTime, 0);
transform.Translate(0, speed*Time.deltaTime, 0);

//**************
timeGoesX+=Time.deltaTime;
timeGoesY+=Time.deltaTime;
timeGoesSpeed+=Time.deltaTime;

if (timeGoesX>timeToChangeX)
{
xDir=!xDir;
timeGoesX-=timeGoesX;
timeToChangeX=Random.Range(changeRotMin, changeRotMax);
curRotSpeedX=Random.Range((rotSpeed),(rotSpeed+rotRandomPlus));
}

if (timeGoesY>timeToChangeY)
{
yDir=!yDir;
timeGoesY-=timeGoesY;
timeToChangeY=Random.Range(changeRotMin, changeRotMax);
curRotSpeedY=Random.Range((rotSpeed),(rotSpeed+rotRandomPlus));
}

if (timeGoesSpeed>timeToChangeSpeed)
{
RandomizeSpeed();
timeGoesSpeed-=timeGoesSpeed;
timeToChangeSpeed=Random.Range(changeSpeedMin, changeSpeedMax);
Debug.Log("hejj");
}

}


text:
"""""
This script was created to make a bash script for the
ZeaAllInfo.14col.allHybVeachPop.heirFstat file.
Created by Kathryn Kananen 6/4/15
"""""
import sys
from num2words import num2words

out = open(sys.argv[1], "w")

path = "~/Documents/Hufford_labs/David_data/chapter2/allPopFSTRun/part3FSTRun/"
pythonPath = path + "FSTpart2Run.R"
# dataPath = path + "ZeaAllInfo.14col.allHybVeachPop.heirFstat"

pastNum = []
# creates number range 106
for number in range(1,36):
	for nextNumber in range(1,36):
		if number != nextNumber:
			if nextNumber in pastNum:

				# formats first numbers
				spelledNum = num2words(number)
				repStep1 = spelledNum.replace("-", "_")
				finRep = repStep1.replace(" ", "_")

				# formats second numbers
				nextSpelledNum = num2words(nextNumber)
				nextRepStep1 = nextSpelledNum.replace("-", "_")
				nextFinRep = nextRepStep1.replace(" ", "_")

				# outputs final line format
				newLine = finRep + "_" + nextFinRep
				finalLine2 = "Rscript --vanilla %s %sHybridFSTRun.txt %sHybridFSTRun.out\n" % (pythonPath, newLine, newLine)
				out.write(finalLine2)

	pastNum.append(number)

out.close()

# line format should go python, pathway, python script, inFile, outFile, num1, num2
# python ~/Users/User/Documents/Hufford_labs/David_data/chapter2/allPopFSTRun/HybVEachPop_heirFStat python BreakingFStatHybV.py ZeaAllInfo.14col.allHybVeachPop.heirFstat one_twoHybridFSTRun.txt 1 2

#
# path = "~/Documents/Hufford_labs/David_data/chapter2/allPopFSTRun/HybVEachPop_heirFStat/"
# pythonPath = path + "BreakingFStatHybV.py"
# dataPath = path + "ZeaAllInfo.14col.allHybVeachPop.heirFstat"
#
# pastNum = []
# # creates number range 106
# for number in range(1,107):
# 	for nextNumber in range(1,107):
# 		if number != nextNumber:
# 			if nextNumber in pastNum:
#
# 				# formats first numbers
# 				spelledNum = num2words(number)
# 				repStep1 = spelledNum.replace("-", "_")
# 				finRep = repStep1.replace(" ", "_")
#
# 				# formats second numbers
# 				nextSpelledNum = num2words(nextNumber)
# 				nextRepStep1 = nextSpelledNum.replace("-", "_")
# 				nextFinRep = nextRepStep1.replace(" ", "_")
#
# 				# outputs final line format
# 				newLine = finRep + "_" + nextFinRep
# 				finalLine2 = "python %s %s %sHybridFSTRun.txt %s %s\n" % (pythonPath, dataPath, newLine, str(number), str(nextNumber))
# 				out.write(finalLine2)
#
# 	pastNum.append(number)
#
#
# out.close()
#
# # line format should go python, pathway, python script, inFile, outFile, num1, num2
# # python ~/Users/User/Documents/Hufford_labs/David_data/chapter2/allPopFSTRun/HybVEachPop_heirFStat python BreakingFStatHybV.py ZeaAllInfo.14col.allHybVeachPop.heirFstat one_twoHybridFSTRun.txt 1 2


text:
package io.spikex.filter.input;

import com.github.brainlag.nsq.NSQConsumer;
import com.github.brainlag.nsq.NSQMessage;
import com.github.brainlag.nsq.callbacks.NSQErrorCallback;
import com.github.brainlag.nsq.callbacks.NSQMessageCallback;
import com.github.brainlag.nsq.exceptions.NSQException;
import com.google.common.base.Preconditions;
import io.spikex.core.AbstractFilter;
import io.spikex.filter.internal.NsqClientConfig;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vertx.java.core.eventbus.EventBus;
import org.vertx.java.core.json.JsonObject;

/**
 *
 * @author cli
 */
public final class Nsq extends AbstractFilter {

    private List<NSQConsumer> m_consumers;

    @Override
    protected void startFilter() {

        NsqClientConfig config = NsqClientConfig.builder(config()).build();
        List<String> topics = config.getTopics();

        // Sanity check
        Preconditions.checkArgument(topics.size() > 0, "No topics defined");
        m_consumers = new ArrayList();

        for (String topic : topics) {

            String channel = "";
            int pos = topic.indexOf(":");

            if (pos != -1) {
                channel = topic.substring(pos + 1);
                topic = topic.substring(0, pos);
            } else {
                throw new IllegalArgumentException("No channel definied for topic: " + topic);
            }

            logger().info("Creating consumer for topic: {} channel: {}", topic, channel);
            NSQConsumer consumer = new NSQConsumer(
                    config.buildNSQLookup(),
                    topic,
                    channel,
                    new NsqMessageHandler(eventBus(), getDestinationAddress()),
                    config.buildNSQConfig(variables()),
                    new NSQErrorCallback() {

                        @Override
                        public void error(final NSQException e) {
                            logger().error("NSQ consumer error", e);

                        }
                    });

            m_consumers.add(consumer);
            consumer.setMessagesPerBatch(config.getMessagesPerBatch());
            consumer.setLookupPeriod(config.getLookupPeriod());

            BlockingQueue<Runnable> messageQueue = new LinkedBlockingQueue(config.getMessagesQueueSize());
            consumer.setExecutor(
                    new ThreadPoolExecutor(
                            config.getCorePoolSize(),
                            config.getMaxPoolSize(),
                            config.getIdleThreadKeepAliveTime(),
                            TimeUnit.MILLISECONDS,
                            messageQueue));
            consumer.start();
        }
    }

    @Override
    protected void stopFilter() {
        if (m_consumers != null) {
            for (NSQConsumer consumer : m_consumers) {
                try {
                    consumer.shutdown();
                } catch (Exception e) {
                    logger().error("Failed to shutdown NSQ consumer", e);
                }
            }
        }
    }

    private static class NsqMessageHandler implements NSQMessageCallback {

        private final EventBus m_eventBus;
        private final String m_address;
        private final Logger m_logger = LoggerFactory.getLogger(NsqMessageHandler.class);

        private NsqMessageHandler(
                final EventBus eventBus,
                final String address) {

            m_eventBus = eventBus;
            m_address = address;
        }

        @Override
        public void message(final NSQMessage message) {

            String id = new String(message.getId(), StandardCharsets.UTF_8);
            String body = new String(message.getMessage(), StandardCharsets.UTF_8);
            JsonObject json = new JsonObject(body);

            m_logger.trace("Received NSQ message {}: {} - publishing on {}", id, json, m_address);
            m_eventBus.publish(m_address, json);
            message.finished(); // Signal that we're done...
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Microsoft.WindowsAPICodePack.DirectX.Direct2D1;

namespace D2DShapes
{
    internal class GeometryShape : DrawingShape
    {
        private Geometry geometry;
        internal PathGeometry geometryOutlined;
        internal PathGeometry geometrySimplified;
        internal PathGeometry geometryWidened;
        internal Matrix3x2F? worldTransform;

        public GeometryShape(RenderTarget initialRenderTarget, Random random, D2DFactory d2DFactory, D2DBitmap bitmap)
            : base(initialRenderTarget, random, d2DFactory, bitmap)
        {
            coolStrokes = CoinFlip;
            double which = Random.NextDouble();
            if (which < 0.67 || coolStrokes)
                PenBrush = RandomBrush();
            if (!coolStrokes && which > 0.33)
                FillBrush = RandomBrush();
            if (coolStrokes || CoinFlip)
                StrokeStyle = RandomStrokeStyle();
            if (CoinFlip)
                worldTransform = RandomMatrix3x2();
            StrokeWidth = RandomStrokeWidth();
            geometry = RandomGeometry();
            if (coolStrokes || Random.NextDouble() < 0.3)
                ModifyGeometry();
            if (coolStrokes && CoinFlip)
            {
                ModifyGeometry();
            }
        }

        [TypeConverter(typeof(ExpandableObjectConverter))]
        public Geometry Geometry
        {
            get { return geometry; }
            set { geometry = value; }
        }

        private void ModifyGeometry()
        {
            GeometrySink geometrySink;
            double which = Random.NextDouble();
            if (which < 0.33)
            {
                geometryOutlined = d2DFactory.CreatePathGeometry();
                geometrySink = geometryOutlined.Open();
                geometry.Outline(geometrySink, FlatteningTolerance);
                geometrySink.Close();
                geometrySink.Dispose();
                geometry.Dispose();
                geometry = geometryOutlined;
            }
            else if (which < 0.67)
            {
                geometrySimplified = d2DFactory.CreatePathGeometry();
                geometrySink = geometrySimplified.Open();
                geometry.Simplify(
                    CoinFlip
                        ? GeometrySimplificationOption.Lines
                        : GeometrySimplificationOption.CubicsAndLines,
                    geometrySink,
                    FlatteningTolerance
                    );
                geometrySink.Close();
                geometrySink.Dispose();
                geometry.Dispose();
                geometry = geometrySimplified;
            }
            else
            {
                geometryWidened = d2DFactory.CreatePathGeometry();
                geometrySink = geometryWidened.Open();
                geometry.Widen(
                    RandomStrokeWidth(), //75
                    RandomStrokeStyle(),
                    geometrySink,
                    FlatteningTolerance);
                geometrySink.Close();
                geometrySink.Dispose();
                geometry.Dispose();
                geometry = geometryWidened;
            }
        }

        //this could be called recursively
        public Geometry RandomGeometry()
        {
            return RandomGeometry(0);
        }

        public Geometry RandomGeometry(int level)
        {
            Geometry g = null;

            while (g == null)
            {
                double which = Random.NextDouble();

                if (which < 0.20)
                    g = RandomEllipseGeometry();
                else if (which < 0.40)
                    g = RandomRoundRectGeometry();
                else if (which < 0.60)
                    g = RandomRectangleGeometry();
                else if (which < 0.80)
                    g = RandomPathGeometry();
                else if (level < 3)
                    g = RandomGeometryGroup(level + 1);
            }

            if (worldTransform.HasValue)
                g = d2DFactory.CreateTransformedGeometry(g, worldTransform.Value);

            return g;
        }

        private Geometry RandomTransformedGeometry()
        {
            Geometry start, ret;
            start = RandomGeometry();
            ret = d2DFactory.CreateTransformedGeometry(
                start,
                RandomMatrix3x2());
            start.Dispose();
            return ret;
        }

        private Geometry RandomGeometryGroup(int level)
        {
            var geometries = new List<Geometry>();
            int count = Random.Next(1, 5);
            for (int i = 0; i < count; i++)
                geometries.Add(RandomGeometry(level));
            GeometryGroup ret = d2DFactory.CreateGeometryGroup(
                Random.NextDouble() < .5 ? FillMode.Winding : FillMode.Alternate,
                geometries);
            foreach (var g in geometries)
            {
                g.Dispose();
            }
            return ret;
        }

        private PathGeometry RandomPathGeometry()
        {
            PathGeometry g = d2DFactory.CreatePathGeometry();
            int totalSegmentCount = 0;
            int figureCount = Random.Next(1, 2);
            using (GeometrySink sink = g.Open())
            {
                for (int f = 0; f < figureCount; f++)
                {
                    int segmentCount = Random.Next(2, 20);
                    AddRandomFigure(sink, segmentCount);
                    totalSegmentCount += segmentCount;
                }
                sink.Close();
            }
            System.Diagnostics.Debug.Assert(g.SegmentCount == totalSegmentCount);
            System.Diagnostics.Debug.Assert(g.FigureCount == figureCount);
            return g;
        }

        private void AddRandomFigure(IGeometrySink sink, int segmentCount)
        {
            previousPoint = null;
            sink.BeginFigure(
                RandomNearPoint(),
                CoinFlip ? FigureBegin.Filled : FigureBegin.Hollow);
            FigureEnd end = CoinFlip ? FigureEnd.Closed : FigureEnd.Closed;
            if (end == FigureEnd.Closed)
                segmentCount--;
            if (CoinFlip)
                for (int i = 0; i < segmentCount; i++)
                    AddRandomSegment(sink);
            else
            {
                double which = Random.NextDouble();
                if (which < 0.33)
                    sink.AddLines(RandomLines(segmentCount));
                else if (which < 0.67)
                    sink.AddQuadraticBeziers(RandomQuadraticBeziers(segmentCount));
                else
                    sink.AddBeziers(RandomBeziers(segmentCount));
            }
            sink.EndFigure(end);
        }

        private IEnumerable<Point2F> RandomLines(int segmentCount)
        {
            var lines = new List<Point2F>();
            for (int i = 0; i < segmentCount; i++)
                lines.Add(RandomNearPoint());
            return lines;
        }

        private IEnumerable<QuadraticBezierSegment> RandomQuadraticBeziers(int segmentCount)
        {
            var beziers = new List<QuadraticBezierSegment>();
            for (int i = 0; i < segmentCount; i++)
                beziers.Add(new QuadraticBezierSegment(
                    RandomNearPoint(),
                    RandomNearPoint()));
            return beziers;
        }

        private IEnumerable<BezierSegment> RandomBeziers(int segmentCount)
        {
            var beziers = new List<BezierSegment>();
            for (int i = 0; i < segmentCount; i++)
                beziers.Add(new BezierSegment(
                    RandomNearPoint(),
                    RandomNearPoint(),
                    RandomNearPoint()));
            return beziers;
        }

        private void AddRandomSegment(IGeometrySink sink)
        {
            double which = Random.NextDouble();
            if (which < 0.25)
                sink.AddLine(RandomNearPoint());
            else if (which < 0.5)
                sink.AddArc(RandomArc());
            else if (which < 0.75)
                sink.AddBezier(RandomBezier());
            else if (which < 1.0)
            sink.AddQuadraticBezier(RandomQuadraticBezier());
        }

        private QuadraticBezierSegment RandomQuadraticBezier()
        {
            return new QuadraticBezierSegment(
                RandomNearPoint(),
                RandomNearPoint());
        }

        private BezierSegment RandomBezier()
        {
            return new BezierSegment(
                RandomNearPoint(),
                RandomNearPoint(),
                RandomNearPoint());
        }

        private ArcSegment RandomArc()
        {
            return new ArcSegment(
                RandomNearPoint(),
                RandomSize(),
                (float)Random.NextDouble() * 360,
                CoinFlip ? SweepDirection.Clockwise : SweepDirection.Counterclockwise,
                CoinFlip ? ArcSize.Large : ArcSize.Small
                );
        }

        private SizeF RandomSize()
        {
            return new SizeF(
                (float)Random.NextDouble() * CanvasWidth,
                (float)Random.NextDouble() * CanvasHeight);
        }

        private RoundedRectangleGeometry RandomRoundRectGeometry()
        {
            return d2DFactory.CreateRoundedRectangleGeometry(
                RandomRoundedRect());
        }

        private RectangleGeometry RandomRectangleGeometry()
        {
            return d2DFactory.CreateRectangleGeometry(
                RandomRect(CanvasWidth, CanvasHeight));
        }

        private EllipseGeometry RandomEllipseGeometry()
        {
            return d2DFactory.CreateEllipseGeometry(
                RandomEllipse());
        }

        protected internal override void ChangeRenderTarget(RenderTarget newRenderTarget)
        {
            PenBrush = CopyBrushToRenderTarget(PenBrush, newRenderTarget);
            FillBrush = CopyBrushToRenderTarget(FillBrush, newRenderTarget);
        }

        protected internal override void Draw(RenderTarget renderTarget)
        {
            Geometry g = geometry;
            if (FillBrush != null)
            {
                renderTarget.FillGeometry(g, FillBrush, null);
            }
            if (PenBrush != null)
            {
                if (StrokeStyle != null)
                {
                    renderTarget.DrawGeometry(g, PenBrush, StrokeWidth, StrokeStyle);
                }
                else
                {
                    renderTarget.DrawGeometry(g, PenBrush, StrokeWidth);
                }
            }
        }

        public override bool HitTest(Point2F point)
        {
            return geometry.FillContainsPoint(point, FlatteningTolerance);
        }

        public override void Dispose()
        {
            if (geometry != null)
                geometry.Dispose();
            geometry = null;
            base.Dispose();
        }
    }
}


text:
import * as THREE from 'three/src/Three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import Stats from 'three/examples/jsm/libs/stats.module.js';

import "./main.css";

import { CelestialBody, AU, AxisAngleQuaternion } from './CelestialBody';
import { Settings, SettingsControl } from './SettingsControl';
import { TimeScaleControl } from './TimeScaleControl';
import { ThrottleControl } from './ThrottleControl';
import { navballRadius, RotationControl, RotationButtons } from './RotationControl';
import { OrbitalElementsControl } from './OrbitalElementsControl';
import { zerofill, StatsControl } from './StatsControl';
import { BodiesControl } from './BodiesControl';
import { MessageControl } from './MessageControl';
import { ScenarioSelectorControl } from './ScenarioSelectorControl';
import { SaveControl } from './SaveControl';
import { LoadControl } from './LoadControl';
import Overlay from './Overlay';
import GameState from './GameState';

import backgroundUrl from './images/hipparcoscyl1.jpg';

let container: HTMLElement;
let stats: Stats;
let camera: THREE.PerspectiveCamera;
let scene: THREE.Scene;
let renderer: THREE.WebGLRenderer;
let background: THREE.Scene;
let overlay: Overlay;
let timescaleControl: TimeScaleControl;
let throttleControl: ThrottleControl;
let speedControl: any;
let orbitalElementsControl: OrbitalElementsControl;
let statsControl: StatsControl;
let bodiesControl: BodiesControl;
let settingsControl: SettingsControl;
let altitudeControl: any;
let messageControl: MessageControl;
let cameraControls: OrbitControls;
let grids: THREE.Object3D;
let scenarioSelectorControl: ScenarioSelectorControl;
let saveControl: SaveControl;
let loadControl: LoadControl;

let windowHalfX = window.innerWidth / 2;
let windowHalfY = window.innerHeight / 2;
let viewScale = 100;

let gameState: GameState;
let settings = new Settings();

let buttons = new RotationButtons();
let accelerate = false;
let decelerate = false;

function init() {

    container = document.createElement( 'div' );
    document.body.appendChild(container);

    const headerTitle = document.createElement('div');
    headerTitle.id = 'info';
    headerTitle.innerHTML = 'Orbital rocket simulation demo - powered by three.js';
    document.body.appendChild(headerTitle);

    const metaViewport = document.createElement('meta');
    metaViewport.setAttribute('name', 'viewport');
    metaViewport.setAttribute('content', "width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0");
    document.head.appendChild(metaViewport);

    camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 10000 );
    camera.position.y = 300;
    camera.position.z = 1000;
    camera.up.set(0,0,1);

    background = new THREE.Scene();
    background.rotation.x = Math.PI / 2;
    const loader = new THREE.TextureLoader();
    loader.load( backgroundUrl, function ( texture ) {

        const geometry = new THREE.SphereGeometry( 2, 20, 20 );

        const material = new THREE.MeshBasicMaterial( { map: texture, depthTest: false, depthWrite: false, side: THREE.BackSide } );
        material.depthWrite = false;
        const mesh = new THREE.Mesh(geometry, material);
        background.add(mesh);

    } );

    overlay = new Overlay();

    scene = new THREE.Scene();

    const orbitMaterial = new THREE.LineBasicMaterial({color: 0x3f3f7f});
    CelestialBody.prototype.orbitMaterial = orbitMaterial; // Default orbit material

    gameState = new GameState({
        scene,
        viewScale,
        overlay: overlay.overlay,
        camera,
        windowHalfX,
        windowHalfY,
     }, settings, (msg) => messageControl.setText(msg));

    const meshMaterial = new THREE.LineBasicMaterial({color: 0x3f3f3f});
    const meshGeometry = new THREE.BufferGeometry();
    const meshVertices = [];
    for(let x = -10; x <= 10; x++)
        meshVertices.push( -10, x, 0, 10, x, 0);
    for(let x = -10; x <= 10; x++)
        meshVertices.push(   x, -10, 0, x, 10, 0);
    meshGeometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(meshVertices), 3));
    grids = new THREE.Object3D();
    const mesh = new THREE.LineSegments(meshGeometry, meshMaterial);
    mesh.scale.x = mesh.scale.y = 100;
    grids.add(mesh);
    const mesh2 = new THREE.LineSegments(meshGeometry, meshMaterial);
    mesh2.scale.x = mesh2.scale.y = 10000 / AU * 100;
    grids.add(mesh2);

    function addAxis(axisVector: THREE.Vector3, color: number){
        const axisXMaterial = new THREE.LineBasicMaterial({color: color});
        const axisXGeometry = new THREE.BufferGeometry();
        axisXGeometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(
            [0, 0, 0, axisVector.x, axisVector.y, axisVector.z]), 3));
        const axisX = new THREE.Line(axisXGeometry, axisXMaterial);
        axisX.scale.multiplyScalar(100);
        grids.add(axisX);
    }
    addAxis(new THREE.Vector3(100,0,0), 0xff0000);
    addAxis(new THREE.Vector3(0,100,0), 0x00ff00);
    addAxis(new THREE.Vector3(0,0,100), 0x0000ff);

    scene.add(grids);

    camera.position.set(0.005, 0.003, 0.005);

    renderer = new THREE.WebGLRenderer();
    renderer.setClearColor( 0x000000 );
    renderer.setSize( window.innerWidth, window.innerHeight );
    renderer.autoClear = false;

    cameraControls = new OrbitControls(camera, renderer.domElement);
    cameraControls.target.set( 0, 0, 0);
    cameraControls.enablePan = false;
    cameraControls.maxDistance = 4000;
    cameraControls.minDistance = 1 / AU;
    cameraControls.zoomSpeed = 5.;
    cameraControls.update();

    container.appendChild( renderer.domElement );

    stats = Stats();
    stats.domElement.style.position = 'absolute';
    stats.domElement.style.top = '0px';
    container.appendChild( stats.domElement );

    timescaleControl = new TimeScaleControl(function(scale){ return gameState.setTimeScale(scale); });
    container.appendChild( timescaleControl.domElement );

    throttleControl = new ThrottleControl(windowHalfX, function(pos){ return gameState.allowThrottle(pos); },
        function(){ return gameState.getSelectObj(); });
    container.appendChild( throttleControl.domElement );

    const rotationControl = new RotationControl(buttons, () => gameState.getSelectObj());
    container.appendChild( rotationControl.domElement );

    class SpeedControl{
        protected element: HTMLDivElement;
        get domElement(){ return this.element; }
        protected valueElement: HTMLDivElement;
        constructor(){
            function setSize(){
                element.style.top = (window.innerHeight - 2 * navballRadius - 32) + 'px';
                element.style.left = (window.innerWidth / 2 - element.getBoundingClientRect().width / 2) + 'px';
            }
            const buttonHeight = 32;
            const buttonWidth = 32;
            this.element = document.createElement('div');
            const element = this.element;
            element.style.position = 'absolute';
            setSize();
            element.style.zIndex = '7';
            element.style.background = 'rgba(0, 0, 0, 0.5)';
            window.addEventListener('resize', setSize);
            const title = document.createElement('div');
            title.innerHTML = 'Orbit';
            element.appendChild(title);
            this.valueElement = document.createElement('div');
            element.appendChild(this.valueElement);
        }

        setSpeed(){
            if(gameState.select_obj){
                const value = gameState.select_obj.velocity.length() * AU;
                if(value < 1)
                    this.valueElement.innerHTML = (value * 1000).toFixed(4) + 'm/s';
                else
                    this.valueElement.innerHTML = value.toFixed(4) + 'km/s';
            }
            else
                this.valueElement.innerHTML = '';
            this.element.style.left = (window.innerWidth / 2 - this.element.getBoundingClientRect().width / 2) + 'px';
        }
    }
    speedControl = new SpeedControl();
    container.appendChild( speedControl.domElement );

    orbitalElementsControl = new OrbitalElementsControl();
    container.appendChild( orbitalElementsControl.domElement );

    bodiesControl = new BodiesControl((selectedObj) => {
        gameState.select_obj = selectedObj;
        throttleControl.visible = selectedObj.controllable;
    });
    container.appendChild( bodiesControl.domElement );

    bodiesControl.setContent(gameState.universe.sun);
    bodiesControl.selectBody(gameState.select_obj);

    settingsControl = new SettingsControl(settings);
    statsControl = new StatsControl(settingsControl, function() { return gameState.getSelectObj(); });
    container.appendChild( statsControl.domElement );
    container.appendChild( settingsControl.domElement );

    class AltitudeControl{
        protected element: HTMLDivElement;
        get domElement(){ return this.element; }
        protected valueElement: HTMLDivElement;
        constructor(){
            const buttonHeight = 32;
            const buttonWidth = 32;
            this.element = document.createElement('div');
            const element = this.element;
            element.style.position = 'absolute';
            element.style.top = '2em';
            element.style.left = '50%';
            element.style.background = 'rgba(0,0,0,0.5)';
            element.style.zIndex = '8';
            const visible = false;

            // Register event handlers
            element.ondragstart = function(event){
                event.preventDefault();
            };
        }

        setText(value: number){
            let text;
            if(value < 1e5)
                text = value.toFixed(4) + 'km';
            else if(value < 1e8)
                text = (value / 1000).toFixed(4) + 'Mm';
            else
                text = (value / AU).toFixed(4) + 'AU';
            this.element.innerHTML = text;
            this.element.style.marginLeft = -this.element.getBoundingClientRect().width / 2 + 'px';
        }
    }
    altitudeControl = new AltitudeControl();
    container.appendChild( altitudeControl.domElement );

    messageControl = new MessageControl();
    container.appendChild( messageControl.domElement );

    scenarioSelectorControl = new ScenarioSelectorControl(
        () => gameState.universe.sun.findRocket(),
        (obj) => bodiesControl.selectBody(obj),
        function(throttle){ throttleControl.setThrottle(throttle); },
        function(){ gameState.resetTime(); },
        function(msg){ messageControl.setText(msg); },
        function(){
            [saveControl, loadControl].map(function(control){ control.setVisible(false); }); // Mutually exclusive
        }
    );
    container.appendChild( scenarioSelectorControl.domElement );

    saveControl = new SaveControl(
        function(){ return gameState.serializeState(); },
        function(msg){ messageControl.setText(msg); },
        function(){
            [scenarioSelectorControl, loadControl].map(function(control){ control.setVisible(false); }); // Mutually exclusive
        }
    );
    container.appendChild( saveControl.domElement );

    gameState.onStateLoad = () => throttleControl.setThrottle(gameState.select_obj.throttle);

    loadControl = new LoadControl(
        function(state){ gameState.loadState(state) },
        function(msg){ messageControl.setText(msg); },
        function(){
            [scenarioSelectorControl, saveControl].map(function(control){ control.setVisible(false); }); // Mutually exclusive
        }
    );
    container.appendChild( loadControl.domElement );

    window.addEventListener( 'resize', onWindowResize, false );
    window.addEventListener( 'keydown', onKeyDown, false );
    window.addEventListener( 'keyup', onKeyUp, false );
    window.addEventListener( 'pageshow', function(){
        const state = localStorage.getItem('WebGLOrbiterAutoSave');
        if(state){
            gameState.loadState(JSON.parse(state));
        }
    });
    window.addEventListener( 'beforeunload', function(){
        localStorage.setItem('WebGLOrbiterAutoSave', JSON.stringify(gameState.serializeState()));
    });

    gameState.startTicking();
}

function onWindowResize() {

    windowHalfX = window.innerWidth / 2;
    windowHalfY = window.innerHeight / 2;

    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    renderer.setSize( window.innerWidth, window.innerHeight );

}

function animate() {

    requestAnimationFrame( animate );

    render();
    stats.update();

}

function render() {
    const [time, realDeltaTimeMilliSec, deltaTime] = gameState.updateTime();
    timescaleControl.setDate(time.getFullYear() + '/' + zerofill(time.getMonth() + 1) + '/' + zerofill(time.getDate())
        + ' ' + zerofill(time.getHours()) + ':' + zerofill(time.getMinutes()) + ':' + zerofill(time.getSeconds()));
    speedControl.setSpeed();
    statsControl.setText(gameState.getMissionTime());
    settingsControl.setText();
    messageControl.timeStep(realDeltaTimeMilliSec * 1e-3);

    camera.near = Math.min(1, cameraControls.target.distanceTo(camera.position) / 10);
    camera.updateProjectionMatrix();

    const acceleration = 5e-10;
    const div = 100; // We should pick subdivide simulation step count by angular speed!

    for(let d = 0; d < div; d++){
        // Allow trying to increase throttle when timewarping in order to show the message
        if(accelerate) throttleControl.increment(deltaTime / div);
        if(decelerate) throttleControl.decrement(deltaTime / div);

        gameState.simulateBody(deltaTime, div, buttons);
    }

    const select_obj = gameState.getSelectObj();
    gameState.universe.update(settings.center_select, viewScale, settings, camera, windowHalfX, windowHalfY,
        function(o, headingApoapsis){
            orbitalElementsControl.setText(o, headingApoapsis, settings.units_km);
        },
        scene,
        select_obj
    );

    grids.visible = settings.grid_enable;

//				camera.up.copy(new THREE.Vector3(0,0,1)); // This did't work with OrbitControls
    cameraControls.update();

    const oldPosition = camera.position.clone();
    const oldQuaternion = camera.quaternion.clone();
    if(settings.sync_rotate && select_obj){
        camera.quaternion.copy(
            select_obj.quaternion.clone()
            .multiply(AxisAngleQuaternion(0, 1, 0, -1*Math.PI / 2)));
        camera.position.copy(new THREE.Vector3(0, 0.2, 1).normalize().multiplyScalar(camera.position.length()).applyQuaternion(camera.quaternion));
    }
    const position = camera.position.clone();
    camera.position.set(0,0,0);
    renderer.render( background, camera);
    camera.position.copy(position);
    renderer.render( scene, camera );

    if(select_obj){
        overlay.update(select_obj);
        camera.position.set(0,0,0);
        camera.quaternion.set(1,0,0,0);
        overlay.render(renderer);
    }

    const orbitalElementsBottom = orbitalElementsControl.getBottom();
    bodiesControl.domElement.style.top = `${orbitalElementsBottom + 4}px`;

    // Restore the original state because cameraControls expect these variables unchanged
    camera.quaternion.copy(oldQuaternion);
    camera.position.copy(oldPosition);

    if(select_obj && select_obj.getParent()){
        altitudeControl.setText(select_obj.position.length() * AU - select_obj.getParent().radius);
    }
    else
        altitudeControl.setText(0);
}

function onKeyDown( event: KeyboardEvent ) {
    const char = String.fromCharCode(event.which || event.keyCode).toLowerCase();

    const select_obj = gameState.getSelectObj();
    if(select_obj && select_obj.controllable) switch( char ){
        case 'z':
            throttleControl.setThrottle(1);
            break;
        case 'x':
            throttleControl.setThrottle(0);
            break;
    }

    // Annoying browser incompatibilities
    const code = event.which || event.keyCode;
    // Also support numpad plus and minus
    if(code === 107 || code === 187 && event.shiftKey)
        timescaleControl.increment();
    if(code === 109 || code === 189)
        timescaleControl.decrement();
    if(code === 16)
        accelerate = true;
    if(code === 17)
        decelerate = true;
}

function onKeyUp( event: KeyboardEvent ) {
    // Annoying browser incompatibilities
    const code = event.which || event.keyCode;
    if(code === 16)
        accelerate = false;
    if(code === 17)
        decelerate = false;
}

init();
animate();


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Text;
using Azure.Core.Diagnostics;
using NUnit.Framework;
using NUnit.Framework.Interfaces;

namespace Azure.Core.TestFramework
{
    /// <summary>
    /// The TestLogger listens for the AzureSDK logging event source and traces
    /// the output so it's easy to view the logs when testing.
    ///
    /// We create an instance in SearchTestBase when we want to log test
    /// output.
    /// </summary>
    internal class TestLogger : IDisposable
    {
        /// <summary>
        /// EventSource listener for AzureSDK events.
        /// </summary>
        private AzureEventSourceListener Listener { get; }

        /// <summary>
        /// Start collecting AzureSDK events to log.
        /// </summary>
        public TestLogger()
        {
            Listener = new AzureEventSourceListener(
                (e, _) => LogEvent(e),
                EventLevel.Verbose);
        }

        /// <summary>
        /// Trace any SDK events.
        /// </summary>
        /// <param name="args">Event arguments.</param>
        public void LogEvent(EventWrittenEventArgs args)
        {
            var category = args.EventName;
            IDictionary<string, string> payload = GetPayload(args);

            // If there's a request ID, use it after the category
            var message = new StringBuilder();
            message
                .Append("[")
                .Append(DateTime.Now.ToString("HH:mm:ss.FFF"))
                .Append("] ")
                .Append(args.EventName).Append(" ");
            if (payload.TryGetValue("requestId", out var requestId))
            {
                payload.Remove("requestId");
                message.Append(requestId);
            }
            message.AppendLine();

            // Add the rest of the payload
            foreach (KeyValuePair<string, string> arg in payload)
            {
                message.AppendFormat("  {0}: ", arg.Key);

                // Don't indent the content's lines
                if (arg.Key == "content" && arg.Value.Length > 0)
                {
                    message.AppendLine("\n" + arg.Value);
                    continue;
                }

                var lines = arg.Value.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
                if (lines.Length == 1)
                {
                    // If there's only one line, write it after the name
                    message.AppendLine(lines[0]);
                }
                else
                {
                    // Otherwise add a newline and indent each nested line
                    message.AppendLine();
                    foreach (var line in lines.Select(l => $"    {l}"))
                    {
                        message.AppendLine(line);
                    }
                }
            }

            // Dump the message and category
            Trace.WriteLine(message, category);

            // Add a line to separate requests/responses within a single test
            message.AppendLine();
            // Output the request/response
            TestContext.Out.WriteLine(message.ToString());
        }

        /// <summary>
        /// Convert the event arguments into a dictionary of strings.
        /// </summary>
        /// <param name="args">The event arguments.</param>
        /// <returns>A dictionary of strings.</returns>
        private static IDictionary<string, string> GetPayload(EventWrittenEventArgs args)
        {
            var payload = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            for (var i = 0; i < args.Payload.Count; i++)
            {
                var name = args.PayloadNames[i];
                var value = "";
                switch (args.Payload[i])
                {
                    case null:
                        break;
                    case string s:
                        value = s;
                        break;
                    case byte[] content:
                        value = Encoding.UTF8.GetString(content);
                        // Control characters mess up copy/pasting so we'll
                        // swap them with the SUB character
                        value = new string(value.Select(ch => !char.IsControl(ch) ? ch : '�').ToArray());
                        break;
                    default:
                        value = args.Payload[i].ToString();
                        break;
                }
                payload.Add(name, value);
            }
            return payload;
        }

        /// <summary>
        /// Cleans up the <see cref="AzureEventSourceListener"/> instance.
        /// </summary>
        public void Dispose() => Listener?.Dispose();
    }
}


text:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>

<configuration>
  <property>
    <name>drill_user</name>
    <value>drill</value>
    <description>User who will run the drillbit</description>
  </property>
  <property>
    <name>drill_group</name>
    <value>drill</value>
    <description>Drill Group</description>
  </property>
  <property>
    <name>drill_log_dir</name>
    <value>/var/log/drill</value>
    <description>Location in which save log files</description>
  </property>
  <property>
    <name>drill_max_direct_memory</name>
    <value>8G</value>
  </property>
  <property>
    <name>drill_heap_size</name>
    <value>4G</value>
  </property>
  <property>
    <name>content</name>
    <value>
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.

DRILL_MAX_DIRECT_MEMORY="{{drill_max_direct_memory}}"
DRILL_HEAP="{{drill_heap_size}}"

export DRILL_JAVA_OPTS="-Xms$DRILL_HEAP -Xmx$DRILL_HEAP -XX:MaxDirectMemorySize=$DRILL_MAX_DIRECT_MEMORY -XX:MaxPermSize=512M -XX:ReservedCodeCacheSize=1G -Ddrill.exec.enable-epoll=true"

# Class unloading is disabled by default in Java 7
# http://hg.openjdk.java.net/jdk7u/jdk7u60/hotspot/file/tip/src/share/vm/runtime/globals.hpp#l1622
export SERVER_GC_OPTS="-XX:+CMSClassUnloadingEnabled -XX:+UseG1GC "
    </value>
  </property>
</configuration>


text:
<?php

namespace React\Dns\Query;

interface ExecutorInterface
{
    /**
     * Executes a query and will return a response message
     *
     * It returns a Promise which either fulfills with a response
     * `React\Dns\Model\Message` on success or rejects with an `Exception` if
     * the query is not successful. A response message may indicate an error
     * condition in its `rcode`, but this is considered a valid response message.
     *
     * ```php
     * $executor->query($query)->then(
     *     function (React\Dns\Model\Message $response) {
     *         // response message successfully received
     *         var_dump($response->rcode, $response->answers);
     *     },
     *     function (Exception $error) {
     *         // failed to query due to $error
     *     }
     * );
     * ```
     *
     * The returned Promise MUST be implemented in such a way that it can be
     * cancelled when it is still pending. Cancelling a pending promise MUST
     * reject its value with an Exception. It SHOULD clean up any underlying
     * resources and references as applicable.
     *
     * ```php
     * $promise = $executor->query($query);
     *
     * $promise->cancel();
     * ```
     *
     * @param Query $query
     * @return \React\Promise\PromiseInterface<\React\Dns\Model\Message,\Exception>
     *     resolves with response message on success or rejects with an Exception on error
     */
    public function query(Query $query);
}


text:
module Kitcat
  # +Kitcat::Logging+ is used to encapsulate the functionality of +Framework+ related to
  # logging.
  #
  # It needs to be initialized with the +migration_name+ because this is used to build the
  # relevant log filename.
  #
  class Logging
    attr_reader :migration_name, :migration_strategy

    def initialize(migration_strategy, migration_name)
      @migration_name = build_migration_name(migration_name, migration_strategy)
    end

    def log_file_path
      @log_file_path ||= File.join(log_dir, build_log_file_name)
    end

    def start_logging
      logger.info 'Start Processing...'
    end

    def end_logging
      logger.info '...end of processing'
    end

    def log_success(item)
      log_line(item) { |method| logger.info "...successfully processed item: #{item.try(method)}" }
    end

    def log_failure(item)
      log_line(item) { |method| logger.error "...error while processing item: #{item.try(method)}" }
    end

    def log_interrupt_callback_start
      logger.info '...user interrupted, calling interrupt callback on migration strategy...'
    end

    def log_interrupt_callback_finish
      logger.info '......end of interrupt callback after user interruption'
    end

    private

    def build_migration_name(migration_name, migration_strategy)
      result = migration_name || migration_strategy.class.name.delete(':').underscore.upcase
      result.gsub(/\W/, '').upcase
    end

    def log_dir
      @log_dir ||= FileUtils.mkdir_p(File.join(Dir.pwd, 'log'))
    end

    def build_log_file_name
      "migration-#{migration_name}-#{timestamp}.log"
    end

    def timestamp
      Time.now.to_s(:number)
    end

    def logger
      @logger ||= Logger.new(log_file_path)
    end

    def log_line(item)
      method = item.respond_to?(:to_log) ? :to_log : :to_s
      yield method
    end
  end
end


text:
<?php
    function longdate($timestamp)
    {
        $temp = date("l F jS Y", $timestamp);
        return "The date is $temp";
    }
    echo longdate(time());
?>


text:
package com.frostwire.jlibtorrent.alerts;

import com.frostwire.jlibtorrent.swig.alerts_dropped_alert;

/**
 * This alert is posted to indicate to the client that some alerts were
 * dropped. Dropped meaning that the alert failed to be delivered to the
 * client. The most common cause of such failure is that the internal alert
 * queue grew too big (controlled by alert_queue_size).
 *
 * @author gubatron
 * @author aldenml
 */
public final class AlertsDroppedAlert extends AbstractAlert<alerts_dropped_alert> {

    AlertsDroppedAlert(alerts_dropped_alert alert) {
        super(alert);
    }
}


text:
Sample Text to Image Application by Ashley Ford, demo on his website - http://papermashup.com/demos/php-gd-image-and-text/

This repo is kept for personal work. You should work with Ashley Ford's one.


text:
---
uid: SolidEdgePart.ResizeHole.Type
summary:
remarks:
---