text:
package com.github.cameltooling.idea.runner.debugger;

import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.ui.ExecutionConsole;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.xdebugger.XDebugProcess;
import com.intellij.xdebugger.XDebugSession;
import com.intellij.xdebugger.XSourcePosition;
import com.intellij.xdebugger.breakpoints.XBreakpointHandler;
import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider;
import com.intellij.xdebugger.evaluation.XDebuggerEvaluator;
import com.intellij.xdebugger.frame.XSuspendContext;
import com.intellij.xdebugger.frame.XValueMarkerProvider;
import com.intellij.xdebugger.stepping.XSmartStepIntoHandler;
import com.intellij.xdebugger.ui.XDebugTabLayouter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.concurrency.Promise;

import javax.swing.event.HyperlinkListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;

public class ContextAwareDebugProcess extends XDebugProcess {
    private final ProcessHandler processHandler;
    private final Map<String, XDebugProcess> debugProcesses;
    private String currentContext;
    private final String defaultContext;

    public ContextAwareDebugProcess(@NotNull XDebugSession session, ProcessHandler processHandler,
                                    Map<String, XDebugProcess> debugProcesses, String defaultContext) {
        super(session);
        this.processHandler = processHandler;
        this.debugProcesses = debugProcesses;
        this.currentContext = defaultContext;
        this.defaultContext = defaultContext;
    }

    public void setContext(String context) {
        this.currentContext = context;
    }

    @Override
    @NotNull
    public XBreakpointHandler<?>[] getBreakpointHandlers() {
        List<XBreakpointHandler<?>> breakpointHandlers = new ArrayList<>();
        final Collection<XDebugProcess> values = debugProcesses.values();
        for (XDebugProcess value : values) {
            breakpointHandlers.addAll(Arrays.asList(value.getBreakpointHandlers()));
        }
        return breakpointHandlers.toArray(new XBreakpointHandler[0]);
    }

    @Override
    @NotNull
    public XDebuggerEditorsProvider getEditorsProvider() {
        return getCurrentDebugProcess().getEditorsProvider();
    }

    @Override
    public void sessionInitialized() {
        getCurrentDebugProcess().sessionInitialized();
    }

    @Override
    public void startPausing() {
        getCurrentDebugProcess().startPausing();
    }

    @Override
    public void startStepOver(@Nullable XSuspendContext context) {
        getCurrentDebugProcess().startStepOver(context);
    }

    @Override
    public void startForceStepInto(@Nullable XSuspendContext context) {
        getCurrentDebugProcess().startForceStepInto(context);
    }

    @Override
    public void startStepInto(@Nullable XSuspendContext context) {
        getCurrentDebugProcess().startStepInto(context);
    }

    @Override
    public void startStepOut(@Nullable XSuspendContext context) {
        getCurrentDebugProcess().startStepOut(context);
    }

    @Override
    @Nullable
    public XSmartStepIntoHandler<?> getSmartStepIntoHandler() {
        return getCurrentDebugProcess().getSmartStepIntoHandler();
    }

    @Override
    public void stop() {
        final Collection<XDebugProcess> values = debugProcesses.values();
        for (XDebugProcess value : values) {
            value.stop();
        }
    }

    @Override
    @NotNull
    public Promise<Object> stopAsync() {
        for (XDebugProcess value : debugProcesses.values()) {
            value.stopAsync();
        }
        return getDefaultDebugProcess().stopAsync();
    }

    @Override
    public void resume(@Nullable XSuspendContext context) {
        getCurrentDebugProcess().resume(context);
    }

    @Override
    public void runToPosition(@NotNull XSourcePosition xSourcePosition, @Nullable XSuspendContext context) {
        getCurrentDebugProcess().runToPosition(xSourcePosition, context);
    }

    @Override
    public boolean checkCanPerformCommands() {
        return getCurrentDebugProcess().checkCanPerformCommands();
    }

    @Override
    public boolean checkCanInitBreakpoints() {
        return getCurrentDebugProcess().checkCanInitBreakpoints();
    }

    @Override
    @Nullable
    public ProcessHandler doGetProcessHandler() {
        return processHandler;
    }

    @Override
    @NotNull
    public ExecutionConsole createConsole() {
        return getDefaultDebugProcess().createConsole();
    }

    @Override
    @Nullable
    public XValueMarkerProvider<?, ?> createValueMarkerProvider() {
        return getDefaultDebugProcess().createValueMarkerProvider();
    }

    @Override
    public void registerAdditionalActions(@NotNull DefaultActionGroup leftToolbar, @NotNull DefaultActionGroup topToolbar,
                                          @NotNull DefaultActionGroup settings) {
        for (XDebugProcess value : debugProcesses.values()) {
            value.registerAdditionalActions(leftToolbar, topToolbar, settings);
        }
    }

    @Override
    public String getCurrentStateMessage() {
        return getCurrentDebugProcess().getCurrentStateMessage();
    }

    @Override
    @Nullable
    public HyperlinkListener getCurrentStateHyperlinkListener() {
        return getCurrentDebugProcess().getCurrentStateHyperlinkListener();
    }

    @Override
    @NotNull
    public XDebugTabLayouter createTabLayouter() {
        return getDefaultDebugProcess().createTabLayouter();
    }

    @Override
    public boolean isValuesCustomSorted() {
        return getCurrentDebugProcess().isValuesCustomSorted();
    }

    @Override
    @Nullable
    public XDebuggerEvaluator getEvaluator() {
        return getCurrentDebugProcess().getEvaluator();
    }

    public XDebugProcess getDefaultDebugProcess() {
        return debugProcesses.get(defaultContext);
    }

    public XDebugProcess getCurrentDebugProcess() {
        final XDebugProcess debugProcess = currentContext != null ? debugProcesses.get(currentContext) : null;
        return debugProcess != null ? debugProcess : getDefaultDebugProcess();
    }

    public Map<String, XDebugProcess> getAllDebugProcesses() {
        return debugProcesses;
    }
}


text:
START_ATF_NAMESPACE
    typedef _FILETIME *PFILETIME;
END_ATF_NAMESPACE

redpajama_set_name: RedPajamaGithub


text:
title: TIMES LITERARY SUPPLEMENT (STORBRITANNIA) on Et velsignet barn
date: 2002-04-04 00:00:00 -0500
book: no/books/et-velsignet-barn.md
attribution: TIMES LITERARY SUPPLEMENT (STORBRITANNIA)
link_to_original: ''
featured: false
weight: ''

---
'I denne rikeste av hennes fire fremragende romaner' og at historien er 'gjengitt med formidable kontrapunktiske narrative evner … _Et velsignet barn_ viser Ullmanns evne til å hevde fantasiens uforgjengelighet'


text:
Log

 0">

    <input ng-model="searchText" type="search" class="form-control" placeholder="Search" />

        #
        Date
        Event type
        Message

        {{ entry.date | date:'HH:mm:ss dd MMM yyyy' }}

<div class="alert alert-info" ng-if="entries.length <= 0">
  Note! Log is empty.


text:
<!DOCTYPE html>
<meta charset=utf-8>
<title>form autocomplete attribute</title>
<link rel="author" title="Denis Ah-Kang" href="mailto:denis@w3.org">
<link rel=help href="https://html.spec.whatwg.org/multipage/#the-form-element">
<link rel=help href="https://html.spec.whatwg.org/multipage/#attr-fe-autocomplete">

<form name="missing_attribute">
  <input>
  <input autocomplete="on">
  <input autocomplete="off">
  <input autocomplete="foobar">
</form>
<form name="autocomplete_on" autocomplete="on">
  <input>
  <input autocomplete="on">
  <input autocomplete="off">
  <input autocomplete="foobar">
</form>
<form name="autocomplete_off" autocomplete="off">
  <input>
  <input autocomplete="on">
  <input autocomplete="off">
  <input autocomplete="foobar">
</form>
<form name="autocomplete_invalid" autocomplete="foobar">
  <input>
  <input autocomplete="on">
  <input autocomplete="off">
  <input autocomplete="foobar">
</form>


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('smartshark', '0021_auto_20160616_1205'),
    ]

    operations = [
        migrations.CreateModel(
            name='Job',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('job_id', models.IntegerField()),
                ('status', models.CharField(choices=[('PEND', 'Pending'), ('PROV', 'Dispatched to power-save host'), ('PSUSP', 'Suspended (pending)'), ('RUN', 'Running'), ('USUSP', 'Suspended (running)'), ('SSUSP', 'Suspended (other)'), ('DONE', 'Done'), ('EXIT', 'Exit'), ('UNKWN', 'Unknown'), ('WAIT', 'Waiting'), ('ZOMBI', 'Zombie!!')], max_length=8)),
                ('output_log', models.CharField(max_length=200)),
                ('error_log', models.CharField(max_length=200)),
                ('revision_path', models.CharField(blank=True, max_length=100)),
                ('submission_string', models.CharField(max_length=300)),
            ],
        ),
        migrations.RenameField(
            model_name='pluginexecution',
            old_name='added_at',
            new_name='submitted_at',
        ),
        migrations.RemoveField(
            model_name='pluginexecution',
            name='error_log',
        ),
        migrations.RemoveField(
            model_name='pluginexecution',
            name='job_id',
        ),
        migrations.RemoveField(
            model_name='pluginexecution',
            name='output_log',
        ),
        migrations.RemoveField(
            model_name='pluginexecution',
            name='revision',
        ),
        migrations.RemoveField(
            model_name='pluginexecution',
            name='status',
        ),
        migrations.RemoveField(
            model_name='pluginexecution',
            name='submission_value',
        ),
        migrations.AddField(
            model_name='job',
            name='plugin_execution',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='smartshark.PluginExecution'),
        ),
    ]


text:
""" This module implements an high-level function to create the classic
Fashion MNIST split CL scenario. """
from pathlib import Path
from typing import Sequence, Optional, Union, Any
from torchvision import transforms

from avalanche.benchmarks import nc_benchmark
from avalanche.benchmarks.classic.classic_benchmarks_utils import (
    check_vision_benchmark,
)
from avalanche.benchmarks.datasets.external_datasets.fmnist import \
    get_fmnist_dataset

_default_fmnist_train_transform = transforms.Compose(
    [transforms.ToTensor(), transforms.Normalize((0.2860,), (0.3530,))]
)

_default_fmnist_eval_transform = transforms.Compose(
    [transforms.ToTensor(), transforms.Normalize((0.2860,), (0.3530,))]
)

