text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>QLDevice</title>
<meta name="date" content="2014-06-20">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.eyetechds.quicklink

Class QLDevice

java.lang.Object

com.eyetechds.quicklink.QLDevice

public class QLDevice
extends java.lang.Object

A QLDevice object contains all the methods needed for communicating with and getting gaze
 data from a device

 Creating a QLDevice object

 A QLDevice object cannot be created directly. The only way to create an object and get its
 reference is by calling enumerate(Context). Only one object is created per device. If
 enumerate(Context) is called multiple time, the same reference will be returned each
 time. To completely destroy the QLDevice objects and create a new one the method
 cleanup() must be called before enumerate(Context) is called again.

 Modifying the device settings

 Under most circumstances the device can operate well without modifying any settings. To improve
 performance or customize operation the device settings can be modified by using the method
 importSettings(QLSettings).

 Getting gaze data

 To get gaze data from the device call the method getFrame(int). In order for the device
 to send gaze data a calibration must be applied by calling
 applyCalibration(QLCalibration) and the device must be started by calling
 start()

See Also:

QLSettings,
QLCalibration

Method Summary

Methods

Modifier and Type
Method and Description

boolean
applyCalibration(QLCalibration calibration)

This method applies a calibration to a device.

boolean
calibrateEyeRadius(double distance,
                  QLFloat leftRadius,
                  QLFloat rightRadius)

This method uses the measured distance to the user in order to calculate the radius of the
 cornea for each eye.

static void
cleanup()

This method is a way to force cleanup of all connection resources of device that were
 detected by calling enumerate(Context).

static QLDevice[]
enumerate(Context AppContext)

This method is the only way of getting a reference to a QLDevice object.

static QLDevice[]
enumerate(Context AppContext,
         Handler deviceMessageHandler,
         boolean statusRebroadcast)

This method is the only way of getting a reference to a QLDevice object.

boolean
exportSettings(QLSettings settings)

This method exports the settings values that are currently being used by the device.

QLFrameData
getFrame(int waitTime)

This method gets the most recent frame from the device.

boolean
getIndicator(QLIndicatorType indicatorType,
            QLIndicatorMode indicatorMode,
            QLColor color)

This method gets the current indicator mode and color for the specified indicator type.

QLDeviceInfo
getInfo()

This method gets device specific information from the device.

QLError
getLastError()

This method gets the last error that occurred for the device.

QLDeviceStatus
getStatus()

This method gets the current status of the device.

boolean
importSettings(QLSettings settings)

This method imports settings values for the device from the specified settings object.

boolean
setIndicator(QLIndicatorType indicatorType,
            QLIndicatorMode indicatorMode,
            QLColor color)

This method sets the mode and color for the specified indicator.

boolean
start()

This method causes the device to start running.

boolean
stop()

This method causes the device to stop running.

static void
stopAll()

This method causes all devices to stop running.

java.lang.String
toString()

This method gets a string containing a concise, human-readable description of the device.

void
tryReconnect()

This method cleans up all threads and handles for the device and then tries to reconnect *
 the device if possible.

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, wait, wait, wait

Method Detail

enumerate

public static QLDevice[] enumerate(Context AppContext,
                   Handler deviceMessageHandler,
                   boolean statusRebroadcast)

This method is the only way of getting a reference to a QLDevice object. The first
 time this method is called it detects the devices that are attached to the system and creates
 a new object for each one. Subsequent calls return the same references to the previously
 created objects. To force detection and object creation again, the method cleanup()
 must be called prior to re-calling this method.

Parameters:

AppContext - The context of the application.

deviceMessageHandler - A message handler that will receive messages from the devices.

statusRebroadcast - On the first call to this method this parameter is ignored. If this is true for
            subsequent calls then the current status of the devices will be broadcast to the
            device message handler.

Returns:

An array of QLDevice objects that are attached to the system.

See Also:

QLDeviceMessage,
enumerate(Context),
android#content#Context,
android#os#Handler

enumerate

public static QLDevice[] enumerate(Context AppContext)

This method is the only way of getting a reference to a QLDevice object. The first
 time this method is called it detects the devices that are attached to the system and creates
 a new object for each one. Subsequent calls return the same references to the previously
 created objects. To force detection and object creation again, the method cleanup()
 must be called prior to re-calling this method.

Parameters:

AppContext - The context of the application.

Returns:

An array of QLDevice objects that are attached to the system.

See Also:

enumerate(Context, Handler, boolean),
android#content#Context

cleanup

public static void cleanup()

This method is a way to force cleanup of all connection resources of device that were
 detected by calling enumerate(Context). It stops all devices, cleans up all threads
 and handles to the devices, and nulls out the device references.

 This method does not force garbage collection on internal resources, but it does make them
 available for garbage collection. All external hard references to devices should be destroyed
 prior to calling this method so that the device objects can become available for garbage
 collection.

See Also:

enumerate(Context)

applyCalibration

public boolean applyCalibration(QLCalibration calibration)

This method applies a calibration to a device. A calibration must be applied to a device
 before valid gaze data can be generated by the device. Once a calibration has been applied to
 a device it will stay with the device until it is power cycled or until another calibration
 has been applied.

 For greatest accuracy a device should be calibrated for each user and for each physical setup
 of the device and display.

Parameters:

calibration - A non-empty QLCalibration object to apply. The calibration object must be
            filled either by loading from a file by using
            QLCalibration.load(java.nio.channels.FileChannel) or by performing a
            calibration sequence.

Returns:

True if the calibration was successfully applied to the device. False if an error
         occurred. Call getLastError() to get further error information.

See Also:

QLCalibration

calibrateEyeRadius

public boolean calibrateEyeRadius(double distance,
                         QLFloat leftRadius,
                         QLFloat rightRadius)

This method uses the measured distance to the user in order to calculate the radius of the
 cornea for each eye. Using the radii returned by this function as the values for the settings
 QLSettings.DEVICE_IMAGE_PROCESSING_EYE_RADIUS_LEFT and
 QLSettings.DEVICE_IMAGE_PROCESSING_EYE_RADIUS_RIGHT will result in greater accuracy
 of the distance output for each frame.

Parameters:

distance - The actual measured distance in centimeters that the user is away from the device
            at the time this method is called.

leftRadius - A QLFloat object that will receive the radius in centimeters of the cornea
            of the left eye.

rightRadius - A QLFloat object that will receive the radius in centimeters of the cornea
            of the right eye.

Returns:

True if the method succeeded. False if there was an error. Call
         getLastError() to get further error information.

See Also:

QLFloat,
QLSettings,
QLSettings.DEVICE_IMAGE_PROCESSING_EYE_RADIUS_LEFT,
QLSettings.DEVICE_IMAGE_PROCESSING_EYE_RADIUS_RIGHT

getInfo

public QLDeviceInfo getInfo()

This method gets device specific information from the device.

Returns:

If successful then a QLDeviceInfo object is returned that contains the device
         information. If there was an error then null is returned. Call
         getLastError() to get further error information.

See Also:

QLDeviceInfo

getStatus

public QLDeviceStatus getStatus()

This method gets the current status of the device.

Returns:

If successful then a QLDeviceStatus object is returned that contains the
         current device status. If there was an error then null is returned. Call
         getLastError() to get further error information.

See Also:

QLDeviceStatus

exportSettings

public boolean exportSettings(QLSettings settings)

This method exports the settings values that are currently being used by the device. The
 values are exported to the specified settings object. It will only export the values for
 setting that have been added to the settings object. To add a setting to the settings object
 use the method QLSettings.add(String settingName) or the method
 QLSettings.setValue(String name, String value).

Parameters:

settings - The settings object that will receive the exported values from the device.

Returns:

True if the method is successful. False if there was an error. Call
         getLastError() to get further error information.

See Also:

QLSettings

importSettings

public boolean importSettings(QLSettings settings)

This method imports settings values for the device from the specified settings object. This
 operation is synchronous with the device. The new settings values will take effect after the
 device has finished processing its current frame, resulting in a latency of one frame.

Parameters:

settings - The settings object that will supply the settings values that will be imported to
            the device.

Returns:

True if the method is successful. False if there was an error. Call
         getLastError() to get further error information.

See Also:

QLSettings

start

public boolean start()

This method causes the device to start running. Once running, the device will grab and
 process frames as fast as the current settings allow. Calling this method on a device that
 has already been started will not restart the device. stop() must be called
 before a device can be restarted.

 This method creates one or more threads. Do not call it from any other methods or threads
 that warn against creating threads from within them.

Returns:

True if the device was started successfully. False if there was an error. Call
         getLastError() to get further error information.

stop

public boolean stop()

This method causes the device to stop running. Before this class is unloaded, this method
 should be called for each device that has been started using start().
 Undefined behavior could result if the class is unloaded before a device is stopped.

 This method kills one or more threads. Do not call it from any other methods or threads that
 warn against destroying threads from within them.

Returns:

True if the device was stopped successfully. False if there was an error. Call
         getLastError() to get further error information.

See Also:

stopAll()

stopAll

public static void stopAll()

This method causes all devices to stop running. Before unloading the class, each device that
 has been started by calling start() must be stopped. This can be done by
 calling stop() for each device that has been started, or this method could
 be called to stop all attached devices. Undefined behavior could result if the class is
 unloaded before a device is stopped.

 Call getLastError() to get error information.

See Also:

stop()

setIndicator

public boolean setIndicator(QLIndicatorType indicatorType,
                   QLIndicatorMode indicatorMode,
                   QLColor color)

This method sets the mode and color for the specified indicator.

Parameters:

indicatorType - A QLIndicatorType object that specifies which indicator to set.

indicatorMode - A QLIndicatorMode object that specifies the indicator mode that should be
            used.

color - A QLColor object that specifies the color of the indicator.

Returns:

True if the indicator was set successfully. False if there was an error. Call
         getLastError() to get further error information.

See Also:

getIndicator(QLIndicatorType, QLIndicatorMode, QLColor),
QLIndicatorType,
QLIndicatorMode,
QLColor