def SplitFMNIST(
    n_experiences: int,
    *,
    first_batch_with_half_classes: bool = False,
    return_task_id=False,
    seed: Optional[int] = None,
    fixed_class_order: Optional[Sequence[int]] = None,
    shuffle: bool = True,
    class_ids_from_zero_in_each_exp: bool = False,
    train_transform: Optional[Any] = _default_fmnist_train_transform,
    eval_transform: Optional[Any] = _default_fmnist_eval_transform,
    dataset_root: Union[str, Path] = None
):
    """
    Creates a CL benchmark using the Fashion MNIST dataset.

    If the dataset is not present in the computer, this method will
    automatically download and store it.

    The returned benchmark will return experiences containing all patterns of a
    subset of classes, which means that each class is only seen "once".
    This is one of the most common scenarios in the Continual Learning
    literature. Common names used in literature to describe this kind of
    scenario are "Class Incremental", "New Classes", etc. By default,
    an equal amount of classes will be assigned to each experience.

    This generator doesn't force a choice on the availability of task labels,
    a choice that is left to the user (see the `return_task_id` parameter for
    more info on task labels).

    The benchmark instance returned by this method will have two fields,
    `train_stream` and `test_stream`, which can be iterated to obtain
    training and test :class:`Experience`. Each Experience contains the
    `dataset` and the associated task label.

    The benchmark API is quite simple and is uniform across all benchmark
    generators. It is recommended to check the tutorial of the "benchmark" API,
    which contains usage examples ranging from "basic" to "advanced".

    :param n_experiences: The number of experiences in the current
        benchmark. If the first experience is a "pretraining" step and it
        contains half of the classes. The value of this parameter should be a
        divisor of 10 if first_task_with_half_classes if false, a divisor of 5
        otherwise.
    :param first_batch_with_half_classes: A boolean value that indicates if a
        first pretraining batch containing half of the classes should be used.
        If it's True, a pretraining batch with half of the classes (5 for
        cifar100) is used. If this parameter is False no pretraining task
        will be used, and the dataset is simply split into
        a the number of experiences defined by the parameter n_experiences.
        Default to False.
    :param return_task_id: if True, a progressive task id is returned for every
        experience. If False, all experiences will have a task ID of 0.
    :param seed: A valid int used to initialize the random number generator.
        Can be None.
    :param fixed_class_order: A list of class IDs used to define the class
        order. If None, value of ``seed`` will be used to define the class
        order. If non-None, ``seed`` parameter will be ignored.
        Defaults to None.
    :param shuffle: If true, the class order in the incremental experiences is
        randomly shuffled. Default to True.
    :param class_ids_from_zero_in_each_exp: If True, original class IDs
        will be mapped to range [0, n_classes_in_exp) for each experience.
        Defaults to False. Mutually exclusive with the
        ``class_ids_from_zero_from_first_exp`` parameter.
    :param train_transform: The transformation to apply to the training data,
        e.g. a random crop, a normalization or a concatenation of different
        transformations (see torchvision.transform documentation for a
        comprehensive list of possible transformations).
        If no transformation is passed, the default train transformation
        will be used.
    :param eval_transform: The transformation to apply to the test data,
        e.g. a random crop, a normalization or a concatenation of different
        transformations (see torchvision.transform documentation for a
        comprehensive list of possible transformations).
        If no transformation is passed, the default test transformation
        will be used.
    :param dataset_root: The root path of the dataset. Defaults to None, which
        means that the default location for 'fashionmnist' will be used.

    :returns: A properly initialized :class:`NCScenario` instance.
    """

    fmnist_train, fmnist_test = get_fmnist_dataset(dataset_root)

    return nc_benchmark(
        train_dataset=fmnist_train,
        test_dataset=fmnist_test,
        n_experiences=n_experiences,
        task_labels=return_task_id,
        seed=seed,
        fixed_class_order=fixed_class_order,
        shuffle=shuffle,
        per_exp_classes={0: 5} if first_batch_with_half_classes else None,
        class_ids_from_zero_in_each_exp=class_ids_from_zero_in_each_exp,
        train_transform=train_transform,
        eval_transform=eval_transform,
    )

__all__ = ["SplitFMNIST"]

if __name__ == "__main__":
    import sys

    benchmark_instance = SplitFMNIST(n_experiences=10)
    check_vision_benchmark(benchmark_instance)
    sys.exit(0)


text:
// Mntone HTML5 UIKit (MNKit) is under MIT license. Copyright (C) 2014 mntone

module MNKit.Utilities
{
	"use strict";

	export function isUndefined( value: any ): boolean
	{
		return value === undefined;
	}

	export function isNull( value: any ): boolean
	{
		return !isUndefined( value ) && value == null;
	}

	export function isFunction( value: any ): boolean
	{
		return typeof value === "function";
	}

	export function clone( value: any ): any
	{
		var ret = {};
		if( value != null )
		{
			Object.keys( value ).forEach( key => ret[key] = value[key] );
		}
		return ret;
	}
}


text:
package org.apache.sshd.common.util.logging;

import java.util.concurrent.atomic.AtomicReference;

import org.apache.sshd.common.util.GenericUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Serves as a common base class for the vast majority of classes that require
 * some kind of logging. Facilitates quick and easy replacement of the actual used
 * logger from one framework to another
 *
 * @author Apache MINA SSHD Project
 */
public abstract class AbstractLoggingBean {
    protected final Logger log;
    private final AtomicReference<SimplifiedLog> simplifiedLog = new AtomicReference<>();

    /**
     * Default constructor - creates a logger using the full class name
     */
    protected AbstractLoggingBean() {
        this("");
    }

    /**
     * Create a logger for instances of the same class for which we might
     * want to have a "discriminator" for them
     *
     * @param discriminator The discriminator value - ignored if {@code null}
     * or empty
     */
    protected AbstractLoggingBean(String discriminator) {
        String name = getClass().getName();
        if (GenericUtils.length(discriminator) > 0) {
            name += "[" + discriminator + "]";
        }
        log = LoggerFactory.getLogger(name);
    }

    protected SimplifiedLog getSimplifiedLogger() {
        SimplifiedLog logger;
        synchronized (simplifiedLog) {
            logger = simplifiedLog.get();
            if (logger == null) {
                logger = LoggingUtils.wrap(log);
            }
        }

        return logger;
    }
}


text:
/**
* @file
* @brief  Implementation of CPACS wing handling routines.
*/

#ifndef CCPACSWING_H
#define CCPACSWING_H

#include <string>

#include "generated/CPACSWing.h"
#include "tigl_config.h"
#include "CTiglTransformation.h"
#include "CTiglRelativelyPositionedComponent.h"
#include "CCPACSWingSections.h"
#include "CCPACSWingSegments.h"
#include "CCPACSWingComponentSegments.h"
#include "CCPACSPositionings.h"
#include "CTiglAbstractSegment.h"
#include "CCPACSGuideCurve.h"
#include "Cache.h"

#include "TopoDS_Shape.hxx"
#include "TopoDS_Compound.hxx"

namespace tigl
{
class CCPACSConfiguration;

class CCPACSWing : public generated::CPACSWing, public CTiglRelativelyPositionedComponent
{
friend class CTiglWingBuilder;

public:
    // Constructor
    TIGL_EXPORT CCPACSWing(CCPACSWings* parent, CTiglUIDManager* uidMgr);
    TIGL_EXPORT CCPACSWing(CCPACSRotorBlades* parent, CTiglUIDManager* uidMgr);

    // Virtual destructor
    TIGL_EXPORT ~CCPACSWing() override;

    // Read CPACS wing elements
    TIGL_EXPORT void ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& wingXPath) override;

    TIGL_EXPORT std::string GetDefaultedUID() const override;

    // Override setters for invalidation
    TIGL_EXPORT void SetSymmetryAxis(const TiglSymmetryAxis& axis) override;
    TIGL_EXPORT void SetParentUID(const boost::optional<std::string>& value) override;

    // Returns whether this wing is a rotor blade
    TIGL_EXPORT bool IsRotorBlade() const;

    // Returns the parent configuration
    TIGL_EXPORT CCPACSConfiguration & GetConfiguration() const;

    // Get section count
    TIGL_EXPORT int GetSectionCount() const;

    // Returns the section for a given index
    TIGL_EXPORT CCPACSWingSection& GetSection(int index);
    TIGL_EXPORT const CCPACSWingSection& GetSection(int index) const;

    // Getter of the number of segments of the wing
    TIGL_EXPORT int GetSegmentCount() const;

    // Returns the segment for a given index or uid
    TIGL_EXPORT CCPACSWingSegment& GetSegment(const int index);
    TIGL_EXPORT const CCPACSWingSegment& GetSegment(const int index) const;
    TIGL_EXPORT CCPACSWingSegment& GetSegment(std::string uid);
    TIGL_EXPORT const CCPACSWingSegment& GetSegment(std::string uid) const;

    // Getter of the number of component segments of the wing
    TIGL_EXPORT int GetComponentSegmentCount() const;

    // Returns the segment for a given index or uid
    TIGL_EXPORT CCPACSWingComponentSegment& GetComponentSegment(const int index);
    TIGL_EXPORT const CCPACSWingComponentSegment& GetComponentSegment(const int index) const;
    TIGL_EXPORT CCPACSWingComponentSegment& GetComponentSegment(const std::string& uid);

    // Get the positioning transformation for a given section uid
    TIGL_EXPORT CTiglTransformation GetPositioningTransformation(std::string sectionUID);

    // Gets the upper point in absolute (world) coordinates for a given segment, eta, xsi
    TIGL_EXPORT gp_Pnt GetUpperPoint(int segmentIndex, double eta, double xsi);

    // Gets the upper point in absolute (world) coordinates for a given segment, eta, xsi
    TIGL_EXPORT gp_Pnt GetLowerPoint(int segmentIndex, double eta, double xsi);

    // Gets a point on the chord surface in absolute (world) coordinates for a given segment, eta, xsi
    TIGL_EXPORT gp_Pnt GetChordPoint(int segmentIndex, double eta, double xsi, TiglCoordinateSystem referenceCS = GLOBAL_COORDINATE_SYSTEM);

    // Gets the loft of the whole wing
    TIGL_EXPORT TopoDS_Shape & GetLoftWithLeadingEdge();

    // Returns the wing loft with cut out control surfaces
    TIGL_EXPORT TopoDS_Shape GetLoftWithCutouts();

    TIGL_EXPORT TopoDS_Shape & GetUpperShape();
    TIGL_EXPORT TopoDS_Shape & GetLowerShape();

    // Gets the volume of this wing
    TIGL_EXPORT double GetVolume();

    // Gets the surfade area of this wing
    TIGL_EXPORT double GetSurfaceArea();

    // Returns the reference area of the wing by taking account the drilateral portions
    // of each wing segment by projecting the wing segments into the plane defined by the user
    TIGL_EXPORT double GetReferenceArea(TiglSymmetryAxis symPlane) const;

    // Returns the reference area of the wing in the plane normal to the major direction
    TIGL_EXPORT double GetReferenceArea() const;

    // Returns wetted Area
    TIGL_EXPORT double GetWettedArea(TopoDS_Shape parent) const;

    // Returns the wingspan of the wing
    TIGL_EXPORT double GetWingspan() const;

    // Returns the aspect ratio of the wing
    TIGL_EXPORT double GetAspectRatio() const;

    // Returns the mean aerodynamic chord of the wing
    TIGL_EXPORT void  GetWingMAC(double& mac_chord, double& mac_x, double& mac_y, double& mac_z) const;