getIndicator

public boolean getIndicator(QLIndicatorType indicatorType,
                   QLIndicatorMode indicatorMode,
                   QLColor color)

This method gets the current indicator mode and color for the specified indicator type.

Parameters:

indicatorType - A QLIndicatorType object that specifies which indicator to get.

indicatorMode - A QLIndicatorMode object that receives the indicator mode that is being
            used.

color - A QLColor object that receives the color of the indicator.

Returns:

True if the indicator was retrieved successfully. False if there was an error. Call
         getLastError() to get further error information.

See Also:

setIndicator(QLIndicatorType, QLIndicatorMode, QLColor),
QLIndicatorType,
QLIndicatorMode,
QLColor

getFrame

public QLFrameData getFrame(int waitTime)

This method gets the most recent frame from the device. It is a blocking method which will
 wait for a frame to become available if there is not one ready. Waiting does not use CPU
 time.

 Only the most recent frame can be retrieved from the device. To ensure that no frames are
 dropped this function needs to be called at least as fast as the frame rate of the device. A
 good way to use this method that will minimize lost frames is to use it in a loop in its own
 thread. The blocking nature of this method will ensure that the loop will only run as fast as
 the device can produce frames. If other processing in the loop does not exceed the time that
 it takes for the device to make another frame available then this function will sync the loop
 to the approximate frame rate of the device.

Parameters:

waitTime - The maximum time in milliseconds to wait for a new frame.

Returns:

A new QLFrameData object that contains the data for the most recent frame.
         Null is returned if there is an error or if the timeout elapsed. Call
         getLastError() to get further error information.

getLastError

public QLError getLastError()

This method gets the last error that occurred for the device.

Returns:

The last error that occurred.

See Also:

QLError

toString

public java.lang.String toString()

This method gets a string containing a concise, human-readable description of the device.

Overrides:

toString in class java.lang.Object

Returns:

A printable representation of this device.

tryReconnect

public void tryReconnect()

This method cleans up all threads and handles for the device and then tries to reconnect *
 the device if possible.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
// Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Subjects;
using System.Text;
using Perspex.Utilities;

namespace Perspex
{
    /// <summary>
    /// Maintains a list of prioritised bindings together with a current value.
    /// </summary>
    /// <remarks>
    /// Bindings, in the form of <see cref="IObservable{Object}"/>s are added to the object using
    /// the <see cref="Add"/> method. With the observable is passed a priority, where lower values
    /// represent higher priorites. The current <see cref="Value"/> is selected from the highest
    /// priority binding that doesn't return <see cref="PerspexProperty.UnsetValue"/>. Where there
    /// are multiple bindings registered with the same priority, the most recently added binding
    /// has a higher priority. Each time the value changes, the <see cref="Changed"/> observable is
    /// fired with the old and new values.
    /// </remarks>
    internal class PriorityValue
    {
        /// <summary>
        /// The name of the property.
        /// </summary>
        private readonly string _name;

        /// <summary>
        /// The value type.
        /// </summary>
        private readonly Type _valueType;

        /// <summary>
        /// The currently registered bindings organised by priority.
        /// </summary>
        private readonly Dictionary<int, PriorityLevel> _levels = new Dictionary<int, PriorityLevel>();

        /// <summary>
        /// The changed observable.
        /// </summary>
        private readonly Subject<Tuple<object, object>> _changed = new Subject<Tuple<object, object>>();

        /// <summary>
        /// The current value.
        /// </summary>
        private object _value;

        /// <summary>
        /// The function used to validate the value, if any.
        /// </summary>
        private readonly Func<object, object> _validate;

        /// <summary>
        /// Initializes a new instance of the <see cref="PriorityValue"/> class.
        /// </summary>
        /// <param name="name">The name of the property.</param>
        /// <param name="valueType">The value type.</param>
        /// <param name="validate">An optional validation function.</param>
        public PriorityValue(string name, Type valueType, Func<object, object> validate = null)
        {
            _name = name;
            _valueType = valueType;
            _value = PerspexProperty.UnsetValue;
            ValuePriority = int.MaxValue;
            _validate = validate;
        }

        /// <summary>
        /// Fired whenever the current <see cref="Value"/> changes.
        /// </summary>
        /// <remarks>
        /// The old and new values may be the same, this class does not check for distinct values.
        /// </remarks>
        public IObservable<Tuple<object, object>> Changed => _changed;

        /// <summary>
        /// Gets the current value.
        /// </summary>
        public object Value => _value;

        /// <summary>
        /// Gets the priority of the binding that is currently active.
        /// </summary>
        public int ValuePriority
        {
            get;
            private set;
        }

        /// <summary>
        /// Adds a new binding.
        /// </summary>
        /// <param name="binding">The binding.</param>
        /// <param name="priority">The binding priority.</param>
        /// <returns>
        /// A disposable that will remove the binding.
        /// </returns>
        public IDisposable Add(IObservable<object> binding, int priority)
        {
            return GetLevel(priority).Add(binding);
        }

        /// <summary>
        /// Sets the value for a specified priority.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="priority">The priority</param>
        public void SetValue(object value, int priority)
        {
            GetLevel(priority).DirectValue = value;
        }

        /// <summary>
        /// Gets the currently active bindings on this object.
        /// </summary>
        /// <returns>An enumerable collection of bindings.</returns>
        public IEnumerable<PriorityBindingEntry> GetBindings()
        {
            foreach (var level in _levels)
            {
                foreach (var binding in level.Value.Bindings)
                {
                    yield return binding;
                }
            }
        }

        /// <summary>
        /// Returns diagnostic string that can help the user debug the bindings in effect on
        /// this object.
        /// </summary>
        /// <returns>A diagnostic string.</returns>
        public string GetDiagnostic()
        {
            var b = new StringBuilder();
            var first = true;

            foreach (var level in _levels)
            {
                if (!first)
                {
                    b.AppendLine();
                }

                b.Append(ValuePriority == level.Key ? "*" : string.Empty);
                b.Append("Priority ");
                b.Append(level.Key);
                b.Append(": ");
                b.AppendLine(level.Value.Value?.ToString() ?? "(null)");
                b.AppendLine("--------");
                b.Append("Direct: ");
                b.AppendLine(level.Value.DirectValue?.ToString() ?? "(null)");

                foreach (var binding in level.Value.Bindings)
                {
                    b.Append(level.Value.ActiveBindingIndex == binding.Index ? "*" : string.Empty);
                    b.Append(binding.Description ?? binding.Observable.GetType().Name);
                    b.Append(": ");
                    b.AppendLine(binding.Value?.ToString() ?? "(null)");
                }

                first = false;
            }

            return b.ToString();
        }

        /// <summary>
        /// Causes a revalidation of the value.
        /// </summary>
        public void Revalidate()
        {
            if (_validate != null)
            {
                PriorityLevel level;

                if (_levels.TryGetValue(ValuePriority, out level))
                {
                    UpdateValue(level.Value, level.Priority);
                }
            }
        }

        /// <summary>
        /// Gets the <see cref="PriorityLevel"/> with the specified priority, creating it if it
        /// doesn't already exist.
        /// </summary>
        /// <param name="priority">The priority.</param>
        /// <returns>The priority level.</returns>
        private PriorityLevel GetLevel(int priority)
        {
            PriorityLevel result;

            if (!_levels.TryGetValue(priority, out result))
            {
                var mode = (LevelPrecedenceMode)(priority % 2);
                result = new PriorityLevel(priority, mode, ValueChanged);
                _levels.Add(priority, result);
            }

            return result;
        }

        /// <summary>
        /// Updates the current <see cref="Value"/> and notifies all subscibers.
        /// </summary>
        /// <param name="value">The value to set.</param>
        /// <param name="priority">The priority level that the value came from.</param>
        private void UpdateValue(object value, int priority)
        {
            if (TypeUtilities.TryCast(_valueType, value, out value))
            {
                var old = _value;

                if (_validate != null && value != PerspexProperty.UnsetValue)
                {
                    value = _validate(value);
                }

                ValuePriority = priority;
                _value = value;
                _changed.OnNext(Tuple.Create(old, _value));
            }
            else
            {
                // TODO: Log error.
            }
        }