    // Calculates the segment coordinates from global (x,y,z) coordinates
    // Returns the segment index of the according segment
    // If x,y,z does not belong to any segment, -1 is returned
    TIGL_EXPORT int GetSegmentEtaXsi(const gp_Pnt& xyz, double& eta, double& xsi, bool &onTop);

    // Returns the Component Type TIGL_COMPONENT_WING.
    TIGL_EXPORT TiglGeometricComponentType GetComponentType() const override
    {
        return !IsRotorBlade() ? TIGL_COMPONENT_WING : TIGL_COMPONENT_ROTORBLADE;
    }

    TIGL_EXPORT TiglGeometricComponentIntent GetComponentIntent() const override {return TIGL_INTENT_PHYSICAL; }

    // Returns the lower Surface of a Segment
    TIGL_EXPORT Handle(Geom_Surface) GetLowerSegmentSurface(int index);

    // Returns the upper Surface of a Segment
    TIGL_EXPORT Handle(Geom_Surface) GetUpperSegmentSurface(int index);

    // Get the guide curve segment (partial guide curve) with a given UID
    TIGL_EXPORT CCPACSGuideCurve& GetGuideCurveSegment(std::string uid);

    // Returns all points that define the guide curves
    TIGL_EXPORT std::vector<gp_Pnt> GetGuideCurvePoints();

    // Returns all guide curve wires as a compound
    TIGL_EXPORT TopoDS_Compound GetGuideCurveWires() const;

    // Returns the "fromRelCirc" parameter for each guide curve wire
    TIGL_EXPORT std::vector<double> GetGuideCurveStartParameters() const;

    // Adjust, whether the wing should be modeled with the flaps or not
    TIGL_EXPORT void SetBuildFlaps(bool enabled);

    // Returns the wing shape without any extended flaps
    TIGL_EXPORT PNamedShape GetWingCleanShape() const;

    // Sets the getPointBehavior to asParameterOnSurface or onLinearLoft
    TIGL_EXPORT void SetGetPointBehavior(TiglGetPointBehavior behavior = asParameterOnSurface);

    // Gets the getPointBehavior
    TIGL_EXPORT TiglGetPointBehavior const GetGetPointBehavior() const;
    TIGL_EXPORT TiglGetPointBehavior GetGetPointBehavior();

protected:

    struct LocatedGuideCurves
    {
        struct LocatedGuideCurve
        {
            TopoDS_Wire wire;
            double fromRelCircumference;
        };

        TopoDS_Compound wiresAsCompound;
        std::vector<LocatedGuideCurve> curves;
    };

    void BuildGuideCurveWires(LocatedGuideCurves& cache) const;

    // Cleanup routine
    void Cleanup();

    // Update internal wing data
    void Update();

    // Adds all Segments of this wing to one shape
    void BuildFusedSegments(PNamedShape& ) const;

    PNamedShape BuildLoft() const override;

    void BuildUpperLowerShells();

private:
    // Invalidates internal state
    void InvalidateImpl(const boost::optional<std::string>& source) const override;

    // get short name for loft
    std::string GetShortShapeName() const;
    void BuildWingWithCutouts(PNamedShape&) const;
    // Adds all Segments of this wing and flaps to one shape
    PNamedShape GroupedFlapsAndWingShapes() const;

private:
    bool                           isRotorBlade;             /**< Indicates if this wing is a rotor blade */
    CCPACSConfiguration*           configuration;            /**< Parent configuration*/
    TopoDS_Shape                   fusedSegmentWithEdge;     /**< All Segments in one shape plus modelled leading edge */
    TopoDS_Shape                   upperShape;
    TopoDS_Shape                   lowerShape;

    Cache<LocatedGuideCurves, CCPACSWing> guideCurves;

    Cache<PNamedShape, CCPACSWing> wingShapeWithCutouts;     /**< Wing without flaps / flaps removed */
    Cache<PNamedShape, CCPACSWing> wingCleanShape;           /**< Clean wing surface without flaps cutout*/
    mutable bool                   rebuildFusedSegWEdge;     /**< Indicates if segmentation fusing need rebuild */
    mutable bool                   rebuildShells;
    bool                           buildFlaps;               /**< Indicates if the wing's loft shall include flaps */
    FusedElementsContainerType     fusedElements;            /**< Stores already fused segments */
    double                         myVolume;                 /**< Volume of this Wing           */

    TiglGetPointBehavior getPointBehavior {asParameterOnSurface};

    friend class CCPACSWingSegment;
    friend class CCPACSWingComponentSegment;
};

/// Transforms a shape in profile coordinates to world coordinates
TIGL_EXPORT TopoDS_Shape transformWingProfileGeometry(const CTiglTransformation& wingTransform, const CTiglWingConnection& connection, const TopoDS_Shape& wire);

} // end namespace tigl

#endif // CCPACSWING_H


text:
This package add a little Keybind for Markdown.

## Usage

Ctrl-c i
: Insert Image tag **`![]()`**

Ctrl-c l
: Insert Link tag **`[]()`**

If you select a word, convert to tag with it. ex) Test to `[Test]()`.

## License

MIT.


text:
<?php

namespace Seld\JsonLint;

class DuplicateKeyException extends ParsingException
{
    /**
     * @phpstan-ignore-next-line
     * @var array{key: string, line: int}
     */
    protected $details;

    /**
     * @param string $message
     * @param string $key
     * @phpstan-param array{line: int} $details
     */
    public function __construct($message, $key, array $details)
    {
        $details['key'] = $key;
        parent::__construct($message, $details);
    }

    /**
     * @return string
     */
    public function getKey()
    {
        return $this->details['key'];
    }

    /**
     * @phpstan-return array{key: string, line: int}
     */
    public function getDetails()
    {
        return $this->details;
    }
}


text:
<title>Hello, Page</title>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

  Free boobs!
  Click me!!!


text:
XCrataPult.server
=================
Magic manuscripts

#### Automatically installs, configures and starts
- **PHP7** in fpm mode
- **MySQL server 5.7+**
- **Nginx 1.0+** with http2 support and qualys A+ grade HTTPS config
- **Redis-server** optional (installer will ask)
- **PHPRedis** (latest on github) with support of **Igbinary** (latest on github)
- **XCrataPult.CMS** (includes CMF and X)
- **UFW** (firewall) with allowed SSH, HTTP and HTTPS by default (installer will ask)

#### And:
- Redis connections limited to unix socket
- MySQL connections limited to unix socket and localhost TCP:3306 (3306 blocked by firewall by default from any to any excluding localhost to localhost)
- all proper owners and rights are set to www directory
- XCrataPult.[CMS](https://github.com/mrXCray/XCrataPult.CMS)/[CMF](https://github.com/mrXCray/XCrataPult.CMF)/[X](https://github.com/mrXCray/XCrataPult.php) are ready to use. Just include('includeme.php')

#### So...

Server is ready to handle web-sites, just put code into /home/www/(domain.name).

You should use any SQL management client via SSH to connect to MySQL socket /var/run/mysqld/mysqld.sock or via SSH tunnel to 127.0.0.1:3306
1
#### To alter configuration

All configs are at their default places, no worries.

#### Install on Ubuntu 14.04 LTS or better

```
cd /home
sudo wget --output-document install.sh https://raw.githubusercontent.com/mrXCray/XCrataPult.server/master/server-install/install.sh?nocache
sudo chmod +x install.sh
sudo ./install.sh
```

#### Upgrade for XCrataPult.CMS/Framework

```
cd /home
sudo wget --output-document xcms-update.sh https://raw.githubusercontent.com/mrXCray/XCrataPult.server/master/server-install/xcms-update.sh?nocache
sudo chmod +x xcms-update.sh
sudo ./xcms-update.sh
```

#### Add XCrataPult project
```
x_add_project.sh domain.ru
```
Script will create folder `/home/www/domain.ru` with initialized configuration and correct permissions.
Since folder name matching domain name is enought to add a new website, there is no need to alter nginx configuration at all.


text:
package org.eclipse.moquette.parser.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import org.eclipse.moquette.proto.messages.PubCompMessage;
import org.eclipse.moquette.proto.messages.AbstractMessage;

/**
 *
 * @author andrea
 */
class PubCompEncoder extends DemuxEncoder<PubCompMessage> {

    @Override
    protected void encode(ChannelHandlerContext chc, PubCompMessage msg, ByteBuf out) {
        out.writeByte(AbstractMessage.PUBCOMP << 4);
        out.writeBytes(Utils.encodeRemainingLength(2));
        out.writeShort(msg.getMessageID());
    }
}


text:
@interface ZNBAddCmtController ()<UITextViewDelegate>
@property (weak, nonatomic) IBOutlet UITextField *replyTextF;
@property (weak, nonatomic) IBOutlet UITextField *beReplyTextF;
@property (weak, nonatomic) IBOutlet UITextView *contentTextV;
@property (weak, nonatomic) IBOutlet UILabel *placeHoder;

@end

@implementation ZNBAddCmtController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.contentTextV.delegate = self;
    self.title = @"添加评论";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveCmt)];
    if (self.cmtUid.length) {
        ZNBTimeLineCmtModel *cmtModel = [ZNBTimeLineCmtModel objectForPrimaryKey:self.cmtUid];
        self.replyTextF.text = cmtModel.replyName;
        self.beReplyTextF.text = cmtModel.beReplyName;
        self.contentTextV.text = cmtModel.content;
        self.placeHoder.hidden = YES;
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear: animated];
    [MobClick beginLogPageView:@"添加评论界面"];
}

- (void)viewWillDisappear:(BOOL)animated {

    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"添加评论界面"];

}
- (void)textViewDidChange:(UITextView *)textView {

    if (textView.text.length) {
        self.placeHoder.hidden = YES;
    }else {
        self.placeHoder.hidden = NO;
    }
}

- (void)saveCmt {
    if (!self.replyTextF.text.length) {
        [ZNBAnimationManager shakeView:self.view];
        UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:@"评论人必填" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alerView show];
        return;
    }

    RLMRealm *realm = [RLMRealm defaultRealm];
    ZNBTimeLineModel *model = [ZNBTimeLineModel objectForPrimaryKey:self.uid];
    ZNBTimeLineCmtModel *cmtModel;
    if (self.cmtUid.length) {
        cmtModel = [ZNBTimeLineCmtModel objectForPrimaryKey:self.cmtUid];
        [realm transactionWithBlock:^{
            cmtModel.replyName = self.replyTextF.text;
            cmtModel.beReplyName = self.beReplyTextF.text;
            cmtModel.content = self.contentTextV.text;
        }];
    }else {
        NSString *cmtUid = [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970]];
        cmtModel = [[ZNBTimeLineCmtModel alloc] init];
        cmtModel.uid = cmtUid;
        cmtModel.replyName = self.replyTextF.text;
        cmtModel.beReplyName = self.beReplyTextF.text;
        cmtModel.content = self.contentTextV.text;

        [realm beginWriteTransaction];
        [model.cmtArr addObject:cmtModel];
        [ZNBTimeLineCmtModel createOrUpdateInRealm:realm withValue:cmtModel];
//        [ZNBTimeLineModel createOrUpdateInRealm:realm withValue:model];
        [realm commitWriteTransaction];
    }

    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