        /// <summary>
        /// Called when the value for a priority level changes.
        /// </summary>
        /// <param name="level">The priority level of the changed entry.</param>
        private void ValueChanged(PriorityLevel level)
        {
            if (level.Priority <= ValuePriority)
            {
                if (level.Value != PerspexProperty.UnsetValue)
                {
                    UpdateValue(level.Value, level.Priority);
                }
                else
                {
                    foreach (var i in _levels.Values.OrderBy(x => x.Priority))
                    {
                        if (i.Value != PerspexProperty.UnsetValue)
                        {
                            UpdateValue(i.Value, i.Priority);
                            return;
                        }
                    }

                    UpdateValue(PerspexProperty.UnsetValue, int.MaxValue);
                }
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
Sway est un compositeur [Wayland] compatible avec [i3]. Lisez la
[FAQ]. Rejoignez le [canal IRC] (#sway sur irc.libera.chat).

## Aide en français

[abdelq] fournit du support en français sur IRC et Github, dans le fuseau
horaire UTC-4 (EST).

## Signatures de nouvelles versions

Les nouvelles versions sont signées avec [E88F5E48] et publiées
[sur GitHub][versions GitHub].

## Installation

### À partir de paquets

Sway est disponible sur beaucoup de distributions. Essayez d'installer le
paquet "sway" pour la vôtre.

Si vous êtes intéressé à maintenir Sway pour votre distribution, passez sur le
canal IRC ou envoyez un e-mail à sir@cmpwn.com (en anglais seulement) pour des
conseils.

### Compilation depuis les sources

Consultez [cette page wiki][Configuration de développement] si vous souhaitez
compiler la révision HEAD de sway et wlroots pour tester ou développer.

Installez les dépendances :

* meson \*
* [wlroots]
* wayland
* wayland-protocols \*
* pcre2
* json-c
* pango
* cairo
* gdk-pixbuf2 (optionnel : system tray)
* [scdoc] (optionnel : requis pour les pages man) \*
* git (optionnel : information de version) \*

_\* Requis uniquement pour la compilation_

Exécutez ces commandes :

    meson build
    ninja -C build
    sudo ninja -C build install

Sur les systèmes sans logind, vous devez suid le binaire de sway :

    sudo chmod a+s /usr/local/bin/sway

Sway se débarassera des permissions *root* peu de temps après le démarrage.

## Configuration

Si vous utilisez déjà i3, copiez votre configuration i3 vers
`~/.config/sway/config` et sway fonctionnera directement. Sinon, copiez
l'exemple de fichier de configuration vers `~/.config/sway/config`. Il se
trouve généralement dans `/etc/sway/config`. Exécutez `man 5 sway` pour lire la
documentation pour la configuration de sway.

## Exécution

Exécutez `sway` à partir d'un TTY. Certains gestionnaires d'affichage peuvent
fonctionner, mais ne sont pas supportés par Sway (gdm est réputé pour assez
bien fonctionner).

[Wayland]: http://wayland.freedesktop.org/
[i3]: https://i3wm.org/
[FAQ]: https://github.com/swaywm/sway/wiki
[canal IRC]: https://web.libera.chat/gamja/?channels=#sway
[abdelq]: https://github.com/abdelq
[E88F5E48]: https://keys.openpgp.org/search?q=34FF9526CFEF0E97A340E2E40FDE7BE0E88F5E48
[versions GitHub]: https://github.com/swaywm/sway/releases
[Configuration de développement]: https://github.com/swaywm/sway/wiki/Development-Setup
[wlroots]: https://gitlab.freedesktop.org/wlroots/wlroots
[scdoc]: https://git.sr.ht/~sircmpwn/scdoc


text:
""" Tools for reading/writing BIDS data files. """

import warnings
import json

import numpy as np
import pandas as pd

from bids.utils import listify
from .entities import NodeIndex
from .variables import SparseRunVariable, DenseRunVariable, SimpleVariable

BASE_ENTITIES = ['subject', 'session', 'task', 'run']
ALL_ENTITIES = BASE_ENTITIES + ['datatype', 'suffix', 'acquisition']

def load_variables(layout, types=None, levels=None, skip_empty=True,
                   dataset=None, scope='all', **kwargs):
    """A convenience wrapper for one or more load_*_variables() calls.

    Parameters
    ----------
    layout : :obj:`bids.layout.BIDSLayout`
        BIDSLayout containing variable files.
    types : str or list
        Types of variables to retrieve. All valid values
        reflect the filename stipulated in the BIDS spec for each kind of
        variable. Valid values include: 'events', 'physio', 'stim',
        'scans', 'participants', 'sessions', and 'regressors'.
    levels : str or list
        Optional level(s) of variables to load. Valid
        values are 'run', 'session', 'subject', or 'dataset'. This is
        simply a shorthand way to specify types--e.g., 'run' will be
        converted to types=['events', 'physio', 'stim', 'regressors'].
    skip_empty : bool
        Whether or not to skip empty Variables (i.e.,
        where there are no rows/records in a file after applying any
        filtering operations like dropping NaNs).
    dataset : NodeIndex
        An existing NodeIndex container to store the
        loaded data in. Can be used to iteratively construct a dataset
        that contains otherwise heterogeneous sets of variables. If None,
        a new NodeIndex is used.
    scope : str or list
        The scope of the space to search for variables. See
        docstring for BIDSLayout for details and valid predefined values.
    kwargs : dict
        Optional keyword arguments to pass onto the individual
        load_*_variables() calls.

    Returns
    -------
    A NodeIndex instance.

    Examples
    --------
    >>> load_variables(layout, ['events', 'physio'], subject='01')  # doctest: +SKIP
    # returns all variables stored in _events.tsv and _physio.tsv.gz files
    # for runs that belong to subject with id '01'.
    """

    TYPES = ['events', 'physio', 'stim', 'scans', 'participants', 'sessions',
             'regressors']

    types = listify(types)

    if types is None:
        if levels is not None:
            types = []
            lev_map = {
                'run': ['events', 'physio', 'stim', 'regressors'],
                'session': ['scans'],
                'subject': ['sessions'],
                'dataset': ['participants']
            }
            [types.extend(lev_map[l.lower()]) for l in listify(levels)]
        else:
            types = TYPES

    bad_types = set(types) - set(TYPES)
    if bad_types:
        raise ValueError("Invalid variable types: %s" % bad_types)

    dataset = dataset or NodeIndex()

    run_types = list({'events', 'physio', 'stim', 'regressors'} - set(types))
    type_flags = {t: False for t in run_types}
    if len(type_flags) < 4:
        _kwargs = kwargs.copy()
        _kwargs.update(type_flags)
        dataset = _load_time_variables(layout, dataset, scope=scope, **_kwargs)

    for t in ({'scans', 'sessions', 'participants'} & set(types)):
        kwargs.pop('suffix', None) # suffix is always one of values above
        dataset = _load_tsv_variables(layout, t, dataset, scope=scope,
                                      **kwargs)

    return dataset

def _get_nvols(img_f):
    import nibabel as nb
    img = nb.load(img_f)
    nvols = 0
    if isinstance(img, nb.Nifti1Pair):
        nvols = img.shape[3]
    elif isinstance(img, nb.Cifti2Image):
        for ax in map(img.header.get_axis, range(len(img.header.matrix))):
            if isinstance(ax, nb.cifti2.SeriesAxis):
                nvols = ax.size
                break
        else:
            raise ValueError("No series axis found in %s" % img_f)
    elif isinstance(img, nb.GiftiImage):
        nvols = len(img.get_arrays_from_intent('time series'))
    else:
        raise ValueError("Unknown image type %s: %s" % img.__class__, img_f)

    return nvols

def _load_time_variables(layout, dataset=None, columns=None, scan_length=None,
                         drop_na=True, events=True, physio=True, stim=True,
                         regressors=True, skip_empty=True, scope='all',
                         **selectors):
    """Loads all variables found in *_events.tsv files and returns them as a
    BIDSVariableCollection.

    Parameters
    ----------
    layout : :obj:`bids.layout.BIDSLayout`
        A BIDSLayout to scan.
    dataset : NodeIndex
        A BIDS NodeIndex container. If None, a new one is
        initialized.
    columns : list
        Optional list of names specifying which columns in the
        event files to read. By default, reads all columns found.
    scan_length : float
        Optional duration of runs (in seconds). By
        default, this will be extracted from the BOLD image. However, in
        cases where the user doesn't have access to the images (e.g.,
        because only file handles are locally available), a fixed duration
        can be manually specified as a fallback.
    drop_na : bool
        If True, removes all events where amplitude is n/a. If
        False, leaves n/a values intact. Note that in the latter case,
        transformations that requires numeric values may fail.
    events : bool
        If True, extracts variables from events.tsv files.
    physio : bool
        If True, extracts variables from _physio files.
    stim : bool
        If True, extracts variables from _stim files.
    skip_empty : bool
        Whether or not to skip empty Variables (i.e.,
        where there are no rows/records in a file, or all onsets,
        durations, and amplitudes are 0).
    scope : str or list
        The scope of the space to search for variables. See
        docstring for BIDSLayout for details and valid predefined values.
    selectors : dict
        Optional keyword arguments passed on to the
        BIDSLayout instance's get() method; can be used to constrain
        which data are loaded.

    Returns
    -------
    A NodeIndex instance.
    """

    # Extract any non-keyword arguments
    selectors = selectors.copy()

    if dataset is None:
        dataset = NodeIndex()

    selectors['datatype'] = 'func'
    selectors['suffix'] = 'bold'
    exts = selectors.pop('extension', ['.nii', '.nii.gz', '.func.gii', '.dtseries.nii'])
    images = layout.get(return_type='object', scope=scope, extension=exts, **selectors)

    if not images:
        raise ValueError("No functional images that match criteria found.")

    # Main loop over images
    for img_obj in images:

        entities = img_obj.entities
        img_f = img_obj.path

        # Run is not mandatory, but we need a default for proper indexing
        if 'run' in entities:
            entities['run'] = int(entities['run'])

        tr = img_obj.get_metadata()["RepetitionTime"]

        # Get duration of run: first try to get it directly from the image
        # header; if that fails, look for a scan_length argument.
        try:
            nvols = _get_nvols(img_f)
            duration = nvols * tr
        except Exception as e:
            if scan_length is not None:
                duration = scan_length
                nvols = int(np.rint(scan_length / tr))
            else:
                msg = ("Unable to extract scan duration from one or more "
                       "BOLD runs, and no scan_length argument was provided "
                       "as a fallback. Please check that the image files are "
                       "available, or manually specify the scan duration.")
                raise ValueError(msg) from e

        # We don't want to pass all the image file's entities onto get_node(),
        # as there can be unhashable nested slice timing values, and this also
        # slows down querying unnecessarily. Instead, pick out files only based
        # on the core BIDS entities and any entities explicitly passed as
        # selectors.
        # TODO: one downside of this approach is the stripped entities also
        # won't be returned in the resulting node due to the way things are
        # implemented. Consider adding a flag to control this.
        select_on = {k: v for (k, v) in entities.items()
                     if k in BASE_ENTITIES or k in selectors}

        # If a matching node already exists, return it
        result = dataset.get_nodes('run', select_on)

        if result:
            if len(result) > 1:
                raise ValueError("More than one existing Node matches the "
                                 "specified entities! You may need to pass "
                                 "additional selectors to narrow the search.")
            run_info = result[0].get_info()

        else:
            # Otherwise create a new node and use that.
            # We first convert any entity values that are currently collections to
            # JSON strings to prevent nasty hashing problems downstream. Note that
            # isinstance() isn't as foolproof as actually trying to hash the
            # value, but the latter is likely to be slower, and since values are
            # coming from JSON or filenames, there's no real chance of encountering
            # anything but a list or dict.
            entities = {
                k: (json.dumps(v) if isinstance(v, (list, dict)) else v)
                for (k, v) in entities.items()
            }

            run = dataset.create_node('run', entities, image_file=img_f,
                                      duration=duration, repetition_time=tr,
                                      n_vols=nvols)
            run_info = run.get_info()

        # Process event files
        if events:
            dfs = layout.get_nearest(
                img_f, extension='.tsv', suffix='events', all_=True,
                full_search=True, ignore_strict_entities=['suffix', 'extension'])
            for _data in dfs:
                _data = pd.read_csv(_data, sep='\t')
                if 'amplitude' in _data.columns:
                    if (_data['amplitude'].astype(int) == 1).all() and \
                            'trial_type' in _data.columns:
                        msg = ("Column 'amplitude' with constant value 1 "
                               "is unnecessary in event files; ignoring it.")
                        _data = _data.drop('amplitude', axis=1)
                    else:
                        msg = ("Column name 'amplitude' is reserved; "
                               "renaming it to 'amplitude_'.")
                        _data = _data.rename(
                            columns={'amplitude': 'amplitude_'})
                    warnings.warn(msg)

                _data = _data.replace('n/a', np.nan)  # Replace BIDS' n/a
                _data = _data.apply(pd.to_numeric, errors='ignore')

                _cols = columns or list(set(_data.columns.tolist()) -
                                        {'onset', 'duration'})

                # Construct a DataFrame for each extra column
                for col in _cols:
                    df = _data[['onset', 'duration']].copy()
                    df['amplitude'] = _data[col].values

                    # Add in all of the run's entities as new columns for
                    # index
                    for entity, value in entities.items():
                        if entity in ALL_ENTITIES:
                            df[entity] = value

                    if drop_na:
                        df = df.dropna(subset=['amplitude'])

                    if df.empty:
                        continue

                    var = SparseRunVariable(
                        name=col, data=df, run_info=run_info, source='events')
                    run.add_variable(var)

        # Process confound files
        if regressors:
            sub_ents = {k: v for k, v in entities.items()
                        if k in BASE_ENTITIES}
            confound_files = layout.get(suffix=['regressors', 'timeseries'],
                                        scope=scope, extension='.tsv',
                                        **sub_ents)
            for cf in confound_files:
                _data = pd.read_csv(cf.path, sep='\t', na_values='n/a')
                if columns is not None:
                    conf_cols = list(set(_data.columns) & set(columns))
                    _data = _data.loc[:, conf_cols]
                for col in _data.columns:
                    sr = 1. / run.repetition_time
                    var = DenseRunVariable(name=col, values=_data[[col]],
                                           run_info=run_info, source='regressors',
                                           sampling_rate=sr)
                    run.add_variable(var)

        # Process recordinging files
        rec_types = []
        if physio:
            rec_types.append('physio')
        if stim:
            rec_types.append('stim')

        if rec_types:
            rec_files = layout.get_nearest(
                img_f, extension='.tsv.gz', all_=True, suffix=rec_types,
                ignore_strict_entities=['suffix', 'extension'], full_search=True)
            for rf in rec_files:
                metadata = layout.get_metadata(rf)
                if not metadata:
                    raise ValueError("No .json sidecar found for '%s'." % rf)
                data = pd.read_csv(rf, sep='\t')
                freq = metadata['SamplingFrequency']
                st = metadata['StartTime']
                rf_cols = metadata['Columns']
                data.columns = rf_cols

                # Filter columns if user passed names
                if columns is not None:
                    rf_cols = list(set(rf_cols) & set(columns))
                    data = data.loc[:, rf_cols]

                n_cols = len(rf_cols)
                if not n_cols:
                    continue

                # Keep only in-scan samples
                if st < 0:
                    start_ind = np.floor(-st * freq)
                    values = data.values[start_ind:, :]
                else:
                    values = data.values

                if st > 0:
                    n_pad = int(freq * st)
                    pad = np.zeros((n_pad, n_cols))
                    values = np.r_[pad, values]

                n_rows = int(run.duration * freq)
                if len(values) > n_rows:
                    values = values[:n_rows, :]
                elif len(values) < n_rows:
                    pad = np.zeros((n_rows - len(values), n_cols))
                    values = np.r_[values, pad]

                df = pd.DataFrame(values, columns=rf_cols)
                source = 'physio' if '_physio.tsv' in rf else 'stim'
                for col in df.columns:
                    var = DenseRunVariable(name=col, values=df[[col]], run_info=run_info,
                                           source=source, sampling_rate=freq)
                    run.add_variable(var)
    return dataset

def _load_tsv_variables(layout, suffix, dataset=None, columns=None,
                        prepend_type=False, scope='all', **selectors):
    """Reads variables from scans.tsv, sessions.tsv, and participants.tsv.

    Parameters
    ----------
    layout : :obj:`bids.layout.BIDSLayout`
        The BIDSLayout to use.
    suffix : str
        The suffix of file to read from. Must be one of 'scans',
        'sessions', or 'participants'.
    dataset : NodeIndex
        A BIDS NodeIndex container. If None, a new one is
        initialized.
    columns : list
        Optional list of names specifying which columns in the
        files to return. If None, all columns are returned.
    prepend_type : bool
        If True, variable names are prepended with the
        type name (e.g., 'age' becomes 'participants.age').
    scope : str or list
        The scope of the space to search for variables. See
        docstring for BIDSLayout for details and valid predefined values.
    selectors : dict
        Optional keyword arguments passed onto the
        BIDSLayout instance's get() method; can be used to constrain
        which data are loaded.

    Returns
    -------
    A NodeIndex instance.
    """

    # Sanitize the selectors: only keep entities at current level or above
    valid_entities_map = {
        'scans': ['subject', 'session'],
        'sessions': ['subject'],
        'participants': []
    }
    valid_entities = valid_entities_map[suffix]
    layout_kwargs = {k: v for k, v in selectors.items() if k in valid_entities}

    if dataset is None:
        dataset = NodeIndex()

    files = layout.get(extension='.tsv', suffix=suffix, scope=scope,
                       **layout_kwargs)

    for f in files:

        _data = f.get_df(include_timing=False)

        # Entities can be defined either within the first column of the .tsv
        # file (for entities that vary by row), or from the full file path
        # (for entities constant over all rows in the file). We extract both
        # and store them in the main DataFrame alongside other variables (as
        # they'll be extracted when the BIDSVariable is initialized anyway).
        for ent_name, ent_val in f.entities.items():
            if ent_name in ALL_ENTITIES:
                _data[ent_name] = ent_val

        # Handling is a bit more convoluted for scans.tsv, because the first
        # column contains the run filename, which we also need to parse.
        if suffix == 'scans':

            # Suffix is guaranteed to be present in each filename, so drop the
            # constant column with value 'scans' to make way for it and prevent
            # two 'suffix' columns.
            _data.drop(columns=['suffix'], inplace=True)

            image = _data['filename']
            _data = _data.drop('filename', axis=1)
            dn = f._dirname
            paths = [str(dn / p) for p in image.values]
            ent_recs = [dict(layout.files[p].entities) for p in paths
                        if p in layout.files]
            ent_cols = pd.DataFrame.from_records(ent_recs)

            # Remove entity columns found in both DFs
            dupes = list(set(ent_cols.columns) & set(_data.columns))
            to_drop = ['extension'] + dupes
            ent_cols.drop(columns=to_drop, inplace=True)

            _data = pd.concat([_data, ent_cols], axis=1, sort=True)

        # The BIDS spec requires ID columns to be named 'session_id', 'run_id',
        # etc., and IDs begin with entity prefixes (e.g., 'sub-01'). To ensure
        # consistent internal handling, we strip these suffixes and prefixes.
        elif suffix == 'sessions':
            _data = _data.rename(columns={'session_id': 'session'})
            _data['session'] = _data['session'].str.replace('ses-', '')
        elif suffix == 'participants':
            _data = _data.rename(columns={'participant_id': 'subject'})
            _data['subject'] = _data['subject'].str.replace('sub-', '')

        def make_patt(x, regex_search=False):
            patt = '%s' % x
            if isinstance(x, (int, float)):
                # allow for leading zeros if a number was specified
                # regardless of regex_search
                patt = '0*' + patt
            if not regex_search:
                patt = '^%s$' % patt
            return patt

        # Filter rows on all selectors
        comm_cols = list(set(_data.columns) & set(selectors.keys()))
        for col in comm_cols:
            ent_patts = [make_patt(x, regex_search=layout.regex_search)
                            for x in listify(selectors.get(col))]
            patt = '|'.join(ent_patts)

            _data = _data[_data[col].str.contains(patt)]

        level = {'scans': 'session', 'sessions': 'subject',
                 'participants': 'dataset'}[suffix]

        node = dataset.get_or_create_node(level, f.entities)

        ent_cols = list(set(ALL_ENTITIES) & set(_data.columns))
        amp_cols = list(set(_data.columns) - set(ent_cols))

        if columns is not None:
            amp_cols = list(set(amp_cols) & set(columns))

        for col_name in amp_cols:

            # Rename columns: values must be in 'amplitude'
            df = _data.loc[:, [col_name] + ent_cols]
            df.columns = ['amplitude'] + ent_cols

            if prepend_type:
                col_name = '%s.%s' % (suffix, col_name)

            node.add_variable(SimpleVariable(name=col_name, data=df, source=suffix))

    return dataset


text:
package pds

import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.FunSuite
import org.scalatest.BeforeAndAfter
import org.scalatest.BeforeAndAfterAll
import akka.actor._
import akka.testkit._
import com.typesafe.config._
import LogicLevel._

@RunWith(classOf[JUnitRunner])
class SimulatorTest(_system: ActorSystem) extends TestKit(_system) with ImplicitSender with FunSuite with BeforeAndAfter with BeforeAndAfterAll {

	def this() = this(ActorSystem("TestSystem", ConfigFactory.parseString(
		"""akka.loglevel = WARNING
			akka.stdout-loglevel = INFO
			akka.actor.default-dispatcher.throughput = 1
			akka.actor.debug.receive = on
			akka.actor.debug.lifecycle = off
			akka.actor.debug.event-stream = on
			""")))

	var cl: ActorRef = _
	var testCount = 0

	before {
		testCount += 1
		cl = system.actorOf(Clock.props, "clock_" + testCount)
	}

	override def afterAll {
		system.shutdown()
	}

	private def ticktock(time: Int): Unit = {
		expectMsg(Tick(time))
		cl ! Tock(time)
	}

	private def start: Unit = {
		cl ! Start(1)
		expectMsg(Start)
	}

	test("start clock without an Agenda immediately stops") {
		cl ! Register
		start
		ticktock(0)
		expectMsg(StoppedAt(1))
	}

	test("send tick to simulant with no currentItems, simulant returns tock") {
		val w = system.actorOf(Wire.props("a", High, cl), "w1")
		w ! Tick(0)
		expectMsg(Tock(0))
	}

	test("start clock with Agenda, end processing when no AgendaItems are left") {
		cl ! Register
		cl ! AddWorkItem(WorkItem(1, TestMsg, self))
		start
		ticktock(0)
		expectMsg((TestMsg, 1))
		ticktock(1)
		expectMsg(StoppedAt(2))
	}

	test("add work items with a longer delay") {
		cl ! Register
		cl ! AddWorkItem(WorkItem(3, TestMsg, self))
		start

		for (i <- 0 to 2) ticktock(i)

		expectMsg((TestMsg, 3))

		ticktock(3)

		expectMsg(StoppedAt(4))
	}

	test("initial logic level is propagated when simulation is started") {
		val w = system.actorOf(Wire.props("a", High, cl))
		w ! AddObserver(testActor)
		cl ! Start(1)
		expectMsg((SignalChanged(w, High), 1))
		expectMsg(StoppedAt(2))
	}

	test("registration of components is possible after the start message has been sent") {
		cl ! Start(1)

		cl ! Register

		expectMsg(Start)

		ticktock(0)
		expectMsg(StoppedAt(1))
	}

	test("introduce a new signalchanged in the simulation") {
		val w = system.actorOf(Wire.props("a", High, cl), "w2")
		w ! AddObserver(testActor)
		cl ! Start(2)
		cl ! Register
		expectMsg(Start)
		ticktock(0)
		expectMsg((SignalChanged(w, High), 1))

		cl ! AddWorkItem(WorkItem(3, SetSignal(Low), w))

		for (i <- 1 to 4) ticktock(i)

		expectMsg((SignalChanged(w, Low), 5))

		ticktock(5)
		expectMsg(StoppedAt(6))
	}

	test("AND gate propagates signal") {
		val in1 = system.actorOf(Wire.props("in1", Low, cl), "in1")
		val in2 = system.actorOf(Wire.props("in1", High, cl), "in2")
		val out = system.actorOf(Wire.props("out", X, cl), "out")
		out ! AddObserver(testActor)
		val andgate = system.actorOf(AndGate.props("and", in1, in2, out, cl))
		cl ! Start(4)
		expectMsg((SignalChanged(out, X), 1))
		expectMsg((SignalChanged(out, Low), 5))
		expectMsg(StoppedAt(6))
	}
}

case object TestMsg


text:
using namespace igloo;

Context(BooleanOperators)
{
  Spec(ShouldHandleIsFalseOperator)
  {
    Assert::That(false, IsFalse());
  }

  Spec(ShouldHandleWhenIsFalseFails)
  {
    AssertTestFails(Assert::That(true, IsFalse()), "Expected: false");
  }

  Spec(ShouldHandleIsTrueOperator)
  {
    Assert::That(true, IsTrue());
  }

  Spec(ShouldHandleWhenIsTrueFails)
  {
    AssertTestFails(Assert::That(false, IsTrue()), "Expected: true");
  }

  Spec(ShouldHandleFluentIsTrue)
  {
    Assert::That(true, Is().True());
    AssertTestFails(Assert::That(false, Is().True()), "Expected: true");
  }

  Spec(ShouldHandleFluentIsFalse)
  {
    Assert::That(false, Is().False());
    AssertTestFails(Assert::That(true, Is().False()), "Expected: false");
  }

  Spec(ShouldTreatAssertWithoutConstraintAsBooleanConstrains)
  {
    Assert::That(true);
  }
};


text:
require 'csv'
require_relative 'player_yearly_statistics'

class BaseballStatsProvider

  def self.stats
    if (defined?(@@stats)).nil?
      @@stats = []
      batting_array = CSV.read(File.new(__dir__+'/Batting-07-12.csv'))
      batting_array.shift

      names = player_name_hash

      batting_array.each {|row| @@stats.push PlayerYearlyStatistics.new(*row,names[row[0]])}
    end
    return @@stats
  end

private
    def self.player_name_hash
      name_array = CSV.read(File.new(__dir__+'/Master-small.csv'))
      name_array.shift
      Hash[name_array.map { |row| [row[0], "#{row[2]} #{row[3]}"] }]
    end
end


text:
package lejos.mf.common;

import lejos.mf.common.exception.UnitMessageException;

import java.util.Arrays;
import java.util.List;

public class UnitMessageBuilder {
    public static UnitMessage build(byte[] rawUnitMessage) throws UnitMessageException {
        if (rawUnitMessage == null) {
            return null;
        }
        final List<byte[]> unitMessageBytesList = Utils.split(UnitMessage.UNIT_MESSAGE_SEPARATOR, rawUnitMessage, 2);

        if (unitMessageBytesList.size() != 2) {
            throw new UnitMessageException(
                    "Size of decoded UnitMessage is not correct: " + unitMessageBytesList.size());
        }

        try {
            UnitMessageType unitMessageType = UnitMessageType.valueOf(new String(unitMessageBytesList.get(0)));
            return new UnitMessage(unitMessageType, unitMessageBytesList.get(1));
        } catch (IllegalArgumentException e) {
            throw new UnitMessageException(
                    "Bad type decoded in UnitMessage: " + Arrays.toString(unitMessageBytesList.get(0)));
        }
    }
}


text: declare var __moduleName;


text:
"""Create site to site vpn connection"""
from baseCmd import *
from baseResponse import *

class createVpnConnectionCmd (baseCmd):
    typeInfo = {}

    def __init__(self):
        self.isAsync = "true"
        """id of the customer gateway"""
        """Required"""
        self.s2scustomergatewayid = None
        self.typeInfo['s2scustomergatewayid'] = 'uuid'
        """id of the vpn gateway"""
        """Required"""
        self.s2svpngatewayid = None
        self.typeInfo['s2svpngatewayid'] = 'uuid'
        """an optional field, whether to the display the vpn to the end user or not"""
        self.fordisplay = None
        self.typeInfo['fordisplay'] = 'boolean'
        """connection is passive or not"""
        self.passive = None
        self.typeInfo['passive'] = 'boolean'
        self.required = ["s2scustomergatewayid", "s2svpngatewayid", ]

class createVpnConnectionResponse (baseResponse):
    typeInfo = {}

    def __init__(self):
        """the connection ID"""
        self.id = None
        self.typeInfo['id'] = 'string'
        """the owner"""
        self.account = None
        self.typeInfo['account'] = 'string'
        """guest cidr list of the customer gateway"""
        self.cidrlist = None
        self.typeInfo['cidrlist'] = 'string'
        """the date and time the host was created"""
        self.created = None
        self.typeInfo['created'] = 'date'
        """the domain name of the owner"""
        self.domain = None
        self.typeInfo['domain'] = 'string'
        """the domain id of the owner"""
        self.domainid = None
        self.typeInfo['domainid'] = 'string'
        """if DPD is enabled for customer gateway"""
        self.dpd = None
        self.typeInfo['dpd'] = 'boolean'
        """Lifetime of ESP SA of customer gateway"""
        self.esplifetime = None
        self.typeInfo['esplifetime'] = 'long'
        """ESP policy of the customer gateway"""
        self.esppolicy = None
        self.typeInfo['esppolicy'] = 'string'
        """if Force NAT Encapsulation is enabled for customer gateway"""
        self.forceencap = None
        self.typeInfo['forceencap'] = 'boolean'
        """is connection for display to the regular user"""
        self.fordisplay = None
        self.typeInfo['fordisplay'] = 'boolean'
        """public ip address id of the customer gateway"""
        self.gateway = None
        self.typeInfo['gateway'] = 'string'
        """Lifetime of IKE SA of customer gateway"""
        self.ikelifetime = None
        self.typeInfo['ikelifetime'] = 'long'
        """IKE policy of the customer gateway"""
        self.ikepolicy = None
        self.typeInfo['ikepolicy'] = 'string'
        """IPsec Preshared-Key of the customer gateway"""
        self.ipsecpsk = None
        self.typeInfo['ipsecpsk'] = 'string'
        """State of vpn connection"""
        self.passive = None
        self.typeInfo['passive'] = 'boolean'
        """the project name"""
        self.project = None
        self.typeInfo['project'] = 'string'
        """the project id"""
        self.projectid = None
        self.typeInfo['projectid'] = 'string'
        """the public IP address"""
        self.publicip = None
        self.typeInfo['publicip'] = 'string'
        """the date and time the host was removed"""
        self.removed = None
        self.typeInfo['removed'] = 'date'
        """the customer gateway ID"""
        self.s2scustomergatewayid = None
        self.typeInfo['s2scustomergatewayid'] = 'string'
        """the vpn gateway ID"""
        self.s2svpngatewayid = None
        self.typeInfo['s2svpngatewayid'] = 'string'
        """State of vpn connection"""
        self.state = None
        self.typeInfo['state'] = 'string'


text:
@interface RKWaterFlowViewCell : UIView
@property(nonatomic,copy) NSString *identifier;
@end


text:
package org.openqa.selenium.firefox;

import java.io.IOException;
import java.net.URL;

public class NotConnectedException extends IOException {
  public NotConnectedException(URL url, long timeToWaitInMilliSeconds, String consoleOutput) {
    super(getMessage(url, timeToWaitInMilliSeconds, consoleOutput));
  }

  private static String getMessage(URL url, long timeToWaitInMilliSeconds, String consoleOutput) {
    return String.format("Unable to connect to host %s on port %d after %d ms. Firefox console output:\n%s",
        url.getHost(), url.getPort(), timeToWaitInMilliSeconds, consoleOutput);
  }
}


text:
/*
 * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file
 * at the root of this project for more details.
 */
package io.github.nucleuspowered.nucleus.modules.kit.commands.kit;

import io.github.nucleuspowered.nucleus.Nucleus;
import io.github.nucleuspowered.nucleus.Util;
import io.github.nucleuspowered.nucleus.api.nucleusdata.Kit;
import io.github.nucleuspowered.nucleus.internal.annotations.Since;
import io.github.nucleuspowered.nucleus.internal.annotations.command.NoModifiers;
import io.github.nucleuspowered.nucleus.internal.annotations.command.Permissions;
import io.github.nucleuspowered.nucleus.internal.annotations.command.RegisterCommand;
import io.github.nucleuspowered.nucleus.internal.command.ReturnMessageException;
import io.github.nucleuspowered.nucleus.internal.interfaces.Reloadable;
import io.github.nucleuspowered.nucleus.internal.permissions.SuggestedLevel;
import io.github.nucleuspowered.nucleus.modules.kit.commands.KitFallbackBase;
import io.github.nucleuspowered.nucleus.modules.kit.config.KitConfigAdapter;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.args.CommandElement;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.item.ItemTypes;
import org.spongepowered.api.item.inventory.Inventory;
import org.spongepowered.api.item.inventory.ItemStack;
import org.spongepowered.api.item.inventory.ItemStackSnapshot;
import org.spongepowered.api.item.inventory.property.InventoryTitle;
import org.spongepowered.api.util.annotation.NonnullByDefault;

import java.util.List;
import java.util.stream.Collectors;

@Permissions(prefix = "kit", suggestedLevel = SuggestedLevel.ADMIN)
@RegisterCommand(value = {"view"}, subcommandOf = KitCommand.class)
@NoModifiers
@NonnullByDefault
@Since(spongeApiVersion = "7.0", minecraftVersion = "1.12.1", nucleusVersion = "1.2")
public class KitViewCommand extends KitFallbackBase<Player> implements Reloadable {

    private boolean processTokens = false;

    @Override public CommandElement[] getArguments() {
        return new CommandElement[] {
                KitFallbackBase.KIT_PARAMETER_PERM_CHECK
        };
    }

    @Override
    public CommandResult executeCommand(Player src, CommandContext args, Cause cause) throws Exception {
        final Kit kitInfo = args.<Kit>getOne(KIT_PARAMETER_KEY).get();

        Inventory inventory = Util.getKitInventoryBuilder()
                .property(InventoryTitle.PROPERTY_NAME, InventoryTitle.of(Nucleus.getNucleus().getMessageProvider()
                        .getTextMessageWithFormat("command.kit.view.title", kitInfo.getName())))
                .build(Nucleus.getNucleus());

        List<ItemStack> lis = kitInfo.getStacks().stream().filter(x -> !x.getType().equals(ItemTypes.NONE)).map(ItemStackSnapshot::createStack)
                .collect(Collectors.toList());
        if (this.processTokens) {
            KIT_HANDLER.processTokensInItemStacks(src, lis);
        }

        lis.forEach(inventory::offer);
        return src.openInventory(inventory)
            .map(x -> {
                KIT_HANDLER.addViewer(x);
                return CommandResult.success();
            })
            .orElseThrow(() -> ReturnMessageException.fromKey("command.kit.view.cantopen", kitInfo.getName()));
    }

    @Override
    public void onReload() {
        this.processTokens = getServiceUnchecked(KitConfigAdapter.class).getNodeOrDefault().isProcessTokens();
    }
}


text:
from .data import WMIDatabase, get_region, get_country, get_year

class InvalidVINException(Exception):
    pass

class VINDecoder(object):
    def __init__(self):
        self.wmi_db = WMIDatabase("wmi_vinquery.csv")

    def parse_wmi(self, vin):
        region_code = vin[0]
        country_code = vin[0:2]
        wmi = vin[0:3]
        region = get_region(region_code)
        country = get_country(country_code)
        manufacturer = self.wmi_db.get(wmi)
        return region, country, manufacturer

    def parse_vds(self, vin, region, manufacturer):
        vds = vin[3:8]
        check = True
        return "Unknown", check

    def parse_vis(self, vin, region, manufacturer):
        vis = vin[9:]
        # XXX determine make and based on that get 1 or 2 character year code
        # from position 7 and 10 accordingly
        year_code = vis[0]
        try:
            year = get_year(year_code)
        except KeyError:
            year = None
        plant = vis[1]
        serial = vis[2:]
        return year, plant, serial

    def decode(self, vin):
        if len(vin) != 17:
            raise InvalidVINException()
        region, country, manufacturer = self.parse_wmi(vin)
        model, check = self.parse_vds(vin, region, manufacturer)
        year, plant, serial = self.parse_vis(vin, region, manufacturer)
        return {
            "region": region,
            "country": country,
            "manufacturer": manufacturer,
            "model": model,
            "check": check,
            "year": year,
            "assembly plant": plant,
            "serial": serial,
            }


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/html; charset=utf-8" />

    <title>numpy.polynomial.polynomial.Polynomial — NumPy v1.8 Manual</title>
    <link rel="stylesheet" href="../../_static/pythonista.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />

    <link rel="author" title="About these documents" href="../../about.html" />
    <link rel="top" title="NumPy v1.8 Manual" href="../../index.html" />
    <link rel="up" title="Polynomial Module (numpy.polynomial.polynomial)" href="../routines.polynomials.polynomial.html" />
    <link rel="next" title="numpy.polynomial.polynomial.Polynomial.domain" href="numpy.polynomial.polynomial.Polynomial.domain.html" />
    <link rel="prev" title="numpy.polynomial.polynomial.polyline" href="numpy.polynomial.polynomial.polyline.html" />
    <link rel="shortcut icon" type="image/png" href="../../_static/py.png" />
    <meta name = "viewport" content = "width=device-width,initial-scale=1.0,user-scalable=no;">

Navigation

          index

          next |

          previous |

NumPy v1.8 Manual »

NumPy Reference »

Routines »

Polynomials »

Polynomial Package »

Polynomial Module (<tt class="docutils literal">numpy.polynomial.polynomial</tt>) »

numpy.polynomial.polynomial.Polynomial¶

class <tt class="descclassname">numpy.polynomial.polynomial.</tt><tt class="descname">Polynomial</tt><big>(</big>coef, domain=[-1, 1], window=[-1, 1]<big>)</big>[source]¶

A Polynomial series class.

Polynomial instances provide the standard Python numerical methods ‘+’,
‘-‘, ‘*’, ‘//’, ‘%’, ‘divmod’, ‘**’, and ‘()’ as well as the listed
methods.

<col class="field-name" />
<col class="field-body" />

Parameters:
coef : array_like

Polynomial coefficients, in increasing order.  For example,
<tt class="docutils literal">(1, 2, 3)</tt> implies <tt class="docutils literal">P_0 + 2P_1 + 3P_2</tt> where the
<tt class="docutils literal">P_i</tt> are a graded polynomial basis.

domain : (2,) array_like, optional

Domain to use. The interval <tt class="docutils literal">[domain[0], domain[1]]</tt> is mapped to
the interval <tt class="docutils literal">[window[0], window[1]]</tt> by shifting and scaling.
The default value is [-1,1].

window : (2,) array_like, optional

Window, see <tt class="docutils literal">domain</tt> for its use. The default value is [-1,1].
.. versionadded:: 1.6.0

Notes

It is important to specify the domain in many cases, for instance in
fitting data, because many of the important properties of the
polynomial basis only hold in a specified interval and consequently
the data must be mapped into that interval in order to benefit.

Attributes

<colgroup>
<col width="10%" />
<col width="90%" />
</colgroup>

<tt class="xref py py-obj docutils literal">domain</tt>

<tt class="xref py py-obj docutils literal">window</tt>

<colgroup>
<col width="7%" />
<col width="21%" />
<col width="72%" />
</colgroup>

coef
(N,) ndarray
Polynomial coefficients, from low to high.

Methods

<colgroup>
<col width="10%" />
<col width="90%" />
</colgroup>

<tt class="xref py py-obj docutils literal">basis</tt>(deg[, domain, window])
Polynomial polynomial of degree deg.

<tt class="xref py py-obj docutils literal">cast</tt>(series[, domain, window])
Convert instance to equivalent Polynomial series.

<tt class="xref py py-obj docutils literal">convert</tt>([domain, kind, window])
Convert to different class and/or domain.

<tt class="xref py py-obj docutils literal">copy</tt>()
Return a copy.

<tt class="xref py py-obj docutils literal">cutdeg</tt>(deg)
Truncate series to the given degree.

<tt class="xref py py-obj docutils literal">degree</tt>()
The degree of the series.

<tt class="xref py py-obj docutils literal">deriv</tt>([m])
Differentiate.

<tt class="xref py py-obj docutils literal">fit</tt>(x, y, deg[, domain, rcond, full, w, window])
Least squares fit to data.

<tt class="xref py py-obj docutils literal">fromroots</tt>(roots[, domain, window])
Return Polynomial instance with specified roots.

<tt class="xref py py-obj docutils literal">has_samecoef</tt>(other)
Check if coefficients match.

<tt class="xref py py-obj docutils literal">has_samedomain</tt>(other)
Check if domains match.

<tt class="xref py py-obj docutils literal">has_sametype</tt>(other)
Check if types match.

<tt class="xref py py-obj docutils literal">has_samewindow</tt>(other)
Check if windows match.

<tt class="xref py py-obj docutils literal">identity</tt>([domain, window])
Identity function.

<tt class="xref py py-obj docutils literal">integ</tt>([m, k, lbnd])
Integrate.

<tt class="xref py py-obj docutils literal">linspace</tt>([n, domain])
Return x,y values at equally spaced points in domain.

<tt class="xref py py-obj docutils literal">mapparms</tt>()
Return the mapping parameters.

<tt class="xref py py-obj docutils literal">roots</tt>()
Return list of roots.

<tt class="xref py py-obj docutils literal">trim</tt>([tol])
Remove small leading coefficients  Remove leading coefficients until a coefficient is reached whose absolute value greater than tol or the beginning of the series is reached.

<tt class="xref py py-obj docutils literal">truncate</tt>(size)
Truncate series to length size.

    © Copyright 2008-2009, The Scipy community.

    The Python Software Foundation is a non-profit corporation.
    Please donate.

    Last updated on May 03, 2016.
    Found a bug?

    Created using Sphinx 1.2.1.


text:
using System;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;

namespace Nest
{
	internal class IndexRequestJsonConverter : JsonConverter
	{
		public override bool CanRead => true;
		public override bool CanWrite => true;
		public override bool CanConvert(Type objectType) => true;

		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			//not optimized but deserializing index requests is far from common practice
			var genericType = objectType.GetTypeInfo().GenericTypeArguments.First();
			var o = serializer.Deserialize(reader, genericType);
			var x = typeof(IndexRequest<>).CreateGenericInstance(genericType, typeof(DocumentPath<>).CreateGenericInstance(genericType, o));
			return x;
		}

		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			var v = value as IIndexRequest;
			serializer.Serialize(writer, v.UntypedDocument);
		}
	}
}


text:
package com.example.loadpluginresource;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Handler handler = new Handler();
        handler.postDelayed(goToPluginActivity, 1500);
    }