package org.apache.carbondata.core.datastore.columnar;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

import org.apache.carbondata.core.constants.CarbonCommonConstants;
import org.apache.carbondata.core.util.ByteUtil;

public class BlockIndexerStorageForNoInvertedIndex implements IndexStorage<int[]> {
  private byte[][] keyBlock;
  private byte[][] sortedBlock;
  private int totalSize;
  private int[] dataIndexMap;

  public BlockIndexerStorageForNoInvertedIndex(byte[][] keyBlockInput, boolean compressData,
      boolean isNoDictionary) {
    // without invertedindex but can be RLE
    if (compressData) {
      // with RLE
      byte[] prvKey = keyBlockInput[0];
      List<byte[]> list = new ArrayList<byte[]>(CarbonCommonConstants.CONSTANT_SIZE_TEN);
      list.add(keyBlockInput[0]);
      int counter = 1;
      int start = 0;
      List<Integer> map = new ArrayList<Integer>(CarbonCommonConstants.CONSTANT_SIZE_TEN);
      int length = keyBlockInput.length;
      for (int i = 1; i < length; i++) {
        if (ByteUtil.UnsafeComparer.INSTANCE.compareTo(prvKey, keyBlockInput[i]) != 0) {
          prvKey = keyBlockInput[i];
          list.add(keyBlockInput[i]);
          map.add(start);
          map.add(counter);
          start += counter;
          counter = 1;
          continue;
        }
        counter++;
      }
      map.add(start);
      map.add(counter);
      this.keyBlock = convertToKeyArray(list);
      if (keyBlockInput.length == this.keyBlock.length) {
        dataIndexMap = new int[0];
      } else {
        dataIndexMap = convertToArray(map);
      }
    } else {
      this.keyBlock = keyBlockInput;
      dataIndexMap = new int[0];
    }

    this.sortedBlock = new byte[keyBlock.length][];
    System.arraycopy(keyBlock, 0, sortedBlock, 0, keyBlock.length);
    if (isNoDictionary) {
      Arrays.sort(sortedBlock, new Comparator<byte[]>() {
        @Override
        public int compare(byte[] col1, byte[] col2) {
          return ByteUtil.UnsafeComparer.INSTANCE
              .compareTo(col1, 2, col1.length - 2, col2, 2, col2.length - 2);
        }
      });
    } else {
      Arrays.sort(sortedBlock, new Comparator<byte[]>() {
        @Override
        public int compare(byte[] col1, byte[] col2) {
          return ByteUtil.UnsafeComparer.INSTANCE.compareTo(col1, col2);
        }
      });
    }

  }

  private int[] convertToArray(List<Integer> list) {
    int[] shortArray = new int[list.size()];
    for (int i = 0; i < shortArray.length; i++) {
      shortArray[i] = list.get(i);
    }
    return shortArray;
  }

  private byte[][] convertToKeyArray(List<byte[]> list) {
    byte[][] shortArray = new byte[list.size()][];
    for (int i = 0; i < shortArray.length; i++) {
      shortArray[i] = list.get(i);
      totalSize += shortArray[i].length;
    }
    return shortArray;
  }

  @Override
  public int[] getDataIndexMap() {
    return dataIndexMap;
  }

  @Override
  public int getTotalSize() {
    return totalSize;
  }

  @Override
  public boolean isAlreadySorted() {
    return true;
  }

  /**
   * no use
   * @return
   */
  @Override
  public int[] getDataAfterComp() {
    return new int[0];
  }

  /**
   * no use
   * @return
   */
  @Override
  public int[] getIndexMap() {
    return new int[0];
  }

  /**
   * @return the keyBlock
   */
  public byte[][] getKeyBlock() {
    return keyBlock;
  }

  @Override public byte[] getMin() {
    return sortedBlock[0];
  }

  @Override public byte[] getMax() {
    return sortedBlock[sortedBlock.length - 1];
  }

}


text:
/*!
  \file
  \version \$Id$
  \author Moritz Bunkus <moritz@bunkus.org>
*/
#ifndef LIBEBML_SAFEREADIOCALLBACK_H
#define LIBEBML_SAFEREADIOCALLBACK_H

#include "EbmlTypes.h"

START_LIBEBML_NAMESPACE

class EBML_DLL_API IOCallback;
class EBML_DLL_API EbmlBinary;

class EBML_DLL_API SafeReadIOCallback {
public:
  class EndOfStreamX {
  public:
    size_t mMissingBytes;
    EndOfStreamX(std::size_t MissingBytes);
  };

private:
  IOCallback *mIO;
  bool mDeleteIO;
  size_t mSize;

public:
  SafeReadIOCallback(IOCallback *IO, bool DeleteIO);
  SafeReadIOCallback(void const *Mem, size_t Size);
  SafeReadIOCallback(EbmlBinary const &Binary);
  ~SafeReadIOCallback();

  size_t GetPosition() const;
  size_t GetSize() const;
  size_t GetRemainingBytes() const;
  bool IsEmpty() const;

  uint8  GetUInt8();
  uint64 GetUIntBE(size_t NumBytes);
  uint16 GetUInt16BE();
  uint32 GetUInt24BE();
  uint32 GetUInt32BE();
  uint64 GetUInt64BE();

  void Read(void *Dst, size_t Count);

  void Skip(size_t Count);
  void Seek(size_t Position);

private:
  SafeReadIOCallback(SafeReadIOCallback const &) { }

protected:
  void Init(IOCallback *IO, bool DeleteIO);
};

END_LIBEBML_NAMESPACE

#endif  // LIBEBML_SAFEREADIOCALLBACK_H


text:
var gulp = require('gulp');
var runSequence = require('run-sequence');

gulp.task('default', function(cb){
  runSequence(
    'clean',
    ['copy', 'sass', 'javascript', 'jade'],
    ['watch', 'server'],
  cb);
});


text:
package com.spiddekauga.servlet;

import org.junit.Test;

import java.lang.reflect.Field;

import static org.junit.Assert.assertEquals;

/**
 * Tests the App servlet class
 */
public class AppServletTest {
@Test
public void getServiceRootUrl_defaultService() throws NoSuchFieldException, IllegalAccessException {
	AppServlet appServlet = new AppServlet() {
	};

	Field fRootUrl = AppServlet.class.getDeclaredField("mRootUrl");
	fRootUrl.setAccessible(true);

	// Test with default service
	fRootUrl.set(appServlet, "https://test-app.appspot.com");
	String correctUrl = "https://service-dot-test-app.appspot.com";
	String serviceUrl = appServlet.getServiceRootUrl("service");
	assertEquals(correctUrl, serviceUrl);
}

@Test
public void getServiceRootUrl_existingService() throws NoSuchFieldException, IllegalAccessException {
	AppServlet appServlet = new AppServlet() {
	};

	Field fRootUrl = AppServlet.class.getDeclaredField("mRootUrl");
	fRootUrl.setAccessible(true);

	// Test with existing service
	String correctUrl = "https://service-dot-test-app.appspot.com";
	fRootUrl.set(appServlet, "https://existing-dot-test-app.appspot.com");
	String serviceUrl = appServlet.getServiceRootUrl("service");
	assertEquals("Existing service", correctUrl, serviceUrl);
}
}


text:
package ch.octo.cffpoc.gtfs

import java.util.Date

import org.joda.time.{ DateTime, DateTimeZone, LocalDate }

/**
 * we must get our own Time, as stopTimes can be with hour >=24 (26: tein comes at 2 in the morning.
 * Joda time does not handle such
 *
 * @param hours
 * @param minutes
 * @param
 * Created by alex on 06/05/16.
 *
 */
case class ScheduleTime(hours: Int, minutes: Int, seconds: Int) {

  def toDateTime(date: LocalDate): DateTime =
    date.toDateTimeAtStartOfDay
      .plusHours(hours)
      .plusMinutes(minutes)
      .plusSeconds(seconds)

  def getSecondOfDay = seconds + 60 * minutes + 3600 * hours

}

case class CannotParseScheduleTimeException(message: String) extends Exception(message)

object ScheduleTime {
  val timeRegex = """(\d\d):(\d\d):(\d\d)""".r

  def apply(s: String): ScheduleTime = s match {
    case timeRegex(h, m, s) => ScheduleTime(h.toInt, m.toInt, s.toInt)
    case _ => throw CannotParseScheduleTimeException(s)
  }
}


text:
<!DOCTYPE html>

        <title>GmapsTools-BETA</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">


text:
package org.apache.calcite.statistic;

import org.apache.calcite.materialize.SqlStatisticProvider;
import org.apache.calcite.plan.RelOptTable;
import org.apache.calcite.util.ImmutableIntList;
import org.apache.calcite.util.Util;

import com.google.common.cache.Cache;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.UncheckedExecutionException;

import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * Implementation of {@link SqlStatisticProvider} that reads and writes a
 * cache.
 */
public class CachingSqlStatisticProvider implements SqlStatisticProvider {
  private final SqlStatisticProvider provider;
  private final Cache<List, Object> cache;

  public CachingSqlStatisticProvider(SqlStatisticProvider provider,
      Cache<List, Object> cache) {
    super();
    this.provider = provider;
    this.cache = cache;
  }

  @Override public double tableCardinality(RelOptTable table) {
    try {
      final ImmutableList<Object> key =
          ImmutableList.of("tableCardinality",
              table.getQualifiedName());
      return (Double) cache.get(key,
          () -> provider.tableCardinality(table));
    } catch (UncheckedExecutionException | ExecutionException e) {
      throw Util.throwAsRuntime(Util.causeOrSelf(e));
    }
  }

  @Override public boolean isForeignKey(RelOptTable fromTable, List<Integer> fromColumns,
      RelOptTable toTable, List<Integer> toColumns) {
    try {
      final ImmutableList<Object> key =
          ImmutableList.of("isForeignKey",
              fromTable.getQualifiedName(),
              ImmutableIntList.copyOf(fromColumns),
              toTable.getQualifiedName(),
              ImmutableIntList.copyOf(toColumns));
      return (Boolean) cache.get(key,
          () -> provider.isForeignKey(fromTable, fromColumns, toTable,
              toColumns));
    } catch (UncheckedExecutionException | ExecutionException e) {
      throw Util.throwAsRuntime(Util.causeOrSelf(e));
    }
  }

  @Override public boolean isKey(RelOptTable table, List<Integer> columns) {
    try {
      final ImmutableList<Object> key =
          ImmutableList.of("isKey", table.getQualifiedName(),
              ImmutableIntList.copyOf(columns));
      return (Boolean) cache.get(key, () -> provider.isKey(table, columns));
    } catch (UncheckedExecutionException | ExecutionException e) {
      throw Util.throwAsRuntime(Util.causeOrSelf(e));
    }
  }
}


text:
from __future__ import absolute_import
from future.utils import PY3

if PY3:
    from pickle import *
else:
    __future_module__ = True
    try:
        from cPickle import *
    except ImportError:
        from pickle import *


text:
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

from matplotlib.externals import six
import warnings

import numpy as np

from matplotlib.testing.decorators import image_comparison, knownfailureif
import matplotlib.pyplot as plt
from nose.tools import assert_raises
from numpy.testing import assert_array_equal
from matplotlib.offsetbox import AnchoredOffsetbox, DrawingArea
from matplotlib.patches import Rectangle

def example_plot(ax, fontsize=12):
    ax.plot([1, 2])
    ax.locator_params(nbins=3)
    ax.set_xlabel('x-label', fontsize=fontsize)
    ax.set_ylabel('y-label', fontsize=fontsize)
    ax.set_title('Title', fontsize=fontsize)

@image_comparison(baseline_images=['tight_layout1'])
def test_tight_layout1():
    'Test tight_layout for a single subplot'
    fig = plt.figure()
    ax = fig.add_subplot(111)
    example_plot(ax, fontsize=24)
    plt.tight_layout()

@image_comparison(baseline_images=['tight_layout2'])
def test_tight_layout2():
    'Test tight_layout for mutiple subplots'
    fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)
    example_plot(ax1)
    example_plot(ax2)
    example_plot(ax3)
    example_plot(ax4)
    plt.tight_layout()

@image_comparison(baseline_images=['tight_layout3'])
def test_tight_layout3():
    'Test tight_layout for mutiple subplots'

    fig = plt.figure()

    ax1 = plt.subplot(221)
    ax2 = plt.subplot(223)
    ax3 = plt.subplot(122)

    example_plot(ax1)
    example_plot(ax2)
    example_plot(ax3)

    plt.tight_layout()

@image_comparison(baseline_images=['tight_layout4'],
                  freetype_version=('2.4.5', '2.4.9'))
def test_tight_layout4():
    'Test tight_layout for subplot2grid'

    fig = plt.figure()

    ax1 = plt.subplot2grid((3, 3), (0, 0))
    ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2)
    ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2)
    ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)

    example_plot(ax1)
    example_plot(ax2)
    example_plot(ax3)
    example_plot(ax4)

    plt.tight_layout()

@image_comparison(baseline_images=['tight_layout5'])
def test_tight_layout5():
    'Test tight_layout for image'

    fig = plt.figure()

    ax = plt.subplot(111)
    arr = np.arange(100).reshape((10, 10))
    ax.imshow(arr, interpolation="none")

    plt.tight_layout()

@image_comparison(baseline_images=['tight_layout6'])
def test_tight_layout6():
    'Test tight_layout for gridspec'

    # This raises warnings since tight layout cannot
    # do this fully automatically. But the test is
    # correct since the layout is manually edited
    with warnings.catch_warnings():
        warnings.simplefilter("ignore", UserWarning)
        fig = plt.figure()

        import matplotlib.gridspec as gridspec

        gs1 = gridspec.GridSpec(2, 1)
        ax1 = fig.add_subplot(gs1[0])
        ax2 = fig.add_subplot(gs1[1])

        example_plot(ax1)
        example_plot(ax2)

        gs1.tight_layout(fig, rect=[0, 0, 0.5, 1])

        gs2 = gridspec.GridSpec(3, 1)

        for ss in gs2:
            ax = fig.add_subplot(ss)
            example_plot(ax)
            ax.set_title("")
            ax.set_xlabel("")

        ax.set_xlabel("x-label", fontsize=12)

        gs2.tight_layout(fig, rect=[0.5, 0, 1, 1], h_pad=0.45)

        top = min(gs1.top, gs2.top)
        bottom = max(gs1.bottom, gs2.bottom)

        gs1.tight_layout(fig, rect=[None, 0 + (bottom-gs1.bottom),
                                    0.5, 1 - (gs1.top-top)])
        gs2.tight_layout(fig, rect=[0.5, 0 + (bottom-gs2.bottom),
                                    None, 1 - (gs2.top-top)],
                         h_pad=0.45)

@image_comparison(baseline_images=['tight_layout7'])
def test_tight_layout7():
    # tight layout with left and right titles
    fig = plt.figure()
    fontsize = 24
    ax = fig.add_subplot(111)
    ax.plot([1, 2])
    ax.locator_params(nbins=3)
    ax.set_xlabel('x-label', fontsize=fontsize)
    ax.set_ylabel('y-label', fontsize=fontsize)
    ax.set_title('Left Title', loc='left', fontsize=fontsize)
    ax.set_title('Right Title', loc='right', fontsize=fontsize)
    plt.tight_layout()

@image_comparison(baseline_images=['tight_layout8'])
def test_tight_layout8():
    'Test automatic use of tight_layout'
    fig = plt.figure()
    fig.set_tight_layout({'pad': .1})
    ax = fig.add_subplot(111)
    example_plot(ax, fontsize=24)

def add_offsetboxes(ax, size=10, margin=.1, color='black'):
    """
    Surround ax with OffsetBoxes
    """
    m, mp = margin, 1+margin
    anchor_points = [(-m, -m), (-m, .5), (-m, mp),
                     (mp, .5), (.5, mp), (mp, mp),
                     (.5, -m), (mp, -m), (.5, -m)]
    for point in anchor_points:
        da = DrawingArea(size, size)
        background = Rectangle((0, 0), width=size,
                               height=size,
                               facecolor=color,
                               edgecolor='None',
                               linewidth=0,
                               antialiased=False)
        da.add_artist(background)

        anchored_box = AnchoredOffsetbox(
            loc=10,
            child=da,
            pad=0.,
            frameon=False,
            bbox_to_anchor=point,
            bbox_transform=ax.transAxes,
            borderpad=0.)
        ax.add_artist(anchored_box)
    return anchored_box

@image_comparison(baseline_images=['tight_layout_offsetboxes1',
                                   'tight_layout_offsetboxes2'])
def test_tight_layout_offsetboxes():
    # 1.
    # - Create 4 subplots
    # - Plot a diagonal line on them
    # - Surround each plot with 7 boxes
    # - Use tight_layout
    # - See that the squares are included in the tight_layout
    #   and that the squares in the middle do not overlap
    #
    # 2.
    # - Make the squares around the right side axes invisible
    # - See that the invisible squares do not affect the
    #   tight_layout
    rows = cols = 2
    colors = ['red', 'blue', 'green', 'yellow']
    x = y = [0, 1]

    def _subplots():
        _, axs = plt.subplots(rows, cols)
        axs = axs.flat
        for ax, color in zip(axs, colors):
            ax.plot(x, y, color=color)
            add_offsetboxes(ax, 20, color=color)
        return axs

    # 1.
    axs = _subplots()
    plt.tight_layout()

    # 2.
    axs = _subplots()
    for ax in (axs[cols-1::rows]):
        for child in ax.get_children():
            if isinstance(child, AnchoredOffsetbox):
                child.set_visible(False)

    plt.tight_layout()


text:
package com.intel.icecp.node.utils;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.IOException;
import java.lang.reflect.Array;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;

import com.intel.icecp.node.management.JarUtils;

/**
 */
public class JarUtilsTest {

    private static final Logger LOGGER = LogManager.getLogger();

    @Test
    public void testGetClassByteCode() throws IOException {
        byte[] byteCode = JarUtils.getClassByteCode(JarUtilsTest.class);

        String byteCodeAsString = new String(byteCode);
        LOGGER.debug("Generated byte code: {}", byteCodeAsString);

        String classNameAsByteCode = 'L' + JarUtilsTest.class.getCanonicalName().replace('.', '/') + ';'; // see http://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.3.2
        assertTrue(new String(byteCode).contains(classNameAsByteCode));
    }

    @Test
    public void testGetClassByteCodeOfInnerClass() throws IOException {
        byte[] byteCode = JarUtils.getClassByteCode(X.class);

        String byteCodeAsString = new String(byteCode);
        LOGGER.debug("Generated byte code: {}", byteCodeAsString);

        String classNameAsByteCode = 'L' + JarUtilsTest.class.getCanonicalName().replace('.', '/') + '$' + X.class.getSimpleName(); // see http://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.3.2
        assertTrue(byteCodeAsString.contains(classNameAsByteCode));
    }

    @Test
    public void testBuildJar() throws IOException {
        byte[] bytes = JarUtils.buildJar(JarUtilsTest.class, JarUtils.class, IOException.class);

        String jarBytesAsString = new String(bytes);
        LOGGER.debug("Generated byte code: {}", jarBytesAsString);

        assertTrue(jarBytesAsString.contains(JarUtilsTest.class.getSimpleName()));
        assertTrue(jarBytesAsString.contains(JarUtils.class.getSimpleName()));
        assertTrue(jarBytesAsString.contains(IOException.class.getSimpleName()));
    }

    @Test
    public void testBuildJarClassesWithNullEntriesDoesNotThrowNullPointerException() throws IOException {
        Class<String>[] classArray = (Class<String>[]) Array.newInstance(Class.class, 10);
        Class<String> clazz = String.class;
        classArray[0] = clazz;
        JarUtils.buildJar(classArray);
        // no assert needed; if we get through this, we haven't thrown an NPE
    }

    private class X {
        // do nothing
    }
}


text:
    {{ 'Message' | translate }}

<form [formGroup]="messageForm">

        <editor formControlName="text" [init]="tinyMceSettings"></editor>

        <button
            type="submit"
            mat-button
            color="accent"
            [mat-dialog-close]="messageForm.value"
            [disabled]="!messageForm.valid"
        >
            {{ 'Save' | translate }}
        </button>

        <button type="button" mat-button [mat-dialog-close]="null">
            {{ 'Cancel' | translate }}
        </button>

</form>


text:
import java.util.Stack;

/**
 * Implement the following operations of a queue using stacks.
 *

 * push(x) -- Push element x to the back of queue.
 * pop() -- Removes the element from in front of queue.
 * peek() -- Get the front element.
 * empty() -- Return whether the queue is empty.
 *

 * Notes:
 * You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid.
 * Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
 * You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
 *

 * Created by drfish on 6/8/2017.
 */
public class _232ImplementQueueUsingStacks {
    public class MyQueue {
        private Stack<Integer> stack1;
        private Stack<Integer> stack2;

        /**
         * Initialize your data structure here.
         */
        public MyQueue() {
            stack1 = new Stack<>();
            stack2 = new Stack<>();
        }

        /**
         * Push element x to the back of queue.
         */
        public void push(int x) {
            stack1.push(x);
        }

        /**
         * Removes the element from in front of queue and returns that element.
         */
        public int pop() {
            if (stack2.isEmpty()) {
                while (!stack1.isEmpty()) {
                    stack2.push(stack1.pop());
                }
            }
            return stack2.pop();

        }

        /**
         * Get the front element.
         */
        public int peek() {
            if (stack2.isEmpty()) {
                while (!stack1.isEmpty()) {
                    stack2.push(stack1.pop());
                }
            }
            return stack2.peek();
        }

        /**
         * Returns whether the queue is empty.
         */
        public boolean empty() {
            return stack1.isEmpty() && stack2.isEmpty();
        }
    }
}