    Runnable goToPluginActivity = new Runnable() {
        @Override
        public void run() {
            try {
                // 启动 Plugin Activity
                Intent intent = new Intent(MainActivity.this, MyApplication.dexClassLoader.loadClass("com.example.plugin4.MainActivity"));
                startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
}


text:
using System;
using HOLMS.Platform.Types;
using HOLMS.Types.Extensions;
using HOLMS.Types.Extensions.Support;
using HOLMS.Types.Primitive;

namespace HOLMS.Types.Operations {
    public partial class CalendarMessageIndicator : EntityIndicator<CalendarMessageIndicator> {
        public CalendarMessageIndicator(Guid id) {
            Id = id.ToUUID();
        }

        public override Uuid GetUuidID() => Id;
    }
}


text:
'use strict';

/**
 * @ngdoc function
 * @name ifacebookApp.controller:FanpageCtrl
 * @description
 * # FanpageCtrl
 * Controller of the ifacebookApp
 */
angular.module('ifacebookApp')
    .controller('FanPageCtrl', function ($scope, $rootScope, $fb, $server, $timeout, $mdDialog) {

        console.log("Controller: FanPage Loading");

        // Tiêu đề
        $rootScope.titleHeader = "FanPage";

        // Thiết lập các Tabs
        $scope.tabs = {
            selectedIndex: 0,
            tab2Locked: false,
            tab3Locked: false,
            tab4Locked: false,
            tab5Locked: true
        };
        $scope.nextTab = function () {
            $scope.tabs.selectedIndex = Math.min($scope.tabs.selectedIndex + 1, 2);
        };

        // 1. Load Campaign in Tab 1: Chien dich
        $scope.loadCampains = function () {
            // List Campaigns
            $scope.campaigns = [];
            $scope.selectedCampaign = {};
            return $timeout(function () {
                $server.getCampains($rootScope.server)
                    .success(function (data) {
                        $scope.campaigns = data;
                        console.log("Campaigns: ", $scope.campaigns);
                    })
                    .error(function (err) {
                        $scope.status = 'Unable to load data:' + err;
                    });
            }, 500);
        };
        $scope.cacheIdCampaign = function (v) {
            $scope.idCampaign = v;
        };

        // 2. Xử lý tab: `FanPages`
        //console.log("FB Token:", $cookies.get('fbToken'));
        function autoLoadPages() {
            setTimeout(function () {
                $server.getPages()
                    .success(function (datas) {
                        datas.forEach(function (data) {
                            $server.countPosts(data._id)
                                .success(function (count) {
                                    $scope.pages.push({data: data, count: count});
                                    $scope.totalUIDPage = $scope.totalUIDPage + count[0].hasUID;
                                    console.log("List Page:", $scope.pages);
                                })
                        });
                        autoLoadPages();
                    })
                    .error(function (err) {
                        $scope.status = err;
                        console.log(err);
                    });
            },3000)

        }

        $scope.pages = [];
        $scope.totalUIDPage = 0;
        //loadPages();
        $scope.loadPages = function () {
            $server.getPages()
                .success(function (datas) {
                    datas.forEach(function (data) {
                        $server.countPosts(data._id)
                            .success(function (count) {
                                $scope.pages.push({data: data, count: count});
                                $scope.totalUIDPage = $scope.totalUIDPage + count[0].hasUID;
                                console.log("List Page:", $scope.pages);
                            })
                    });
                    //autoLoadPages();
                })
                .error(function (err) {
                    $scope.status = err;
                    console.log(err);
                });
        };

        $scope.initPage = function (node) {
            console.log("Page Node", node);
            $server.initPage(node,$rootScope.server)
                .success(function (data) {
                    console.log("Data init Page:", data);
                    $scope.infoPage = data;
                })
                .error(function (err) {
                    console.log("err:", err);
                    $scope.status('Unable loading from server:', err);
                })
        };
        $scope.alert = '';

        $scope.createPage = function () {
            var page = $scope.infoPage;
            page.idCampaign = $scope.idCampaign;
            console.log('Campaign selected: ', $scope.idCampaign, page);
            $server.createPage(page, $rootScope.server)
                .success(function (data) {
                    console.log("Data", data._id);
                    $scope.getFeed($scope.infoPage.username, data._id);

                    autoLoad(data._id);

                    $scope.nextTab();
                    if (data.message) {
                        $scope.status = data.message;
                    }
                })
                .error(function (err) {
                    console.log("Error", err);
                    $scope.status = err;
                });
        };

        /// Getting FEED
        $scope.feed = [];

        function autoLoad(idPage) {
            $server.getPostsByPage(idPage, $rootScope.server)
                .success(function (data) {
                    console.log("Data Autoload:", data);
                    if (data) {
                        $scope.feed = data;
                        setTimeout(function () {
                            autoLoad(idPage);
                        }, 3000)
                    }

                })
                .error(function (err) {
                    console.log(err);
                })
        }
        $scope.showFeed = function (node, idPage) {
            console.log("Show Feed:", node, idPage);
            autoLoad(idPage);
        };

        var nodeCachingLoad; // check username ko bi duplicate trang
        $scope.getFeed = function (node, idPage) {
            console.log("Node:", node, "- idPage:", idPage);
            $server.getFeeds(node, idPage)
                .success(function (data) {
                    console.log("Data FEED:", data);
                    $scope.feed = data.data;
                    if ( node == nodeCachingLoad) {
                        autoLoad(idPage);
                    }

                })
                .error(function (err) {
                    console.log("Server error:", err)
                })
        };

        $scope.updateFeed = function (node, idPage) {
            console.log("Node:", node, "- idPage:", idPage);
            $server.updateFeed(node, idPage)
                .success(function (data) {
                    console.log("Data Feed Update:", data);
                    $scope.feed = data.data;
                })
                .error(function (err) {
                    console.log("Server error:", err)
                })
        };

        $scope.tokens = [];

        $scope.GetUid = function (idPost, totalLike, token) {
            console.log('Getting data ...', idPost, totalLike, token);
            $server.getUid(idPost, totalLike, token).success(function (data) {
                console.log(data);
            })
                .error(function (err) {
                    console.log(err);
                })
        };

        $scope.autoGetUID = function (page) {
            $server.autoGetUID(page)
                .success(function (data) {
                    console.log("Data success:", data);
                })
                .error(function (err) {
                    console.log("Error Auto Get UID:", err);
                })
        };

        $scope.getFiltedUID = function (page) {
            $server.getFiltedUID(page)
                .success(function (data) {
                    console.log("Data success:", data);
                })
                .error(function (err) {
                    console.log("Error Auto Get UID:", err);
                })
        };

        $scope.getInfo = function (page) {
            $server.getInfo(page)
                .success(function (data) {
                    console.log("Data success:", data);
                })
                .error(function (err) {
                    console.log("Error Auto Get UID:", err);
                })
        };

        $scope.setLock = function (index) {
            var post = $scope.feed[index];
            $server.setLock(post.idPost)
                .success(function (data) {
                    console.log("set lock idPost", post.idPost, data);
                })
                .error(function (err) {
                    console.log("error set lock idPost", post.idPost, err)
                })
        };

        $scope.unLock = function (index) {
            var post = $scope.feed[index];
            $server.unLock(post.idPost)
                .success(function (data) {
                    console.log("set lock idPost", post.idPost, data);
                })
                .error(function (err) {
                    console.log("error set lock idPost", post.idPost, err)
                })
        };

        $scope.LoadMorePost = function(paging) {
            $server.loadmorePost(paging).success(function(morefeeds) {

                $scope.feed.paging.next = morefeeds.paging.next;
                morefeeds.data.forEach(function(ele) {
                    $scope.feed.data.push(ele);
                })
            })
        };

        $scope.loadUFB = function () {
            // List Campaigns
            $scope.UFBs = [];
            $scope.selectedUFB = [];

            return $timeout(function () {
                $server.getAllUFB()
                    .success(function (data) {
                        $scope.UFBs = data;
                        console.log("All UFB: ", $scope.UFBs);
                        console.log("Selected UFB", $scope.selectedUFB);
                    })
                    .error(function (err) {
                        $scope.status = 'Unable to load data:' + err;
                    });
            }, 500);
        };
    }
);


text:
let login = (username, password) => {
    if(username !== 'admin' || password !== 'radical') {
        console.log('incorrect login');
    }
};

login('admin', 'idunno');


text:
package org.wildfly.extension.elytron;

import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.StringListAttributeDefinition;
import org.jboss.dmr.ModelType;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.modules.ModuleLoadException;

/**
 * The common attribute definitions for specifying classes to be loaded by the subsystem.
 *
 * @author Darran Lofthouse
 */
class ClassLoadingAttributeDefinitions {

    static final SimpleAttributeDefinition MODULE = new SimpleAttributeDefinitionBuilder(ElytronDescriptionConstants.MODULE, ModelType.STRING, true)
        .setAttributeGroup(ElytronDescriptionConstants.CLASS_LOADING)
        .setAllowExpression(true)
        .setMinSize(1)
        .build();

    static final SimpleAttributeDefinition SLOT = new SimpleAttributeDefinitionBuilder(ElytronDescriptionConstants.SLOT, ModelType.STRING, true)
        .setAttributeGroup(ElytronDescriptionConstants.CLASS_LOADING)
        .setAllowExpression(true)
        .setMinSize(1)
        .build();

    static final SimpleAttributeDefinition CLASS_NAME = new SimpleAttributeDefinitionBuilder(ElytronDescriptionConstants.CLASS_NAME, ModelType.STRING, false)
        .setAttributeGroup(ElytronDescriptionConstants.CLASS_LOADING)
        .setAllowExpression(true)
        .setMinSize(1)
        .build();

    static final StringListAttributeDefinition CLASS_NAMES = new StringListAttributeDefinition.Builder(ElytronDescriptionConstants.CLASS_NAMES)
        .setAttributeGroup(ElytronDescriptionConstants.CLASS_LOADING)
        .setAllowExpression(true)
        .setAllowNull(true)
        .build();

    static ClassLoader resolveClassLoader(String module, String slot) throws ModuleLoadException {
        Module current = Module.getCallerModule();
        if (module != null) {
            ModuleIdentifier mi = ModuleIdentifier.create(module, slot);
            current = current.getModule(mi);
        }

        return current.getClassLoader();
    }

}


text:
// Licensed under the MIT License. See LICENSE file in the root of the solution for license information.

using System.Reflection.Emit;

namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions
{
    public class IlHandle
    {
        public ILGenerator Generator { get; internal set; }
    }
}


text:
package com.opp.service;

import com.opp.BaseIntegrationTest;
import com.opp.domain.ApplicationMap;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Optional;

import static org.junit.Assert.assertTrue;

/**
 * Created by jpalmer on 1/10/17.
 */
/* don't run if not using an external app-map service */
@Ignore
public class ApplicationMapExternalServiceTest extends BaseIntegrationTest {
    private static final String TEST_RR_TESTAPP = "test-rr-testapp";
    @Autowired
    private ApplicationMapExternalService service;

    @Before
    public void setup(){
        // Clear out any test apps.
        cleanupTestApps();
    }

    @After
    public void tearDown(){
        // Clear out any test apps.
        cleanupTestApps();
    }

    @Test
    public void getAllApplications() {
        assertTrue(service.getAll().size() > 0);
    }

    @Test
    public void getApplicationsAppKey() {
        String appKey = "auth-platform";
        List<ApplicationMap> apps = service.getAllByAppKey(appKey);
        assertTrue(apps.size() > 0);
        assertTrue(apps.get(0).getAppKey().equalsIgnoreCase(appKey));
    }

    @Test
    public void getAppById() {
        ApplicationMap applicationMap = new ApplicationMap();

        applicationMap.setIsClientSide(true);
        applicationMap.setAppKey(TEST_RR_TESTAPP);
        applicationMap.setInCdPipelineClient(true);
        applicationMap.setKqiAppName("test-kqi-app-name");
        applicationMap.setSecurityId(234234234);
        applicationMap.setNewrelic("my-nr-name");
        Optional<ApplicationMap> setupApp = service.add(applicationMap);

        assertTrue("If the app failed to get added this step will fail.", setupApp.isPresent());
        int applicationId = setupApp.get().getId();

        Optional<ApplicationMap> response = service.getById(applicationId);
        assertTrue(response.isPresent());
        assertTrue(response.get().getId().equals(applicationId));
    }

    @Test
    public void addApp() {
        ApplicationMap applicationMap = new ApplicationMap();

        applicationMap.setIsClientSide(true);
        applicationMap.setAppKey(TEST_RR_TESTAPP);
        applicationMap.setInCdPipelineClient(true);
        applicationMap.setKqiAppName("test-kqi-app-name");
        applicationMap.setSecurityId(234234234);
        applicationMap.setNewrelic("my-nr-name");
        Optional<ApplicationMap> response = service.add(applicationMap);

        assertTrue(response.isPresent());
        assertTrue(response.get().getId() > 0);
        assertTrue(response.get().getAppKey().equalsIgnoreCase(TEST_RR_TESTAPP));

    }

    @Test
    public void updateApp() {
        ApplicationMap applicationMap = new ApplicationMap();

        applicationMap.setIsClientSide(true);
        applicationMap.setAppKey(TEST_RR_TESTAPP);
        applicationMap.setInCdPipelineClient(true);
        applicationMap.setKqiAppName("test-kqi-app-name");
        applicationMap.setSecurityId(234234234);
        applicationMap.setNewrelic("my-nr-name");
        Optional<ApplicationMap> response = service.add(applicationMap);

        assertTrue(response.isPresent());
        assertTrue(response.get().getId() > 0);
        assertTrue(response.get().getAppKey().equalsIgnoreCase(TEST_RR_TESTAPP));

        applicationMap.setSecurityId(1234);
        Optional<ApplicationMap> updateResponse = service.update(response.get().getId(), applicationMap);

        assertTrue(updateResponse.isPresent());
        assertTrue(updateResponse.get().getId().equals(response.get().getId()));
        assertTrue(updateResponse.get().getSecurityId().equals(1234));

    }

    private void cleanupTestApps() {
        service.getAllByAppKey(TEST_RR_TESTAPP).forEach(app -> service.delete(app.getId()));
    }
}


text:
namespace AutoDependencyDetector.Interfaces
{
    public interface IDependencyProvider
    {
        void ProvideDependency( string dependendcyFullPath, string destinationDirectory );
    }
}


text:
<?php
    $this->load->view('admin_templates/header');
    $this->load->helper('form');

 ?>

Welcome to Battleme Admin Panel

                Reset Password

            <?php
            	    error_reporting(0);
                    $attributes = array('id' => 'resetpassword');
                    echo form_open('forgetpassword/update_password/'.$id, $attributes);
                ?>
                <fieldset>

                        <input type="password" name="password1" placeholder="New Password" class="form-control rounded input-lg text-center no-border">
                        <?php echo form_error('password1'); ?>

                       <input type="password" name="password2" placeholder="confirm Password" class="form-control rounded input-lg text-center no-border">
                        <?php echo form_error('password2'); ?>

                        <a href="<?php echo base_url('forgetpassword') ?>"> Forgot Password?

                        <input type="submit" class="btn btn-primary" value="Reset" />

                </fieldset>
             <?php echo form_close();?>


text:
<!-- Auto Generated Below -->

## Properties

| Property   | Attribute  | Description                                                                                | Type                                         | Default     |
| ---------- | ---------- | ------------------------------------------------------------------------------------------------------ | -------------------------------------------- | ----------- |
| `disabled` | `disabled` | Set to true to disable the button.                                                                     | `boolean`                                    | `undefined` |
| `fill`     | `fill`     |                                                                                | `"fill" \| "stroke"`                         | `'stroke'`  |
| `href`     | `href`     | When set, the underlying button will be rendered as an `<a>` with this `href` instead of a `<button>`. | `string`                                     | `undefined` |
| `onClick`  | --         |                                                                                | `(event: MouseEvent) => void`                | `undefined` |
| `target`   | `target`   | Tells the browser where to open the link. Only used when `href` is set.                                | `"_blank" \| "_parent" \| "_self" \| "_top"` | `undefined` |

## Shadow Parts

| Part      | Description |
| --------- | ----------- |
| `"base"`  |             |
| `"label"` |             |

## Dependencies

### Used by

 - [peculiar-button-split](../button-split)
 - [peculiar-certificate-decoder](../certificate-decoder)
 - [peculiar-certificates-viewer](../certificates-viewer)
 - [peculiar-text-hider](../text-hider)

### Graph
```mermaid
graph TD;
  peculiar-button-split --> peculiar-button
  peculiar-certificate-decoder --> peculiar-button
  peculiar-certificates-viewer --> peculiar-button
  peculiar-text-hider --> peculiar-button
  style peculiar-button fill:#f9f,stroke:#333,stroke-width:4px
```

----------------------------------------------


text:
title: Get Started
parent: Home
nav_order: 1
---

# Get Started

This is the quickest way to get MNE-CPP up and running on your machine:

**1 Download MNE-CPP**

  [Download](../install/binaries.md) the latest stable release for the best stability, or the dev_build release for the latest features.

**2 Unzip the downloaded file**

  Extract the downloaded build into a folder on your machine

**3 Select the tool you wish to use from the `bin` folder**

  Currently we offer a real-time application: [MNE-Scan](../learn/scan.md); a visualization/analysis application: [MNE Analyze](../learn/analyze.md); and a data anonymization tool: [MNE Anonymize](../learn/anonymize).

**4 Follow the [guides](../learn/learn.md) on how to use MNE-CPP tools**

---

If you'd like to develop with and contribute to MNE-CPP you can check out our guide on how to [build from source](../install/buildguide.md).