text:
namespace mojo {
namespace system {
namespace {

TEST(AwakableListTest, BasicCancel) {
  MojoResult result;
  uint32_t context;

  // Cancel immediately after thread start.
  {
    AwakableList awakable_list;
    test::SimpleWaiterThread thread(&result, &context);
    awakable_list.Add(thread.waiter(), MOJO_HANDLE_SIGNAL_READABLE, 1);
    thread.Start();
    awakable_list.CancelAll();
    // Double-remove okay:
    awakable_list.Remove(thread.waiter());
  }  // Join |thread|.
  EXPECT_EQ(MOJO_RESULT_CANCELLED, result);
  EXPECT_EQ(1u, context);

  // Cancel before after thread start.
  {
    AwakableList awakable_list;
    test::SimpleWaiterThread thread(&result, &context);
    awakable_list.Add(thread.waiter(), MOJO_HANDLE_SIGNAL_WRITABLE, 2);
    awakable_list.CancelAll();
    thread.Start();
  }  // Join |thread|.
  EXPECT_EQ(MOJO_RESULT_CANCELLED, result);
  EXPECT_EQ(2u, context);

  // Cancel some time after thread start.
  {
    AwakableList awakable_list;
    test::SimpleWaiterThread thread(&result, &context);
    awakable_list.Add(thread.waiter(), MOJO_HANDLE_SIGNAL_READABLE, 3);
    thread.Start();
    base::PlatformThread::Sleep(2 * test::EpsilonTimeout());
    awakable_list.CancelAll();
  }  // Join |thread|.
  EXPECT_EQ(MOJO_RESULT_CANCELLED, result);
  EXPECT_EQ(3u, context);
}

TEST(AwakableListTest, BasicAwakeSatisfied) {
  MojoResult result;
  uint32_t context;

  // Awake immediately after thread start.
  {
    AwakableList awakable_list;
    test::SimpleWaiterThread thread(&result, &context);
    awakable_list.Add(thread.waiter(), MOJO_HANDLE_SIGNAL_READABLE, 1);
    thread.Start();
    awakable_list.AwakeForStateChange(HandleSignalsState(
        MOJO_HANDLE_SIGNAL_READABLE,
        MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_WRITABLE));
    awakable_list.Remove(thread.waiter());
  }  // Join |thread|.
  EXPECT_EQ(MOJO_RESULT_OK, result);
  EXPECT_EQ(1u, context);

  // Awake before after thread start.
  {
    AwakableList awakable_list;
    test::SimpleWaiterThread thread(&result, &context);
    awakable_list.Add(thread.waiter(), MOJO_HANDLE_SIGNAL_WRITABLE, 2);
    awakable_list.AwakeForStateChange(HandleSignalsState(
        MOJO_HANDLE_SIGNAL_WRITABLE,
        MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_WRITABLE));
    awakable_list.Remove(thread.waiter());
    // Double-remove okay:
    awakable_list.Remove(thread.waiter());
    thread.Start();
  }  // Join |thread|.
  EXPECT_EQ(MOJO_RESULT_OK, result);
  EXPECT_EQ(2u, context);

  // Awake some time after thread start.
  {
    AwakableList awakable_list;
    test::SimpleWaiterThread thread(&result, &context);
    awakable_list.Add(thread.waiter(), MOJO_HANDLE_SIGNAL_READABLE, 3);
    thread.Start();
    base::PlatformThread::Sleep(2 * test::EpsilonTimeout());
    awakable_list.AwakeForStateChange(HandleSignalsState(
        MOJO_HANDLE_SIGNAL_READABLE,
        MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_WRITABLE));
    awakable_list.Remove(thread.waiter());
  }  // Join |thread|.
  EXPECT_EQ(MOJO_RESULT_OK, result);
  EXPECT_EQ(3u, context);
}

TEST(AwakableListTest, BasicAwakeUnsatisfiable) {
  MojoResult result;
  uint32_t context;

  // Awake (for unsatisfiability) immediately after thread start.
  {
    AwakableList awakable_list;
    test::SimpleWaiterThread thread(&result, &context);
    awakable_list.Add(thread.waiter(), MOJO_HANDLE_SIGNAL_READABLE, 1);
    thread.Start();
    awakable_list.AwakeForStateChange(HandleSignalsState(
        MOJO_HANDLE_SIGNAL_NONE, MOJO_HANDLE_SIGNAL_WRITABLE));
    awakable_list.Remove(thread.waiter());
  }  // Join |thread|.
  EXPECT_EQ(MOJO_RESULT_FAILED_PRECONDITION, result);
  EXPECT_EQ(1u, context);

  // Awake (for unsatisfiability) before after thread start.
  {
    AwakableList awakable_list;
    test::SimpleWaiterThread thread(&result, &context);
    awakable_list.Add(thread.waiter(), MOJO_HANDLE_SIGNAL_WRITABLE, 2);
    awakable_list.AwakeForStateChange(HandleSignalsState(
        MOJO_HANDLE_SIGNAL_READABLE, MOJO_HANDLE_SIGNAL_READABLE));
    awakable_list.Remove(thread.waiter());
    thread.Start();
  }  // Join |thread|.
  EXPECT_EQ(MOJO_RESULT_FAILED_PRECONDITION, result);
  EXPECT_EQ(2u, context);

  // Awake (for unsatisfiability) some time after thread start.
  {
    AwakableList awakable_list;
    test::SimpleWaiterThread thread(&result, &context);
    awakable_list.Add(thread.waiter(), MOJO_HANDLE_SIGNAL_READABLE, 3);
    thread.Start();
    base::PlatformThread::Sleep(2 * test::EpsilonTimeout());
    awakable_list.AwakeForStateChange(HandleSignalsState(
        MOJO_HANDLE_SIGNAL_NONE, MOJO_HANDLE_SIGNAL_WRITABLE));
    awakable_list.Remove(thread.waiter());
    // Double-remove okay:
    awakable_list.Remove(thread.waiter());
  }  // Join |thread|.
  EXPECT_EQ(MOJO_RESULT_FAILED_PRECONDITION, result);
  EXPECT_EQ(3u, context);
}

TEST(AwakableListTest, MultipleAwakables) {
  MojoResult result1;
  MojoResult result2;
  MojoResult result3;
  MojoResult result4;
  uint32_t context1;
  uint32_t context2;
  uint32_t context3;
  uint32_t context4;

  // Cancel two awakables.
  {
    AwakableList awakable_list;
    test::SimpleWaiterThread thread1(&result1, &context1);
    awakable_list.Add(thread1.waiter(), MOJO_HANDLE_SIGNAL_READABLE, 1);
    thread1.Start();
    test::SimpleWaiterThread thread2(&result2, &context2);
    awakable_list.Add(thread2.waiter(), MOJO_HANDLE_SIGNAL_WRITABLE, 2);
    thread2.Start();
    base::PlatformThread::Sleep(2 * test::EpsilonTimeout());
    awakable_list.CancelAll();
  }  // Join threads.
  EXPECT_EQ(MOJO_RESULT_CANCELLED, result1);
  EXPECT_EQ(1u, context1);
  EXPECT_EQ(MOJO_RESULT_CANCELLED, result2);
  EXPECT_EQ(2u, context2);

  // Awake one awakable, cancel other.
  {
    AwakableList awakable_list;
    test::SimpleWaiterThread thread1(&result1, &context1);
    awakable_list.Add(thread1.waiter(), MOJO_HANDLE_SIGNAL_READABLE, 3);
    thread1.Start();
    test::SimpleWaiterThread thread2(&result2, &context2);
    awakable_list.Add(thread2.waiter(), MOJO_HANDLE_SIGNAL_WRITABLE, 4);
    thread2.Start();
    base::PlatformThread::Sleep(2 * test::EpsilonTimeout());
    awakable_list.AwakeForStateChange(HandleSignalsState(
        MOJO_HANDLE_SIGNAL_READABLE,
        MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_WRITABLE));
    awakable_list.Remove(thread1.waiter());
    awakable_list.CancelAll();
  }  // Join threads.
  EXPECT_EQ(MOJO_RESULT_OK, result1);
  EXPECT_EQ(3u, context1);
  EXPECT_EQ(MOJO_RESULT_CANCELLED, result2);
  EXPECT_EQ(4u, context2);

  // Cancel one awakable, awake other for unsatisfiability.
  {
    AwakableList awakable_list;
    test::SimpleWaiterThread thread1(&result1, &context1);
    awakable_list.Add(thread1.waiter(), MOJO_HANDLE_SIGNAL_READABLE, 5);
    thread1.Start();
    test::SimpleWaiterThread thread2(&result2, &context2);
    awakable_list.Add(thread2.waiter(), MOJO_HANDLE_SIGNAL_WRITABLE, 6);
    thread2.Start();
    base::PlatformThread::Sleep(2 * test::EpsilonTimeout());
    awakable_list.AwakeForStateChange(HandleSignalsState(
        MOJO_HANDLE_SIGNAL_NONE, MOJO_HANDLE_SIGNAL_READABLE));
    awakable_list.Remove(thread2.waiter());
    awakable_list.CancelAll();
  }  // Join threads.
  EXPECT_EQ(MOJO_RESULT_CANCELLED, result1);
  EXPECT_EQ(5u, context1);
  EXPECT_EQ(MOJO_RESULT_FAILED_PRECONDITION, result2);
  EXPECT_EQ(6u, context2);

  // Cancel one awakable, awake other for unsatisfiability.
  {
    AwakableList awakable_list;
    test::SimpleWaiterThread thread1(&result1, &context1);
    awakable_list.Add(thread1.waiter(), MOJO_HANDLE_SIGNAL_READABLE, 7);
    thread1.Start();

    base::PlatformThread::Sleep(1 * test::EpsilonTimeout());

    // Should do nothing.
    awakable_list.AwakeForStateChange(HandleSignalsState(
        MOJO_HANDLE_SIGNAL_NONE,
        MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_WRITABLE));

    test::SimpleWaiterThread thread2(&result2, &context2);
    awakable_list.Add(thread2.waiter(), MOJO_HANDLE_SIGNAL_WRITABLE, 8);
    thread2.Start();

    base::PlatformThread::Sleep(1 * test::EpsilonTimeout());

    // Awake #1.
    awakable_list.AwakeForStateChange(HandleSignalsState(
        MOJO_HANDLE_SIGNAL_READABLE,
        MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_WRITABLE));
    awakable_list.Remove(thread1.waiter());

    base::PlatformThread::Sleep(1 * test::EpsilonTimeout());

    test::SimpleWaiterThread thread3(&result3, &context3);
    awakable_list.Add(thread3.waiter(), MOJO_HANDLE_SIGNAL_WRITABLE, 9);
    thread3.Start();

    test::SimpleWaiterThread thread4(&result4, &context4);
    awakable_list.Add(thread4.waiter(), MOJO_HANDLE_SIGNAL_READABLE, 10);
    thread4.Start();

    base::PlatformThread::Sleep(1 * test::EpsilonTimeout());

    // Awake #2 and #3 for unsatisfiability.
    awakable_list.AwakeForStateChange(HandleSignalsState(
        MOJO_HANDLE_SIGNAL_NONE, MOJO_HANDLE_SIGNAL_READABLE));
    awakable_list.Remove(thread2.waiter());
    awakable_list.Remove(thread3.waiter());

    // Cancel #4.
    awakable_list.CancelAll();
  }  // Join threads.
  EXPECT_EQ(MOJO_RESULT_OK, result1);
  EXPECT_EQ(7u, context1);
  EXPECT_EQ(MOJO_RESULT_FAILED_PRECONDITION, result2);
  EXPECT_EQ(8u, context2);
  EXPECT_EQ(MOJO_RESULT_FAILED_PRECONDITION, result3);
  EXPECT_EQ(9u, context3);
  EXPECT_EQ(MOJO_RESULT_CANCELLED, result4);
  EXPECT_EQ(10u, context4);
}

class KeepAwakable : public Awakable {
 public:
  KeepAwakable() : awake_count(0) {}

  bool Awake(MojoResult result, uintptr_t context) override {
    awake_count++;
    return true;
  }

  int awake_count;

  DISALLOW_COPY_AND_ASSIGN(KeepAwakable);
};

class RemoveAwakable : public Awakable {
 public:
  RemoveAwakable() : awake_count(0) {}

  bool Awake(MojoResult result, uintptr_t context) override {
    awake_count++;
    return false;
  }

  int awake_count;

  DISALLOW_COPY_AND_ASSIGN(RemoveAwakable);
};

TEST(AwakableListTest, KeepAwakablesReturningTrue) {
  KeepAwakable keep0;
  KeepAwakable keep1;
  RemoveAwakable remove0;
  RemoveAwakable remove1;
  RemoveAwakable remove2;

  HandleSignalsState hss(MOJO_HANDLE_SIGNAL_WRITABLE,
                         MOJO_HANDLE_SIGNAL_WRITABLE);

  AwakableList remove_all;
  remove_all.Add(&remove0, MOJO_HANDLE_SIGNAL_WRITABLE, 0);
  remove_all.Add(&remove1, MOJO_HANDLE_SIGNAL_WRITABLE, 0);

  remove_all.AwakeForStateChange(hss);
  EXPECT_EQ(remove0.awake_count, 1);
  EXPECT_EQ(remove1.awake_count, 1);

  remove_all.AwakeForStateChange(hss);
  EXPECT_EQ(remove0.awake_count, 1);
  EXPECT_EQ(remove1.awake_count, 1);

  AwakableList remove_first;
  remove_first.Add(&remove2, MOJO_HANDLE_SIGNAL_WRITABLE, 0);
  remove_first.Add(&keep0, MOJO_HANDLE_SIGNAL_WRITABLE, 0);
  remove_first.Add(&keep1, MOJO_HANDLE_SIGNAL_WRITABLE, 0);

  remove_first.AwakeForStateChange(hss);
  EXPECT_EQ(keep0.awake_count, 1);
  EXPECT_EQ(keep1.awake_count, 1);
  EXPECT_EQ(remove2.awake_count, 1);

  remove_first.AwakeForStateChange(hss);
  EXPECT_EQ(keep0.awake_count, 2);
  EXPECT_EQ(keep1.awake_count, 2);
  EXPECT_EQ(remove2.awake_count, 1);

  remove_first.Remove(&keep0);
  remove_first.Remove(&keep1);
}

}  // namespace
}  // namespace system
}  // namespace mojo


text:
+++
Title = "devopsdays Washington, D.C. 2020"
Type = "welcome"
aliases = [
  "/events/2020-washington-dc/",
  "/events/2020-washington-dc/location",
  "/events/2020-washington-dc/program",
  "/events/2020-washington-dc/propose",
  "/events/2020-washington-dc/registration",
  "/events/2020-washington-dc/speakers",
  "/events/2020-washington-dc/sponsor"
]
Description = "devopsdays Washington, D.C. 2020"
+++

DevOpsDays Washington, D.C. Coronavirus Pandemic Update: CANCELED

        Last updated: April 16, 2020

        The organizing team for DevOpsDays DC, like you, is sitting isolated at home watching the Coronavirus pandemic impact everyone.  We have decided to cancel the 2020 edition of DevOpsDays DC.

        DevOpsDays DC will not be held in 2020.

        Please stay safe and follow all necessary recommendations during this difficult time.

        We do expect there will be a DevOpsDays DC 2021.

    Dates

    {{< event_start >}} - {{< event_end >}}

    Contact

    {{< event_link page="contact" text="Get in touch with the organizers" >}}


text:
package org.assertj.core.internal.dates;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.assertj.core.error.ShouldHaveTime.shouldHaveTime;
import static org.assertj.core.test.TestData.someInfo;
import static org.assertj.core.util.FailureMessages.actualIsNull;
import static org.mockito.Mockito.verify;

import java.util.Date;

import org.assertj.core.api.AssertionInfo;
import org.assertj.core.internal.Dates;
import org.assertj.core.internal.DatesBaseTest;
import org.junit.jupiter.api.Test;

/**
 * Tests for <code>{@link Dates#assertHasTime(AssertionInfo, Date, long)}</code>.
 *
 * @author Guillaume Girou
 * @author Nicolas François
 */
class Dates_assertHasTime_Test extends DatesBaseTest {

  @Override
  protected void initActualDate() {
    actual = new Date(42);
  }

  @Test
  void should_fail_if_actual_is_null() {
    assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> dates.assertHasTime(someInfo(), null, 1))
                                                   .withMessage(actualIsNull());
  }

  @Test
  void should_pass_if_actual_has_same_time() {
    dates.assertHasTime(someInfo(), actual, 42L);
  }

  @Test
  void should_fail_if_actual_has_not_same_time() {
    AssertionInfo info = someInfo();

    Throwable error = catchThrowable(() -> dates.assertHasTime(someInfo(), actual, 24L));

    assertThat(error).isInstanceOf(AssertionError.class);
    verify(failures).failure(info, shouldHaveTime(actual, 24L));
  }
}


text:
require 'formula'

class Dict < Formula
  homepage 'http://www.dict.org/'
  url 'http://en.sourceforge.jp/frs/g_redir.php?m=jaist&f=%2Fdict%2Fdictd%2Fdictd-1.9.15%2Fdictd-1.9.15.tar.gz'
  sha1 '081ea97a4a6a936855af30d9c2a31f5733985822'

  def install
    system "./configure", "--disable-debug", "--disable-dependency-tracking",
                          "--prefix=#{prefix}",
                          "--sysconfdir=#{etc}",
                          "--mandir=#{man}"
    # install the client
    system "make install"

    # set up the conf file
    (prefix+'etc/dict.conf').write <<-EOS
#  /etc/dict.conf Written by Bob Hilliard <hilliard@debian.org>
#  1998/03/20.  Last revised Sun, 22 Nov 1998 18:10:04 -0500 This is
#  the configuration file for /usr/bin/dict.  In most cases only the
#  server keyword need be specified.

#  This default configuration will try to access a dictd server on the
#  local host, failing that, it will try the public server.  In many
#  cases this will be slow, so you should comment out the line for the
#  server that you don't want to use. To use any other server, enter
#  its IP address in place of "dict.org".

#  Refer to the dict manpage (man dict) for other options that could
#  be inserted in here.

server localhost
server dict.org
EOS
  end
end


text:
package com.intellij.execution.impl;

import com.intellij.execution.filters.*;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.ide.ui.LafManager;
import com.intellij.ide.ui.LafManagerListener;
import com.intellij.ide.ui.UISettings;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.undo.UndoUtil;
import com.intellij.openapi.components.Service;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.colors.*;
import com.intellij.openapi.editor.colors.impl.DelegateColorScheme;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.ex.util.EmptyEditorHighlighter;
import com.intellij.openapi.editor.impl.EditorFactoryImpl;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.SyntaxHighlighter;
import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.containers.ConcurrentFactoryMap;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.text.StringTokenizer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public final class ConsoleViewUtil {
  public static final Key<Boolean> EDITOR_IS_CONSOLE_HISTORY_VIEW = Key.create("EDITOR_IS_CONSOLE_HISTORY_VIEW");

  private static final Key<Boolean> REPLACE_ACTION_ENABLED = Key.create("REPLACE_ACTION_ENABLED");

  public static @NotNull EditorEx setupConsoleEditor(@Nullable Project project, boolean foldingOutlineShown, boolean lineMarkerAreaShown) {
    EditorFactory editorFactory = EditorFactory.getInstance();
    Document document = ((EditorFactoryImpl)editorFactory).createDocument(true);
    UndoUtil.disableUndoFor(document);
    EditorEx editor = (EditorEx)editorFactory.createViewer(document, project, EditorKind.CONSOLE);
    setupConsoleEditor(editor, foldingOutlineShown, lineMarkerAreaShown);
    return editor;
  }

  public static void setupConsoleEditor(final @NotNull EditorEx editor, final boolean foldingOutlineShown, final boolean lineMarkerAreaShown) {
    ApplicationManager.getApplication().runReadAction(() -> {
      EditorSettings editorSettings = editor.getSettings();
      editorSettings.setLineMarkerAreaShown(lineMarkerAreaShown);
      editorSettings.setIndentGuidesShown(false);
      editorSettings.setLineNumbersShown(false);
      editorSettings.setFoldingOutlineShown(foldingOutlineShown);
      editorSettings.setAdditionalPageAtBottom(false);
      editorSettings.setAdditionalColumnsCount(0);
      editorSettings.setAdditionalLinesCount(0);
      editorSettings.setRightMarginShown(false);
      editorSettings.setCaretRowShown(false);
      editorSettings.setShowingSpecialChars(false);
      editor.getGutterComponentEx().setPaintBackground(false);

      DelegateColorScheme scheme = updateConsoleColorScheme(editor.getColorsScheme());
      if (UISettings.getInstance().getPresentationMode()) {
        scheme.setEditorFontSize(UISettings.getInstance().getPresentationModeFontSize());
      }
      editor.setColorsScheme(scheme);
      editor.setHighlighter(new NullEditorHighlighter());
    });
  }

  public static void setupLanguageConsoleEditor(final @NotNull EditorEx editor) {
    setupConsoleEditor(editor, false, false);

    editor.getContentComponent().setFocusCycleRoot(false);
    editor.setBorder(null);

    EditorSettings editorSettings = editor.getSettings();
    editorSettings.setAdditionalLinesCount(1);
    editorSettings.setAdditionalColumnsCount(1);
  }

  private static final class NullEditorHighlighter extends EmptyEditorHighlighter {
    private static final TextAttributes NULL_ATTRIBUTES = new TextAttributes();

    NullEditorHighlighter() {
      super(NULL_ATTRIBUTES);
    }

    @Override
    public void setAttributes(TextAttributes attributes) { }

    @Override
    public void setColorScheme(@NotNull EditorColorsScheme scheme) {}
  }

  public static @NotNull DelegateColorScheme updateConsoleColorScheme(@NotNull EditorColorsScheme scheme) {
    return new DelegateColorScheme(scheme) {
      @Override
      public @NotNull Color getDefaultBackground() {
        final Color color = getColor(ConsoleViewContentType.CONSOLE_BACKGROUND_KEY);
        return color == null ? super.getDefaultBackground() : color;
      }

      @Override
      public @NotNull FontPreferences getFontPreferences() {
        return getConsoleFontPreferences();
      }

      @Override
      public int getEditorFontSize() {
        return getConsoleFontSize();
      }

      @Override
      public float getEditorFontSize2D() {
        return getConsoleFontSize2D();
      }

      @Override
      public String getEditorFontName() {
        return getConsoleFontName();
      }

      @Override
      public float getLineSpacing() {
        return getConsoleLineSpacing();
      }

      @Override
      public @NotNull Font getFont(EditorFontType key) {
        return super.getFont(EditorFontType.getConsoleType(key));
      }

      @Override
      public void setEditorFontSize(int fontSize) {
        setConsoleFontSize(fontSize);
      }

      @Override
      public void setEditorFontSize(float fontSize) {
        setConsoleFontSize(fontSize);
      }
    };
  }

  public static boolean isConsoleViewEditor(@NotNull Editor editor) {
    return editor.getEditorKind() == (EditorKind.CONSOLE);
  }

  public static boolean isReplaceActionEnabledForConsoleViewEditor(@NotNull Editor editor) {
    return editor.getUserData(REPLACE_ACTION_ENABLED) == Boolean.TRUE;
  }

  public static void enableReplaceActionForConsoleViewEditor(@NotNull Editor editor) {
    editor.putUserData(REPLACE_ACTION_ENABLED, true);
  }

  @Service(Service.Level.APP)
  private static final class ColorCache {
    static final ColorCache INSTANCE = new ColorCache();

    private ColorCache() {
      ApplicationManager.getApplication().getMessageBus().simpleConnect().subscribe(LafManagerListener.TOPIC, new LafManagerListener() {
        @Override
        public void lookAndFeelChanged(@NotNull LafManager source) {
          mergedTextAttributes.clear();
        }
      });
    }

    private final Map<Key<?>, List<TextAttributesKey>> textAttributeKeys = new ConcurrentHashMap<>();
    private final Map<Key<?>, TextAttributes> mergedTextAttributes = ConcurrentFactoryMap.createMap(contentKey-> {
        EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme();
        TextAttributes result = scheme.getAttributes(HighlighterColors.TEXT);
        for (TextAttributesKey key : textAttributeKeys.get(contentKey)) {
          TextAttributes attributes = scheme.getAttributes(key);
          if (attributes != null) {
            result = TextAttributes.merge(result, attributes);
          }
        }
        return result;
      }
    );

    private final Map<List<TextAttributesKey>, Key<?>> keys = new ConcurrentHashMap<>();

    private Key<?> getKey(List<TextAttributesKey> keyList) {
      return keys.computeIfAbsent(keyList, keys -> {
        StringBuilder keyName = new StringBuilder("ConsoleViewUtil_");
        for (TextAttributesKey key : keys) {
          keyName.append("_").append(key.getExternalName());
        }
        Key<?> newKey = new Key<>(keyName.toString());
        textAttributeKeys.put(newKey, keys);
        ConsoleViewContentType contentType = new ConsoleViewContentType(keyName.toString(), new TextAttributes()) {
          @Override
          public TextAttributes getAttributes() {
            return mergedTextAttributes.get(newKey);
          }
        };

        ConsoleViewContentType.registerNewConsoleViewType(newKey, contentType);
        return newKey;
      });
    }
  }

  public static void printWithHighlighting(@NotNull ConsoleView console, @NotNull String text, @NotNull SyntaxHighlighter highlighter) {
    printWithHighlighting(console, text, highlighter, null);
  }

  public static void printWithHighlighting(@NotNull ConsoleView console, @NotNull String text,
                                           @NotNull SyntaxHighlighter highlighter,
                                           Runnable doOnNewLine) {
    Lexer lexer = highlighter.getHighlightingLexer();
    lexer.start(text, 0, text.length(), 0);

    IElementType tokenType;
    while ((tokenType = lexer.getTokenType()) != null) {
      ConsoleViewContentType contentType = getContentTypeForToken(tokenType, highlighter);
      StringTokenizer eolTokenizer = new StringTokenizer(lexer.getTokenText(), "\n", true);
      while (eolTokenizer.hasMoreTokens()){
        String tok = eolTokenizer.nextToken();
        console.print(tok, contentType);
        if (doOnNewLine != null && "\n".equals(tok)) {
            doOnNewLine.run();
        }
      }

      lexer.advance();
    }
  }

  public static @NotNull ConsoleViewContentType getContentTypeForToken(@NotNull IElementType tokenType,
                                                                       @NotNull SyntaxHighlighter highlighter) {
    TextAttributesKey[] keys = highlighter.getTokenHighlights(tokenType);
    if (keys.length == 0) {
      return ConsoleViewContentType.NORMAL_OUTPUT;
    }
    return ConsoleViewContentType.getConsoleViewType(ColorCache.INSTANCE.getKey(List.of(keys)));
  }

  public static void printAsFileType(@NotNull ConsoleView console, @NotNull String text, @NotNull FileType fileType) {
    SyntaxHighlighter highlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(fileType, null, null);
    if (highlighter != null) {
      printWithHighlighting(console, text, highlighter);
    }
    else {
      console.print(text, ConsoleViewContentType.NORMAL_OUTPUT);
    }
  }

  public static @NotNull List<Filter> computeConsoleFilters(@NotNull Project project,
                                                            @Nullable ConsoleView consoleView,
                                                            @NotNull GlobalSearchScope searchScope) {
    List<Filter> result = new ArrayList<>();
    for (ConsoleFilterProvider eachProvider : ConsoleFilterProvider.FILTER_PROVIDERS.getExtensions()) {
      Filter[] filters;
      if (consoleView != null && eachProvider instanceof ConsoleDependentFilterProvider) {
        filters = ((ConsoleDependentFilterProvider)eachProvider).getDefaultFilters(consoleView, project, searchScope);
      }
      else if (eachProvider instanceof ConsoleFilterProviderEx) {
        filters = ((ConsoleFilterProviderEx)eachProvider).getDefaultFilters(project, searchScope);
      }
      else {
        filters = eachProvider.getDefaultFilters(project);
      }
      ContainerUtil.addAll(result, filters);
    }
    return result;
  }

  public static @NotNull InputFilter computeInputFilter(@NotNull ConsoleView consoleView,
                                                        @NotNull Project project,
                                                        @NotNull GlobalSearchScope searchScope) {
    List<ConsoleInputFilterProvider> inputFilters = ConsoleInputFilterProvider.INPUT_FILTER_PROVIDERS.getExtensionList();
    if (inputFilters.isEmpty()) {
      return (text, contentType) -> null;
    }
    List<InputFilter> allFilters = new ArrayList<>();
    for (ConsoleInputFilterProvider eachProvider : inputFilters) {
      if (eachProvider instanceof ConsoleDependentInputFilterProvider) {
        allFilters.addAll(((ConsoleDependentInputFilterProvider)eachProvider).getDefaultFilters(consoleView, project, searchScope));
      }
      else {
        allFilters.addAll(Arrays.asList(eachProvider.getDefaultFilters(project)));
      }
    }
    return new CompositeInputFilter(project, allFilters);
  }
}


text: find first intersection for a moving man in a pattern


text:
const producer = require('../kafka')
const logger = require('../logger')
const config = require('../config')

/**
 * Send a valid packet into kafka for later process
 *
 * @param {Buffer} packet the published MQTT packet
 * @param {Object} client client will be null for internal messages
 * @param {Function} done callback function
 */
module.exports = (packet, client, done) => {
  if (client == null) {
    logger.debug(packet, 'internal message')
    done()
    return
  }

  let payloads = [
    {topic: config.kafka.topic, key: client.id, messages: packet.payload}
  ]
  producer.send(payloads, (err, data) => {
    if (err) {
      logger.error({err: err}, 'an error occurred when send data to kafka')
      done()
      return
    }

    logger.info('success send data to kafka')
    done()
  })
}


text:
using System;
using SharpDX.Direct3D11;
using SharpDX.DXGI;
using Device2 = SharpDX.DXGI.Device2;
using Resource = SharpDX.Direct3D11.Resource;

namespace Grasshopper.SharpDX.Graphics.Rendering.Internal
{
    internal class WindowTextureBuffer : IDisposable
    {
        private readonly DeviceManager _deviceManager;
        private readonly IntPtr _windowHandle;

        public WindowTextureBuffer(DeviceManager deviceManager, IntPtr windowHandle, int width, int height)
        {
            _deviceManager = deviceManager;
            _windowHandle = windowHandle;
            Width = width;
            Height = height;

            SampleCount = 4;
            SampleQuality = 4;
        }

        public int Width { get; private set; }
        public int Height { get; private set; }
        public bool Initialized { get; private set; }
        public RenderTargetView RenderTargetView { get; private set; }
        public Texture2D Texture { get; private set; }
        public SwapChain SwapChain { get; private set; }

        public int SampleCount { get; set; }
        public int SampleQuality { get; set; }

        public void Initialize()
        {
            if(!_deviceManager.IsInitialized)
                throw new InvalidOperationException("Device manager is not initialized");

            if(Initialized)
                Uninitialize();

            var swapChainDescription = new SwapChainDescription1
            {
                Width = Width,
                Height = Height,
                Format = Format.B8G8R8A8_UNorm,
                Stereo = false,
                SampleDescription = new SampleDescription(SampleCount, SampleQuality),
                Usage = Usage.BackBuffer | Usage.RenderTargetOutput,
                BufferCount = 1,
                Scaling = Scaling.Stretch,
                SwapEffect = SwapEffect.Discard,
                Flags = SwapChainFlags.AllowModeSwitch
            };
            var fullScreenDescription = new SwapChainFullScreenDescription
            {
                RefreshRate = new Rational(60, 1),
                Scaling = DisplayModeScaling.Centered,
                Windowed = true
            };

            using(var dxgiDevice2 = _deviceManager.Device.QueryInterface<Device2>())
            using(var dxgiFactory2 = dxgiDevice2.Adapter.GetParent<Factory2>())
            {
                SwapChain = new SwapChain1(dxgiFactory2, _deviceManager.Device, _windowHandle, ref swapChainDescription, fullScreenDescription);
                dxgiFactory2.MakeWindowAssociation(_windowHandle, WindowAssociationFlags.IgnoreAll);
            }

            Texture = Resource.FromSwapChain<Texture2D>(SwapChain, 0);
            RenderTargetView = new RenderTargetView(_deviceManager.Device, Texture);

            Initialized = true;
        }

        public void Uninitialize()
        {
            if(Texture != null)
            {
                Texture.Dispose();
                Texture = null;
            }
            if(RenderTargetView != null)
            {
                RenderTargetView.Dispose();
                RenderTargetView = null;
            }
            if(SwapChain != null)
            {
                SwapChain.Dispose();
                SwapChain = null;
            }
            Initialized = false;
        }

        public void Resize(int width, int height)
        {
            Width = width;
            Height = height;

            if(Initialized)
                Initialize();
        }

        public void Dispose()
        {
            Uninitialize();
        }
    }
}