text:
{-# LANGUAGE TemplateHaskell #-}
module Matterhorn.Types.EditState
  ( EditMode(..)
  , AttachmentData(..)
  , AutocompletionType(..)

  , CompletionSource(..)
  , SpecialMention(..)
  , specialMentionName
  , isSpecialMention

  , EditState(..)
  , newEditState
  , unsafeEsFileBrowser
  , esAttachmentList
  , esFileBrowser
  , esMisspellings
  , esEditMode
  , esEphemeral
  , esEditor
  , esAutocomplete
  , esAutocompletePending
  , esResetEditMode
  , esJustCompleted
  , esShowReplyPrompt
  , esSpellCheckTimerReset
  , esTeamId
  , esChannelId

  , EphemeralEditState(..)
  , defaultEphemeralEditState
  , eesMultiline
  , eesInputHistoryPosition
  , eesLastInput
  , eesTypingUsers
  , addEphemeralStateTypingUser

  , AutocompleteState(..)
  , acPreviousSearchString
  , acCompletionList
  , acCachedResponses
  , acType

  , AutocompleteAlternative(..)
  , autocompleteAlternativeReplacement
  )
where

import           Prelude ()
import           Matterhorn.Prelude

import           Brick.Widgets.Edit ( Editor, editor )
import           Brick.Widgets.List ( List, list )
import qualified Brick.Widgets.FileBrowser as FB
import qualified Data.ByteString as BS
import qualified Data.HashMap.Strict as HM
import qualified Data.Text as T
import           Lens.Micro.Platform ( Lens', makeLenses, (.~), (^?!), lens, _Just
                                     , (%~) )
import           Network.Mattermost.Types

import           Matterhorn.Types.Common
import           Matterhorn.Types.Messages ( Message, MessageType )
import           Matterhorn.Types.Users ( TypingUsers, noTypingUsers, addTypingUser
                                        , addUserSigil, trimUserSigil )
import           Matterhorn.Constants

-- | A "special" mention that does not map to a specific user, but is an
-- alias that the server uses to notify users.
data SpecialMention =
    MentionAll
    -- ^ @all: notify everyone in the channel.
    | MentionChannel
    -- ^ @channel: notify everyone in the channel.

data AutocompleteAlternative =
    UserCompletion User Bool
    -- ^ User, plus whether the user is in the channel that triggered
    -- the autocomplete
    | SpecialMention SpecialMention
    -- ^ A special mention.
    | ChannelCompletion Bool Channel
    -- ^ Channel, plus whether the user is a member of the channel
    | SyntaxCompletion Text
    -- ^ Name of a skylighting syntax definition
    | CommandCompletion CompletionSource Text Text Text
    -- ^ Source, name of a slash command, argspec, and description
    | EmojiCompletion Text
    -- ^ The text of an emoji completion

-- | The source of an autocompletion alternative.
data CompletionSource = Server | Client
                      deriving (Eq, Show)

specialMentionName :: SpecialMention -> Text
specialMentionName MentionChannel = "channel"
specialMentionName MentionAll = "all"

isSpecialMention :: T.Text -> Bool
isSpecialMention n = isJust $ lookup (T.toLower $ trimUserSigil n) pairs
    where
        pairs = mkPair <$> mentions
        mentions = [ MentionChannel
                   , MentionAll
                   ]
        mkPair v = (specialMentionName v, v)

autocompleteAlternativeReplacement :: AutocompleteAlternative -> Text
autocompleteAlternativeReplacement (EmojiCompletion e) =
    ":" <> e <> ":"
autocompleteAlternativeReplacement (SpecialMention m) =
    addUserSigil $ specialMentionName m
autocompleteAlternativeReplacement (UserCompletion u _) =
    addUserSigil $ userUsername u
autocompleteAlternativeReplacement (ChannelCompletion _ c) =
    normalChannelSigil <> (sanitizeUserText $ channelName c)
autocompleteAlternativeReplacement (SyntaxCompletion t) =
    "```" <> t
autocompleteAlternativeReplacement (CommandCompletion _ t _ _) =
    "/" <> t

-- | The type of data that the autocompletion logic supports. We use
-- this to track the kind of completion underway in case the type of
-- completion needs to change.
data AutocompletionType =
    ACUsers
    | ACChannels
    | ACCodeBlockLanguage
    | ACEmoji
    | ACCommands
    deriving (Eq, Show)

-- | An attachment.
data AttachmentData =
    AttachmentData { attachmentDataFileInfo :: FB.FileInfo
                   , attachmentDataBytes :: BS.ByteString
                   }
                   deriving (Eq, Show)

-- | The input state associated with the message editor.
data EditMode =
    NewPost
    -- ^ The input is for a new post.
    | Editing Post MessageType
    -- ^ The input is ultimately to replace the body of an existing post
    -- of the specified type.
    | Replying Message Post
    -- ^ The input is to be used as a new post in reply to the specified
    -- post.
    deriving (Show, Eq)

data AutocompleteState n =
    AutocompleteState { _acPreviousSearchString :: Text
                      -- ^ The search string used for the
                      -- currently-displayed autocomplete results, for
                      -- use in deciding whether to issue another server
                      -- query
                      , _acCompletionList :: List n AutocompleteAlternative
                      -- ^ The list of alternatives that the user
                      -- selects from
                      , _acType :: AutocompletionType
                      -- ^ The type of data that we're completing
                      , _acCachedResponses :: HM.HashMap Text [AutocompleteAlternative]
                      -- ^ A cache of alternative lists, keyed on search
                      -- string, for use in avoiding server requests.
                      -- The idea here is that users type quickly enough
                      -- (and edit their input) that would normally lead
                      -- to rapid consecutive requests, some for the
                      -- same strings during editing, that we can avoid
                      -- that by caching them here. Note that this cache
                      -- gets destroyed whenever autocompletion is not
                      -- on, so this cache does not live very long.
                      }

-- | The 'EditState' value contains the editor widget itself as well as
-- history and metadata we need for editing-related operations.
data EditState n =
    EditState { _esEditor :: Editor Text n
              , _esEditMode :: EditMode
              , _esEphemeral :: EphemeralEditState
              , _esMisspellings :: Set Text
              , _esAutocomplete :: Maybe (AutocompleteState n)
              -- ^ The autocomplete state. The autocompletion UI is
              -- showing only when this state is present.
              , _esResetEditMode :: EditMode
              -- ^ The editing mode to reset to after input is handled.
              , _esAutocompletePending :: Maybe Text
              -- ^ The search string associated with the latest
              -- in-flight autocompletion request. This is used to
              -- determine whether any (potentially late-arriving) API
              -- responses are for stale queries since the user can type
              -- more quickly than the server can get us the results,
              -- and we wouldn't want to show results associated with
              -- old editor states.
              , _esAttachmentList :: List n AttachmentData
              -- ^ The list of attachments to be uploaded with the post
              -- being edited.
              , _esFileBrowser :: Maybe (FB.FileBrowser n)
              -- ^ The browser for selecting attachment files. This is
              -- a Maybe because the instantiation of the FileBrowser
              -- causes it to read and ingest the target directory, so
              -- this action is deferred until the browser is needed.
              , _esJustCompleted :: Bool
              -- A flag that indicates whether the most recent editing
              -- event was a tab-completion. This is used by the smart
              -- trailing space handling.
              , _esShowReplyPrompt :: Bool
              -- ^ Whether to show the reply prompt when replying
              , _esSpellCheckTimerReset :: Maybe (IO ())
              -- ^ An action to reset the spell check timer for this
              -- editor, if a spell checker is running.
              , _esChannelId :: ChannelId
              -- ^ Channel ID associated with this edit state
              , _esTeamId :: Maybe TeamId
              -- ^ Team ID associated with this edit state (optional
              -- since not all channels are associated with teams)
              }

newEditState :: n -> n -> Maybe TeamId -> ChannelId -> EditMode -> Bool -> Maybe (IO ()) -> EditState n
newEditState editorName attachmentListName tId cId initialEditMode showReplyPrompt reset =
    EditState { _esEditor               = editor editorName Nothing ""
              , _esEphemeral            = defaultEphemeralEditState
              , _esEditMode             = initialEditMode
              , _esResetEditMode        = initialEditMode
              , _esMisspellings         = mempty
              , _esAutocomplete         = Nothing
              , _esAutocompletePending  = Nothing
              , _esAttachmentList       = list attachmentListName mempty 1
              , _esFileBrowser          = Nothing
              , _esJustCompleted        = False
              , _esShowReplyPrompt      = showReplyPrompt
              , _esSpellCheckTimerReset = reset
              , _esChannelId            = cId
              , _esTeamId               = tId
              }

data EphemeralEditState =
    EphemeralEditState { _eesMultiline :: Bool
                       -- ^ Whether the editor is in multiline mode
                       , _eesInputHistoryPosition :: Maybe Int
                       -- ^ The input history position, if any
                       , _eesLastInput :: (T.Text, EditMode)
                       -- ^ The input entered into the text editor last
                       -- time the user was focused on the channel
                       -- associated with this state.
                       , _eesTypingUsers :: TypingUsers
                       }

defaultEphemeralEditState :: EphemeralEditState
defaultEphemeralEditState =
    EphemeralEditState { _eesMultiline = False
                       , _eesInputHistoryPosition = Nothing
                       , _eesLastInput = ("", NewPost)
                       , _eesTypingUsers = noTypingUsers
                       }

makeLenses ''EphemeralEditState

-- | Add user to the list of users in this state who are currently typing.
addEphemeralStateTypingUser :: UserId -> UTCTime -> EphemeralEditState -> EphemeralEditState
addEphemeralStateTypingUser uId ts = eesTypingUsers %~ (addTypingUser uId ts)

makeLenses ''EditState
makeLenses ''AutocompleteState

unsafeEsFileBrowser :: Lens' (EditState n) (FB.FileBrowser n)
unsafeEsFileBrowser =
     lens (\st   -> st^.esFileBrowser ^?! _Just)
          (\st t -> st & esFileBrowser .~ Just t)


text:
#region License

// Copyright (c) 2014 The Sentry Team and individual contributors.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
//     1. Redistributions of source code must retain the above copyright notice, this list of
//        conditions and the following disclaimer.
//
//     2. Redistributions in binary form must reproduce the above copyright notice, this list of
//        conditions and the following disclaimer in the documentation and/or other materials
//        provided with the distribution.
//
//     3. Neither the name of the Sentry nor the names of its contributors may be used to
//        endorse or promote products derived from this software without specific prior written
//        permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#endregion

using System.Configuration;

namespace SharpRaven.Nancy
{
    /// <summary>
    /// Nancy-specific configuration for SharpRaven.
    /// </summary>
    public class NancyConfiguration : Configuration
    {
        private const string CaptureExceptionOnErrorKey = "captureExceptionOnError";
        private const string PipelineNameKey = "pipelineName";

        /// <summary>
        /// Gets the nancy context data slot.
        /// </summary>
        /// <value>
        /// The nancy context data slot.
        /// </value>
        public const string NancyContextDataSlot = "SharpRaven.Nancy.NancyContext";

        /// <summary>
        /// Gets the key for the GUID returned from Sentry after a successfully logged exception.
        /// </summary>
        /// <value>
        /// The key for the GUID returned from Sentry after a successfully logged exception.
        /// </value>
        public const string SentryEventGuidKey = "SharpRaven.Nancy.SentryEventGuid";

        private static readonly NancyConfiguration settings =
            ConfigurationManager.GetSection("sharpRaven") as NancyConfiguration;

        /// <summary>
        /// Gets the <captureExceptionOnError /> configuration element.
        /// </summary>
        /// <value>
        /// The <captureExceptionOnError /> configuration element.
        /// </value>
        [ConfigurationProperty(CaptureExceptionOnErrorKey, IsKey = true)]
        public CaptureExceptionOnErrorElement CaptureExceptionOnError
        {
            get { return (CaptureExceptionOnErrorElement)base[CaptureExceptionOnErrorKey]; }
        }

        /// <summary>
        /// Gets the <pipelineName /> configuration element.
        /// </summary>
        /// <value>
        /// The <pipelineName /> configuration element.
        /// </value>
        [ConfigurationProperty(PipelineNameKey, IsKey = true)]
        public PipelineNameElement PipelineName
        {
            get { return (PipelineNameElement)base[PipelineNameKey]; }
        }

        /// <summary>
        /// Gets the <sharpRaven/> configuration element.
        /// </summary>
        /// <value>
        /// The the <sharpRaven/> configuration element.
        /// </value>
        public new static NancyConfiguration Settings
        {
            get { return settings; }
        }

        #region Nested type: CaptureExceptionOnErrorElement

        /// <summary>
        /// The <captureExceptionOnError /> configuration element.
        /// </summary>
        public class CaptureExceptionOnErrorElement : ConfigurationElement
        {
            /// <summary>
            /// Gets or sets the value of the the <captureExceptionOnError /> configuration element.
            /// </summary>
            /// <value>
            ///   <c>true</c> if exceptions should be captured by SharpRaven; otherwise, <c>false</c>.
            /// </value>
            [ConfigurationProperty("value", DefaultValue = "true")]
            public bool Value
            {
                get { return (bool)this["value"]; }
                set { this["value"] = value; }
            }
        }

        #endregion

        #region Nested type: PipelineNameElement

        /// <summary>
        /// The <pipelineName /> configuration element.
        /// </summary>
        public class PipelineNameElement : ConfigurationElement
        {
            /// <summary>
            /// Gets or sets the value of the <pipelineName /> configuration element.
            /// </summary>
            /// <value>
            /// The value of the the <pipelineName /> configuration element.
            /// </value>
            [ConfigurationProperty("value", DefaultValue = "SharpRaven.Nancy")]
            public string Value
            {
                get { return (string)this["value"]; }
                set { this["value"] = value; }
            }
        }

        #endregion
    }
}

redpajama_set_name: RedPajamaGithub


text:
import sbt._
import Keys._

object PluginBuild extends Build {
  // xsbt-gpg-plugin 0.4 is the last version compatible with sbt 0.12
  lazy val xsbtGpgPlugin =
    RootProject(uri("git://github.com/sbt/xsbt-gpg-plugin.git#0.4"))

  lazy val root =
    Project(id = "root", base = file(".")).dependsOn(xsbtGpgPlugin)

  override final def settings =
    super.settings :+ (scalaVersion := "2.9.1")

}

// vim: set ts=2 sw=2 et:


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Documents;
using System.Windows;
using System.Windows.Media;

namespace Sigillo.DragDrop
{
    class DragAdorner : Adorner
    {
        public DragAdorner(UIElement adornedElement, UIElement adornment)
            : base(adornedElement)
        {
            m_AdornerLayer = AdornerLayer.GetAdornerLayer(adornedElement);
            m_AdornerLayer.Add(this);
            m_Adornment = adornment;
            IsHitTestVisible = false;
        }

        public Point MousePosition
        {
            get { return m_MousePosition; }
            set
            {
                if (m_MousePosition != value)
                {
                    m_MousePosition = value;
                    m_AdornerLayer.Update(AdornedElement);
                }
            }
        }

        public void Detatch()
        {
            m_AdornerLayer.Remove(this);
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            m_Adornment.Arrange(new Rect(finalSize));
            return finalSize;
        }

        public override GeneralTransform GetDesiredTransform(GeneralTransform transform)
        {
            GeneralTransformGroup result = new GeneralTransformGroup();
            result.Children.Add(base.GetDesiredTransform(transform));
            result.Children.Add(new TranslateTransform(MousePosition.X - 4, MousePosition.Y - 4));

            return result;
        }

        protected override Visual GetVisualChild(int index)
        {
            return m_Adornment;
        }

        protected override Size MeasureOverride(Size constraint)
        {
            m_Adornment.Measure(constraint);
            return m_Adornment.DesiredSize;
        }

        protected override int VisualChildrenCount
        {
            get { return 1; }
        }

        AdornerLayer m_AdornerLayer;
        UIElement m_Adornment;
        Point m_MousePosition;
    }
}


text:
package org.jitsi.service.neomedia;

import java.net.*;

/**
 * RTP extensions are defined by RFC 5285 and they allow attaching additional
 * information to some or all RTP packets of an RTP stream. This class describes
 * RTP extensions in a way that makes them convenient for use in SDP
 * generation/parsing.
 *
 * @author Emil Ivov
 */
public class RTPExtension
{
    /**
     * The URN identifying the RTP extension that allows mixers to send to
     * conference participants the audio levels of all contributing sources.
     * Defined in RFC6465.
     */
    public static final String CSRC_AUDIO_LEVEL_URN
            = "urn:ietf:params:rtp-hdrext:csrc-audio-level";

    /**
     * The URN identifying the RTP extension that allows clients to send to
     * conference mixers the audio level of their packet payload. Defined in
     * RFC6464.
     */
    public static final String SSRC_AUDIO_LEVEL_URN
            = "urn:ietf:params:rtp-hdrext:ssrc-audio-level";

    /**
     * The URN identifying the abs-send-time RTP extension.
     * Defined at
     * {@link "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"}
     */
    public static final String ABS_SEND_TIME_URN
            = "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time";

    /**
     * The direction that this extension will be transmitted in.
     */
    private MediaDirection direction = MediaDirection.SENDRECV;

    /**
     * The <tt>URI</tt> identifier of this extension.
     */
    private final URI extensionURI;

    /**
     * Extension specific attributes.
     */
    private String extensionAttributes = null;

    /**
     * Creates an <tt>RTPExtension</tt> instance for the specified
     * <tt>extensionURI</tt> using a default <tt>SENDRECV</tt> direction and no
     * extension attributes.
     *
     * @param extensionURI the <tt>URI</tt> (possibly a URN) of the RTP
     * extension that we'd like to create.
     */
    public RTPExtension(URI extensionURI)
    {
        this(extensionURI, MediaDirection.SENDRECV);
    }

    /**
     * Creates an <tt>RTPExtension</tt> instance for the specified
     * <tt>extensionURI</tt> and <tt>direction</tt>.
     *
     * @param extensionURI the <tt>URI</tt> (possibly a URN) of the RTP
     * extension that we'd like to create.
     * @param direction a <tt>MediaDirection</tt> instance indication how this
     * extension will be transmitted.
     */
    public RTPExtension(URI extensionURI, MediaDirection direction)
    {
        this(extensionURI, direction, null);
    }

    /**
     * Creates an <tt>RTPExtension</tt> instance for the specified
     * <tt>extensionURI</tt> using a default <tt>SENDRECV</tt> direction and
     * <tt>extensionAttributes</tt>.
     *
     * @param extensionURI the <tt>URI</tt> (possibly a URN) of the RTP
     * extension that we'd like to create.
     * @param extensionAttributes any attributes that we'd like to add to this
     * extension.
     */
    public RTPExtension(URI extensionURI, String extensionAttributes)
    {
        this(extensionURI, MediaDirection.SENDRECV, extensionAttributes);
    }

    /**
     * Creates an <tt>RTPExtension</tt> instance for the specified
     * <tt>extensionURI</tt> and <tt>direction</tt> and sets the specified
     * <tt>extensionAttributes</tt>.
     *
     * @param extensionURI the <tt>URI</tt> (possibly a URN) of the RTP
     * extension that we'd like to create.
     * @param direction a <tt>MediaDirection</tt> instance indication how this
     * extension will be transmitted.
     * @param extensionAttributes any attributes that we'd like to add to this
     * extension.
     */
    public RTPExtension(URI            extensionURI,
                        MediaDirection direction,
                        String         extensionAttributes)
    {
        this.extensionURI = extensionURI;
        this.direction = direction;
        this.extensionAttributes = extensionAttributes;
    }

    /**
     * Returns the direction that the corresponding <tt>MediaDevice</tt>
     * supports for this extension. By default RTP extension headers inherit
     * the direction of a stream. When explicitly specified <tt>SENDONLY</tt>
     * direction indicates an ability to attach the extension in outgoing RTP
     * packets; a <tt>RECVONLY</tt> direction indicates a desire to receive
     * the extension in incoming packets; a <tt>SENDRECV</tt> direction
     * indicates both.  An <tt>INACTIVE</tt> direction indicates neither, but
     * later re-negotiation may make an extension active.
     *
     * @return the direction that the corresponding <tt>MediaDevice</tt>
     * supports for this extension.
     */
    public MediaDirection getDirection()
    {
        return direction;
    }

    /**
     * Returns the <tt>URI</tt> that identifies the format and meaning of this
     * extension.
     *
     * @return the <tt>URI</tt> (possibly a URN) that identifies the format and
     * meaning of this extension.
     */
    public URI getURI()
    {
        return extensionURI;
    }

    /**
     * Returns the extension attributes associated with this
     * <tt>RTPExtension</tt> or <tt>null</tt> if this extension does not have
     * any.
     *
     * @return A <tt>String</tt> containing the extension attributes associated
     * with this <tt>RTPExtension</tt> or <tt>null</tt> if this extension does
     * not have any.
     */
    public String getExtensionAttributes()
    {
        return extensionAttributes;
    }

    /**
     * Returns a <tt>String</tt> representation of this <tt>RTPExtension</tt>'s
     * <tt>URI</tt>.
     *
     * @return a <tt>String</tt> representation of this <tt>RTPExtension</tt>'s
     * <tt>URI</tt>.
     */
    @Override
    public String toString()
    {
        return extensionURI.toString() + ";" + getDirection();
    }

    /**
     * Returns <tt>true</tt> if and only if <tt>o</tt> is an instance of
     * <tt>RTPExtension</tt> and <tt>o</tt>'s <tt>URI</tt> is equal to this
     * extension's <tt>URI</tt>. The method returns <tt>false</tt> otherwise.
     *
     * @param o the <tt>Object</tt> that we'd like to compare to this
     * <tt>RTPExtension</tt>.
     *
     * @return <tt>true</tt> when <tt>o</tt>'s <tt>URI</tt> is equal to this
     * extension's <tt>URI</tt> and <tt>false</tt> otherwise.
     */
    @Override
    public boolean equals(Object o)
    {
        return (o instanceof RTPExtension)
            && ((RTPExtension)o).getURI().equals(getURI());
    }

    /**
     * Returns the hash code of this extension instance which is actually the
     * hash code of the <tt>URI</tt> that this extension is encapsulating.
     *
     * @return the hash code of this extension instance which is actually the
     * hash code of the <tt>URI</tt> that this extension is encapsulating.
     */
    @Override
    public int hashCode()
    {
        return getURI().hashCode();
    }
}


text:
Candle is a client/server package for controlling Chrome (and Chromium based browsers) remotely.
Use it to show pictures of cats on your dashboard monitors or to close/make active different tabs.

##Installation

The only requirement is `node`/`npm`. Download them through your favorite package manager, or at [http://nodejs.org/](http://nodejs.org/)

If you've got `npm` installed, you can simply run this command from the top level directory:

	npm run install-all

… which will install bower (globally), and fetch the bower dependencies for the Chrome extension and Server.

You can install just the server:

	npm run install-server

And just the client:

	npm run install-client

##Running

###Server

After running the installation step above, you can run the server via:

	npm run server -- -p [port]

Or:

	node server/server.js -p [port]

Where [port] is a required argument, and a number.

Visiting 127.0.0.1:[port] with a client connected will present you the administration page.

###Client

In Chrome, visit the [extensions page](chrome://extensions/), hit the 'Load unpacked extension…' button, navigate to the chrome/ subdirectory and select it.

##License

MIT.


text:
package cz.cvut.fit.ortstepa.universalbookingsystem.web;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cz.cvut.fit.ortstepa.universalbookingsystem.domain.ResourceProperty;
import cz.cvut.fit.ortstepa.universalbookingsystem.service.ResourcePropertyService;

@Controller
@RequestMapping("/resource/property")
public class ResourcePropertyController {

	@Autowired
	private ResourcePropertyService resourcePropertyService;

	private static final String VN_RES_PROP_LIST = "resource/property/list";
	private static final String VN_RES_PROP_DETAIL = "resource/property/detail";
	private static final String VN_RES_PROP_EDIT = "resource/property/edit";
	private static final String VN_RES_PROP_REDIRECT = "redirect:/resource/property";

	private static final Logger logger = LoggerFactory.getLogger(ResourcePropertyController.class);

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.setAllowedFields(new String[] {
			"name", "type", "defaultValue"
		});
	}

	private String page(Model model) {
		model.addAttribute("resourcePropertyList", resourcePropertyService.getAll());
		return VN_RES_PROP_LIST;
	}

	private String detail(Model model, ResourceProperty resourceProperty) {
		model.addAttribute("resourceProperty", resourceProperty);
		return VN_RES_PROP_DETAIL;
	}

	private String form(Model model, ResourceProperty resourceProperty) {
		model.addAttribute("resourceProperty", resourceProperty);
		return VN_RES_PROP_EDIT;
	}

	@RequestMapping(method = RequestMethod.GET, params={"form"})
	public String create(Model model) {
		return form(model, new ResourceProperty());
	}

	@RequestMapping(method = RequestMethod.GET)
	public String list(Model model) {
		return page(model);
	}

	@RequestMapping(value="/{id}", method=RequestMethod.GET)
	public String item(Model model, @PathVariable Long id, @RequestParam(required=false) String form, final RedirectAttributes redirectAttributes) {
		ResourceProperty resourceProperty = resourcePropertyService.getById(id);
		if (resourceProperty == null) {
			redirectAttributes.addFlashAttribute("error", "resourceProperty.notFound");
			return VN_RES_PROP_REDIRECT;
		}
		if (form != null) {
			return form(model, resourceProperty);
		}
		return detail(model, resourceProperty);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
	public String edit(@Valid @ModelAttribute ResourceProperty resourceProperty, BindingResult result, @PathVariable Long id, Model model, final RedirectAttributes redirectAttributes) {
		if (!result.hasErrors()) {
			resourceProperty.setId(id);
			resourcePropertyService.update(resourceProperty, result);
			if (!result.hasErrors()) {
				redirectAttributes.addFlashAttribute("success", "resourceProperty.edit.success");
				return VN_RES_PROP_REDIRECT;
			}
		}
		return VN_RES_PROP_EDIT;
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	public String remove(Model model, @PathVariable Long id, final RedirectAttributes redirectAttributes) {
		if (resourcePropertyService.delete(id)) {
			redirectAttributes.addFlashAttribute("success", "resourceProperty.remove.success");
			return VN_RES_PROP_REDIRECT;
		}
		model.addAttribute("error", "resourceProperty.remove.error");
		return VN_RES_PROP_DETAIL;
	}

	@RequestMapping(method = RequestMethod.POST)
	public String create(@Valid @ModelAttribute ResourceProperty resourceProperty, BindingResult result, Model model, final RedirectAttributes redirectAttributes) {
		if (!result.hasErrors()) {
			resourcePropertyService.add(resourceProperty, result);
			if (!result.hasErrors()) {
				redirectAttributes.addFlashAttribute("success", "resourceProperty.create.success");
				return VN_RES_PROP_REDIRECT;
			}
		}
		return VN_RES_PROP_EDIT;
	}
}


text:
package net.sf.pagecache.constructs.web.plugins.redis;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

import net.sf.pagecache.constructs.web.plugins.redis.serializer.HessianSerializer;
import net.sf.pagecache.constructs.web.plugins.redis.serializer.ISerializer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPipeline;
import redis.clients.jedis.ShardedJedisPool;

/**
 * 分片的redis客户端
 *
 * @author hailin0@yeah.net
 * @createDate 2016年3月3日
 *
 */
public class JedisManager {

    private static final Logger log = LoggerFactory.getLogger(JedisManager.class);

    private ShardedJedisPool shardedJedisPool;

    /**
     * 序列化工具,默认使用Hessian2
     */
    private ISerializer<Object> serializer = new HessianSerializer();

    /**
     * @param shardedJedisPool
     */
    public JedisManager(ShardedJedisPool shardedJedisPool) {
        this.shardedJedisPool = shardedJedisPool;
    }

    /**
     * 在hash中存入单个键值对
     *
     * @param key
     * @param field
     * @param value
     * @param expireTime
     */
    public void hsetByte(String key, String field, Object value, int expireTime) {
        ShardedJedis shardedJedis = shardedJedisPool.getResource();
        if (shardedJedis == null) {
            return;
        }
        try {
            ShardedJedisPipeline pipelined = shardedJedis.pipelined();
            pipelined.hset(serializer.serialize(key), serializer.serialize(field),
                    serializer.serialize(value));
            pipelined.expire(serializer.serialize(key), expireTime);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            shardedJedis.close();
        }
    }

    /**
     * 删除hash中某些field,如果field为空则删除整个hash
     *
     * @param key
     * @param field
     */
    public void hdelByte(String key, String... field) {
        ShardedJedis shardedJedis = shardedJedisPool.getResource();
        if (shardedJedis == null) {
            return;
        }
        try {
            if (null == field) {
                shardedJedis.del(serializer.serialize(key));
                return;
            }
            shardedJedis.hdel(serializer.serialize(key), stringToByte(field));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            shardedJedis.close();
        }
    }

    /**
     * 批量获取
     *
     * @param key
     * @param clazz
     * @param field
     * @return
     */
    public <T> Collection<T> hgetByte(String key, Class<T> clazz, String... field) {
        ShardedJedis shardedJedis = shardedJedisPool.getResource();
        if (shardedJedis == null) {
            return null;
        }
        Collection<T> result = new ArrayList<T>();
        ;
        try {
            Collection<byte[]> values = null;
            if (null != field) {
                values = shardedJedis.hmget(serializer.serialize(key), stringToByte(field));
            } else {
                Map<byte[], byte[]> hgetAll = shardedJedis.hgetAll(serializer.serialize(key));
                values = hgetAll.values();
            }
            result = serializer.deserialize(values, clazz);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            shardedJedis.close();
        }
        return result;
    }

    /**
     * 获取hash中的field
     *
     * @param key
     * @param clazz
     * @param field
     * @return
     */
    public <T> T hgetByte(String key, Class<T> clazz, String field) {
        ShardedJedis shardedJedis = shardedJedisPool.getResource();
        if (shardedJedis == null) {
            return null;
        }
        T result = null;
        try {
            if (null != field) {
                byte[] bytes = shardedJedis.hget(serializer.serialize(key),
                        serializer.serialize(field));
                return serializer.deserialize(bytes, clazz);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            shardedJedis.close();
        }
        return result;
    }

    /**
     * String数组转byte
     *
     * @param field
     * @return
     */
    public byte[][] stringToByte(String... field) {
        byte[][] result = new byte[field.length][];
        for (int i = 0, len = field.length; i < len; i++) {
            try {
                result[i] = serializer.serialize(field[i]);
            } catch (Exception e) {
                return null;
            }
        }
        return result;
    }
}


text:
<?php
namespace Tests\DecoratorStack;

/**
 * Class FooBarObject
 *
 * @package Tests\DecoratorStack
 */
class FooBarObject
{
    /**
     * @param string $foo
     */
    public function __construct($foo)
    {
        // Something to do
    }
}


text:
package com.linecorp.armeria.common;

import java.nio.charset.Charset;

import com.linecorp.armeria.common.annotation.Nullable;

/**
 * A complete HTTP headers and content that are readily available.
 */
public interface AggregatedHttpObject {

    /**
     * Returns the HTTP headers.
     */
    HttpHeaders headers();

    /**
     * Returns the content of this message.
     */
    HttpData content();

    /**
     * Returns the content of this message as a string encoded in the specified {@link Charset}.
     */
    default String content(Charset charset) {
        return content().toString(charset);
    }

    /**
     * Returns the content of this message as a UTF-8 string.
     */
    default String contentUtf8() {
        return content().toStringUtf8();
    }

    /**
     * Returns the content of this message as an ASCII string.
     */
    default String contentAscii() {
        return content().toStringAscii();
    }

    /**
     * Returns the value of the {@code 'content-type'} header.
     * @return the valid header value if present, or {@code null} otherwise.
     */
    @Nullable
    default MediaType contentType() {
        return headers().contentType();
    }
}


text:
"""
Given a complete binary tree, count the number of nodes.

In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level
are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
"""
__author__ = 'Daniel'

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

    def __repr__(self):
        return repr(self.val)

class Solution:
    def countNodes(self, root):
        """
        O((lg n)^2)
        """
        if not root:
            return 0
        h = self.get_height(root)
        h_r = self.get_height(root.right)
        if h == h_r+1:
            return 2**(h-1)-1+1+self.countNodes(root.right)  # left_tree nodes + root + right_tree nodes
        else:
            return 2**(h-2)-1+1+self.countNodes(root.left)  # right_tree nodes + root + left_tree nodes

    def get_height(self, cur):
        h = 0  # depth starting from 0
        while cur:
            h += 1
            cur = cur.left

        return h

class Solution_TLE:
    def __init__(self):
        self.depth = 0  # depth starts from 1
        self.cnt = 0
        self.stopped = False

    def countNodes(self, root):
        """

        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        self.get_depth(root)
        self.fanthom(root, 1)
        return 2**(self.depth-1)-1+self.cnt

    def get_depth(self, root):
        self.depth += 1
        if root.left:
            self.get_depth(root.left)

    def fanthom(self, root, depth):
        if self.stopped:
            return

        if not root.left and not root.left:
            if self.depth == depth:
                self.cnt += 1
            else:
                self.stopped = True
            return

        if root.left:
            self.fanthom(root.left, depth+1)
        if root.right:
            self.fanthom(root.right, depth+1)

    def countNodes_TLE(self, root):
        """
        Brute Force

        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0

        return 1+self.countNodes(root.left)+self.countNodes(root.right)

if __name__ == "__main__":
    pass


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Syn. meth. fung. (Göttingen) 2: 533 (1801)

#### Original name
Boletus polymorphus Hoffm., 1794

### Remarks
null


text:
<selector xmlns:android="http://schemas.android.com/apk/res/android" android:enterFadeDuration="@android:integer/config_shortAnimTime" android:exitFadeDuration="@android:integer/config_shortAnimTime">

    <item android:drawable="@drawable/card_pressed" android:state_pressed="true" />
    <item android:drawable="@drawable/card_focused" android:state_focused="true"/>
    <item android:drawable="@drawable/card_selected" android:state_selected="true"/>
    <item android:drawable="@drawable/card_default"/>

</selector>


text:
'use strict';

var assert = require('assert');
var greekStemmer = require('../lib');
var YAML = require('yamljs');
var path = require('path');
var examples = YAML.load(path.join(__dirname, './fixtures/examples.yml'));

describe('greek-stemmer', function () {
  describe('stem()', function () {
    it('should stem words in examples properly ', function () {
      for (var word in examples) {
        assert(examples[word], greekStemmer.stem(word));
      }
    });
  });
});

describe('greek-stemmer', function () {
  it('should not stem words not in ', function () {
    assert('STEMMED', greekStemmer.stem('STEMMED'));
  });
});


text:
<?php
/**
 * Message translations for Full crud static messages
 *
 */
return array (
  'Cancel' => 'Atcelt',
  'Create' => 'Izveidot',
  'Data' => 'Dati',
  'Delete' => 'Dzēst',
  'Do you want to delete this item?' => 'Vai patiešam vēlaties šo ierakstu dzēst',
  'Fields with * are required.' => 'Atzīmētie ar * ir obligāti.',
  'Invalid request. Please do not repeat this request again.' => 'Kļūdains pieprasījums.',
  'Manage' => 'Saraksts',
  'Relations' => 'Relācijas',
  'Save' => 'Saglabāt',
  'Search' => 'Meklēt',
  'The requested page does not exist.' => 'Pieprasītā lapa neeksistē',
  'Update' => 'Labot',
  'View' => 'Skatīt',
);


text:
package de.mineformers.investiture.serialisation;

import com.google.common.base.Throwables;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Table;
import de.mineformers.investiture.network.ManualTranslation;
import de.mineformers.investiture.network.Message;
import io.netty.buffer.ByteBuf;
import net.minecraft.entity.Entity;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.*;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import org.apache.commons.lang3.ClassUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
 * Internal handler for all networking serialisation needs.
 *

 * WARNING: This class is an implementation detail and not supposed to be called by anything directly but {@link Message}, so binary incompatible
 * API changes can occur at random.
 */
public class Serialisation
{
    public static final Serialisation INSTANCE = new Serialisation();
    private Map<Class<?>, Translator<?, ?>> translators = new HashMap<>();
    private Multimap<String, FieldData> fields = HashMultimap.create();
    private Table<String, String, Translator<?, ?>> fieldTranslators = HashBasedTable.create();

    /**
     * Constructor that registers default serialisation.
     *

     * It's private because there should only ever be one {@link Serialisation#INSTANCE instance} of this class.
     */
    private Serialisation()
    {
        // String translator
        registerTranslator(String.class, new Translator<String, NBTTagString>()
        {
            @Override
            public void serialiseImpl(String value, ByteBuf buffer)
            {
                ByteBufUtils.writeUTF8String(buffer, value);
            }

            @Override
            public String deserialiseImpl(ByteBuf buffer)
            {
                return ByteBufUtils.readUTF8String(buffer);
            }

            @Override
            public NBTTagString serialiseImpl(String value)
            {
                return new NBTTagString(value);
            }

            @Override
            public String deserialiseImpl(NBTTagString tag)
            {
                return tag.getString();
            }
        });

        // int translator
        registerTranslator(Integer.TYPE, new Translator<Integer, NBTTagInt>()
        {
            @Override
            public void serialiseImpl(Integer value, ByteBuf buffer)
            {
                buffer.writeInt(value);
            }

            @Override
            public Integer deserialiseImpl(ByteBuf buffer)
            {
                return buffer.readInt();
            }

            @Override
            public NBTTagInt serialiseImpl(Integer value)
            {
                return new NBTTagInt(value);
            }

            @Override
            public Integer deserialiseImpl(NBTTagInt tag)
            {
                return tag.getInt();
            }
        });

        // byte translator
        registerTranslator(Byte.TYPE, new Translator<Byte, NBTTagByte>()
        {
            @Override
            public void serialiseImpl(Byte value, ByteBuf buffer)
            {
                buffer.writeByte(value);
            }

            @Override
            public Byte deserialiseImpl(ByteBuf buffer)
            {
                return buffer.readByte();
            }

            @Override
            public NBTTagByte serialiseImpl(Byte value)
            {
                return new NBTTagByte(value);
            }

            @Override
            public Byte deserialiseImpl(NBTTagByte tag)
            {
                return tag.getByte();
            }
        });

        // short translator
        registerTranslator(Short.TYPE, new Translator<Short, NBTTagShort>()
        {
            @Override
            public void serialiseImpl(Short value, ByteBuf buffer)
            {
                buffer.writeShort(value);
            }

            @Override
            public Short deserialiseImpl(ByteBuf buffer)
            {
                return buffer.readShort();
            }

            @Override
            public NBTTagShort serialiseImpl(Short value)
            {
                return new NBTTagShort(value);
            }

            @Override
            public Short deserialiseImpl(NBTTagShort tag)
            {
                return tag.getShort();
            }
        });

        // long translator
        registerTranslator(Long.TYPE, new Translator<Long, NBTTagLong>()
        {
            @Override
            public void serialiseImpl(Long value, ByteBuf buffer)
            {
                buffer.writeLong(value);
            }

            @Override
            public Long deserialiseImpl(ByteBuf buffer)
            {
                return buffer.readLong();
            }

            @Override
            public NBTTagLong serialiseImpl(Long value)
            {
                return new NBTTagLong(value);
            }

            @Override
            public Long deserialiseImpl(NBTTagLong tag)
            {
                return tag.getLong();
            }
        });

        // char translator
        registerTranslator(Character.TYPE, new Translator<Character, NBTTagInt>()
        {
            @Override
            public void serialiseImpl(Character value, ByteBuf buffer)
            {
                buffer.writeChar(value);
            }

            @Override
            public Character deserialiseImpl(ByteBuf buffer)
            {
                return buffer.readChar();
            }

            @Override
            public NBTTagInt serialiseImpl(Character value)
            {
                return new NBTTagInt(value);
            }

            @Override
            public Character deserialiseImpl(NBTTagInt tag)
            {
                return (char) tag.getInt();
            }
        });

        // boolean translator
        registerTranslator(Boolean.TYPE, new Translator<Boolean, NBTTagByte>()
        {
            @Override
            public void serialiseImpl(Boolean value, ByteBuf buffer)
            {
                buffer.writeBoolean(value);
            }

            @Override
            public Boolean deserialiseImpl(ByteBuf buffer)
            {
                return buffer.readBoolean();
            }

            @Override
            public NBTTagByte serialiseImpl(Boolean value)
            {
                return new NBTTagByte((byte) (value ? 1 : 0));
            }

            @Override
            public Boolean deserialiseImpl(NBTTagByte tag)
            {
                return tag.getByte() > 0;
            }
        });

        // float translator
        registerTranslator(Float.TYPE, new Translator<Float, NBTTagFloat>()
        {
            @Override
            public void serialiseImpl(Float value, ByteBuf buffer)
            {
                buffer.writeFloat(value);
            }

            @Override
            public Float deserialiseImpl(ByteBuf buffer)
            {
                return buffer.readFloat();
            }

            @Override
            public NBTTagFloat serialiseImpl(Float value)
            {
                return new NBTTagFloat(value);
            }

            @Override
            public Float deserialiseImpl(NBTTagFloat tag)
            {
                return tag.getFloat();
            }
        });

        // double translator
        registerTranslator(Double.TYPE, new Translator<Double, NBTTagDouble>()
        {
            @Override
            public void serialiseImpl(Double value, ByteBuf buffer)
            {
                buffer.writeDouble(value);
            }

            @Override
            public Double deserialiseImpl(ByteBuf buffer)
            {
                return buffer.readDouble();
            }

            @Override
            public NBTTagDouble serialiseImpl(Double value)
            {
                return new NBTTagDouble(value);
            }

            @Override
            public Double deserialiseImpl(NBTTagDouble tag)
            {
                return tag.getDouble();
            }
        });

        // ItemStack translator
        registerTranslator(ItemStack.class, new Translator<ItemStack, NBTTagCompound>()
        {
            @Override
            public void serialiseImpl(ItemStack value, ByteBuf buffer)
            {
                ByteBufUtils.writeItemStack(buffer, value);
            }

            @Override
            public ItemStack deserialiseImpl(ByteBuf buffer)
            {
                return ByteBufUtils.readItemStack(buffer);
            }

            @Override
            public NBTTagCompound serialiseImpl(ItemStack value)
            {
                NBTTagCompound result = new NBTTagCompound();
                value.writeToNBT(result);
                return result;
            }

            @Override
            public ItemStack deserialiseImpl(NBTTagCompound tag)
            {
                return new ItemStack(tag);
            }
        });

        // NBT compound translator
        registerTranslator(NBTTagCompound.class, new Translator<NBTTagCompound, NBTTagCompound>()
        {
            @Override
            public void serialiseImpl(NBTTagCompound value, ByteBuf buffer)
            {
                ByteBufUtils.writeTag(buffer, value);
            }

            @Override
            public NBTTagCompound deserialiseImpl(ByteBuf buffer)
            {
                return ByteBufUtils.readTag(buffer);
            }

            @Override
            public NBTTagCompound serialiseImpl(NBTTagCompound value)
            {
                return value;
            }

            @Override
            public NBTTagCompound deserialiseImpl(NBTTagCompound tag)
            {
                return tag;
            }
        });

        // Direction translator
        registerTranslator(EnumFacing.class, new Translator<EnumFacing, NBTTagByte>()
        {
            @Override
            public void serialiseImpl(EnumFacing value, ByteBuf buffer)
            {
                buffer.writeInt(value.ordinal());
            }

            @Override
            public EnumFacing deserialiseImpl(ByteBuf buffer)
            {
                return EnumFacing.values()[buffer.readInt()];
            }

            @Override
            public NBTTagByte serialiseImpl(EnumFacing value)
            {
                return new NBTTagByte((byte) value.getIndex());
            }

            @Override
            public EnumFacing deserialiseImpl(NBTTagByte tag)
            {
                return EnumFacing.getFront(tag.getByte());
            }
        });

        // Position translator
        registerTranslator(BlockPos.class, new Translator<BlockPos, NBTTagLong>()
        {
            @Override
            public void serialiseImpl(BlockPos value, ByteBuf buffer)
            {
                buffer.writeLong(value.toLong());
            }

            @Override
            public BlockPos deserialiseImpl(ByteBuf buffer)
            {
                return BlockPos.fromLong(buffer.readLong());
            }

            @Override
            public NBTTagLong serialiseImpl(BlockPos value)
            {
                return new NBTTagLong(value.toLong());
            }

            @Override
            public BlockPos deserialiseImpl(NBTTagLong tag)
            {
                return BlockPos.fromLong(tag.getLong());
            }
        });

        // Vec3 translator
        registerTranslator(Vec3d.class, new Translator<Vec3d, NBTTagCompound>()
        {
            @Override
            public void serialiseImpl(Vec3d value, ByteBuf buffer)
            {
                buffer.writeDouble(value.x);
                buffer.writeDouble(value.y);
                buffer.writeDouble(value.z);
            }

            @Override
            public Vec3d deserialiseImpl(ByteBuf buffer)
            {
                return new Vec3d(buffer.readDouble(), buffer.readDouble(), buffer.readDouble());
            }

            @Override
            public NBTTagCompound serialiseImpl(Vec3d value)
            {
                NBTTagCompound result = new NBTTagCompound();
                result.setDouble("X", value.x);
                result.setDouble("Y", value.y);
                result.setDouble("Z", value.z);
                return result;
            }

            @Override
            public Vec3d deserialiseImpl(NBTTagCompound tag)
            {
                return new Vec3d(tag.getDouble("X"), tag.getDouble("Y"), tag.getDouble("Z"));
            }
        });

        // Byte array translator
        registerTranslator(byte[].class, new Translator<byte[], NBTTagByteArray>()
        {
            @Override
            public void serialiseImpl(byte[] value, ByteBuf buffer)
            {
                buffer.writeInt(value.length);
                buffer.writeBytes(value);
            }

            @Override
            public byte[] deserialiseImpl(ByteBuf buffer)
            {
                byte[] result = new byte[buffer.readInt()];
                buffer.readBytes(result);
                return result;
            }

            @Override
            public NBTTagByteArray serialiseImpl(byte[] value)
            {
                return new NBTTagByteArray(value);
            }

            @Override
            public byte[] deserialiseImpl(NBTTagByteArray tag)
            {
                return tag.getByteArray();
            }
        });

        // Ray trace result translator
        registerTranslator(RayTraceResult.class, new Translator<RayTraceResult, NBTTagCompound>()
        {
            @Override
            public void serialiseImpl(RayTraceResult value, ByteBuf buffer)
            {
                buffer.writeInt(value.typeOfHit.ordinal());
                buffer.writeDouble(value.hitVec.x);
                buffer.writeDouble(value.hitVec.y);
                buffer.writeDouble(value.hitVec.z);
                switch (value.typeOfHit)
                {
                    case ENTITY:
                        buffer.writeInt(value.entityHit.dimension);
                        buffer.writeInt(value.entityHit.getEntityId());
                        break;
                    case BLOCK:
                        buffer.writeInt(value.sideHit.getIndex());
                        buffer.writeInt(value.getBlockPos().getX());
                        buffer.writeInt(value.getBlockPos().getY());
                        buffer.writeInt(value.getBlockPos().getZ());
                        break;
                    default:
                        break;
                }
            }

            @Override
            public RayTraceResult deserialiseImpl(ByteBuf buffer)
            {
                RayTraceResult.Type type = RayTraceResult.Type.values()[buffer.readInt()];
                Vec3d hitVec = new Vec3d(buffer.readDouble(), buffer.readDouble(), buffer.readDouble());
                switch (type)
                {
                    case ENTITY:
                        World world = DimensionManager.getWorld(buffer.readInt());
                        Entity entity = world.getEntityByID(buffer.readInt());
                        return new RayTraceResult(entity, hitVec);
                    case BLOCK:
                        EnumFacing facing = EnumFacing.getFront(buffer.readInt());
                        BlockPos pos = new BlockPos(buffer.readInt(), buffer.readInt(), buffer.readInt());
                        return new RayTraceResult(hitVec, facing, pos);
                    default:
                        return new RayTraceResult(RayTraceResult.Type.MISS, hitVec, null, BlockPos.ORIGIN);
                }
            }

            @Override
            public NBTTagCompound serialiseImpl(RayTraceResult value)
            {
                NBTTagCompound result = new NBTTagCompound();
                result.setInteger("TypeOfHit", value.typeOfHit.ordinal());
                result.setDouble("HitX", value.hitVec.x);
                result.setDouble("HitY", value.hitVec.y);
                result.setDouble("HitZ", value.hitVec.z);
                switch (value.typeOfHit)
                {
                    case ENTITY:
                        result.setInteger("EntityDimension", value.entityHit.dimension);
                        result.setInteger("Entity", value.entityHit.getEntityId());
                        break;
                    case BLOCK:
                        result.setInteger("SideHit", value.sideHit.getIndex());
                        result.setInteger("BlockX", value.getBlockPos().getX());
                        result.setInteger("BlockY", value.getBlockPos().getY());
                        result.setInteger("BlockZ", value.getBlockPos().getZ());
                        break;
                    default:
                        break;
                }
                return result;
            }

            @Override
            public RayTraceResult deserialiseImpl(NBTTagCompound tag)
            {
                RayTraceResult.Type type = RayTraceResult.Type.values()[tag.getInteger("TypeOfHit")];
                Vec3d hitVec = new Vec3d(tag.getDouble("HitX"), tag.getDouble("HitY"), tag.getDouble("HitZ"));
                switch (type)
                {
                    case ENTITY:
                        World world = DimensionManager.getWorld(tag.getInteger("EntityDimension"));
                        Entity entity = world.getEntityByID(tag.getInteger("Entity"));
                        return new RayTraceResult(entity, hitVec);
                    case BLOCK:
                        EnumFacing facing = EnumFacing.getFront(tag.getInteger("SideHit"));
                        BlockPos pos = new BlockPos(tag.getInteger("BlockX"), tag.getInteger("BlockY"), tag.getInteger("BlockZ"));
                        return new RayTraceResult(hitVec, facing, pos);
                    default:
                        return new RayTraceResult(RayTraceResult.Type.MISS, hitVec, null, BlockPos.ORIGIN);
                }
            }
        });

        // Ray trace result translator
        registerTranslator(UUID.class, new Translator<UUID, NBTTagCompound>()
        {
            @Override
            public void serialiseImpl(UUID value, ByteBuf buffer)
            {
                buffer.writeLong(value.getMostSignificantBits());
                buffer.writeLong(value.getLeastSignificantBits());
            }

            @Override
            public UUID deserialiseImpl(ByteBuf buffer)
            {
                return new UUID(buffer.readLong(), buffer.readLong());
            }

            @Override
            public NBTTagCompound serialiseImpl(UUID value)
            {
                NBTTagCompound result = new NBTTagCompound();
                result.setUniqueId("Value", value);
                return result;
            }

            @Override
            public UUID deserialiseImpl(NBTTagCompound tag)
            {
                return tag.getUniqueId("Value");
            }
        });
    }

    /**
     * Internal method for adding a translator to the framework.
     *
     * @param type       the type the translator supports
     * @param translator the translator
     */
    public void registerTranslator(Class<?> type, Translator<?, ?> translator)
    {
        translators.put(type, translator);
    }

    /**
     * Finds a translator for a given type. If there is no direct translation available, the first translator that can handle a super class of the
     * type will be used.
     *
     * @param type the type to find a translator for
     * @return a translator for the given type, either one that directly supports the type or one for a super type
     */
    private Translator<?, ?> findTranslator(Class<?> type)
    {
        // Direct translation available, short circuit
        if (translators.containsKey(type)) return translators.get(type);

        // No direct translation available, we have to find one that fits the type nonetheless
        Optional<Translator<?, ?>> fit = translators.entrySet().stream()
                                                    .filter(e -> e.getKey().isAssignableFrom(type))
                                                    .findFirst()
                                                    .map(Map.Entry::getValue);
        if (fit.isPresent())
        {
            return fit.get();
        }
        else
        // There doesn't seem to be a translator for this type, we can't handle this particular situation gracefully
        {
            throw new RuntimeException("There is no translator for type " + type.getName() + ", consider writing one.");
        }
    }

    /**
     * Collects a list of fields which are supposed to be synchronised over the network.
     *
     * @param type          the type to get the fields from
     * @param onlyAnnotated specifies whether all fields should be synchronised or only those with the {@link Serialise} annotation.
     * @return a set of fields to synchronise
     */
    public Set<FieldData> getNetFields(Class<?> type, boolean onlyAnnotated)
    {
        if (!fields.containsKey(type.getName()))
            registerClass(type, onlyAnnotated);
        return fields.get(type.getName()).stream().filter(f -> f.net).collect(Collectors.toSet());
    }

    /**
     * Registers a message to the serialisation framework. Allows faster serialisation due to caching of the results of intensive reflective
     * operations.
     *
     * @param type the class representing the type of the message
     */
    public void registerClass(Class<?> type, boolean onlyAnnotated)
    {
        StreamSupport
            .stream(ClassUtils.hierarchy(type, ClassUtils.Interfaces.INCLUDE).spliterator(), false)
            .map(Class::getDeclaredFields)
            .flatMap(Arrays::stream)
            .filter(f -> (f.getModifiers() & Modifier.STATIC) == 0)
            .sorted(Comparator.comparing(Field::getName))
            .forEach(f ->
                     {
                         if (f.getAnnotationsByType(ManualTranslation.class).length != 0)
                             return;
                         Serialise serialise = f.getAnnotation(Serialise.class);
                         boolean nbt = true;
                         boolean net = true;
                         if (serialise != null)
                         {
                             nbt = serialise.nbt();
                             net = serialise.net();
                         }
                         else if (onlyAnnotated)
                             return;

                         fields.put(type.getName(), new FieldData(f, nbt, net));
                         // Cache the translator for each field, prevents disparities between different points in time
                         f.setAccessible(true);
                         fieldTranslators.put(type.getName(), f.getName(), findTranslator(f.getType()));
                     });
    }

    /**
     * Serialises an object to a given NBT tag compound, giving each field its own entry.
     *
     * @param object   the object to serialise
     * @param compound the compound to serialise to
     */
    public void serialise(Object object, NBTTagCompound compound)
    {
        String className = object.getClass().getName();
        for (FieldData f : this.fields.get(className))
        {
            if (!f.nbt)
                continue;
            Translator<?, ?> translator = fieldTranslators.get(className, f.name);
            Optional<? extends NBTBase> value = translator.serialise(f.get(object));
            value.ifPresent(v -> compound.setTag(f.name, v));
        }
    }

    /**
     * Deserialises an object from a given NBT tag compound.
     *
     * @param compound the compound to deserialise from
     * @param object   the object to deserialise to
     */
    public void deserialise(NBTTagCompound compound, Object object)
    {
        String className = object.getClass().getName();
        for (FieldData f : this.fields.get(className))
        {
            if (!f.nbt)
                continue;
            Translator<?, ?> translator = fieldTranslators.get(className, f.name);
            f.set(object, translator.deserialise(compound.hasKey(f.name) ? Optional.ofNullable(compound.getTag(f.name))
                                                                         : Optional.empty()));
        }
    }

    /**
     * Serialises each field of a message to a byte buffer, utilising translators that fit each field's type best.
     *
     * @param object the message to serialise
     * @param buffer the buffer to serialise the message into
     */
    public void serialiseFrom(Object object, ByteBuf buffer)
    {
        String className = object.getClass().getName();
        for (FieldData f : this.fields.get(className))
        {
            if (!f.net)
                continue;
            Translator<?, ?> translator = fieldTranslators.get(className, f.name);
            translator.serialise(f.get(object), buffer);
        }
    }

    /**
     * Deserialises the contents of a byte buffer into a message, writing each field utilising translators.
     *
     * @param buffer the buffer to deserialise from
     * @param object the message to deserialise into
     */
    public void deserialiseTo(ByteBuf buffer, Object object)
    {
        String className = object.getClass().getName();
        for (FieldData f : this.fields.get(className))
        {
            if (!f.net)
                continue;
            Translator<?, ?> translator = fieldTranslators.get(className, f.name);
            f.set(object, translator.deserialise(buffer));
        }
    }

    /**
     * Serialises all specified fields of a message to a byte buffer, utilising translators that fit each field's type best.
     *
     * @param object the message to serialise
     * @param fields the fields to serialise
     * @param buffer the buffer to serialise the message into
     */
    public void serialiseFieldsFrom(Object object, Collection<FieldData> fields, ByteBuf buffer)
    {
        String className = object.getClass().getName();
        buffer.writeInt(fields.size());
        for (FieldData f : fields)
        {
            ByteBufUtils.writeUTF8String(buffer, f.name);
            Translator<?, ?> translator = fieldTranslators.get(className, f.name);
            translator.serialise(f.get(object), buffer);
        }
    }

    /**
     * Deserialises the contents of a byte buffer into a message, writing each field utilising translators.
     *
     * @param buffer the buffer to deserialise from
     * @param object the message to deserialise into
     */
    public void deserialiseFieldsTo(ByteBuf buffer, Object object)
    {
        String className = object.getClass().getName();
        int count = buffer.readInt();
        for (int i = 0; i < count; i++)
        {
            String fieldName = ByteBufUtils.readUTF8String(buffer);
            FieldData f = fields.get(className).stream().filter(field -> Objects.equals(field.name, fieldName)).findFirst().get();
            Translator<?, ?> translator = fieldTranslators.get(className, f.name);
            f.set(object, translator.deserialise(buffer));
        }
    }

    public <N extends NBTBase, T> Optional<N> translateToNBT(T o)
    {
        return (Optional<N>) findTranslator(o.getClass()).serialise(o);
    }

    public <T> T translateFromNBT(Class<T> type, Optional<NBTBase> nbt)
    {
        return (T) findTranslator(type).deserialise(nbt);
    }

    public void writeToBuffer(Object o, ByteBuf buffer)
    {
        findTranslator(o.getClass()).serialise(o, buffer);
    }

    public <T> T readFromBuffer(Class<T> type, ByteBuf buffer)
    {
        return (T) findTranslator(type).deserialise(buffer);
    }

    /**
     * Represents any serialisable field.
     */
    public static class FieldData
    {
        public final Field field;
        public final String name;
        public final boolean nbt;
        public final boolean net;

        private FieldData(Field field, boolean nbt, boolean net)
        {
            this.field = field;
            this.name = field.getName();
            this.nbt = nbt;
            this.net = net;
        }

        /**
         * Sets the field to a given value.
         *
         * @param instance the instance the value is to be set in, may be null for static fields
         * @param value    the value to set the field to
         */
        public void set(Object instance, Object value)
        {
            field.setAccessible(true);
            try
            {
                field.set(instance, value);
            }
            catch (IllegalAccessException e)
            {
                e.printStackTrace();
            }
            catch (IllegalArgumentException e)
            {
                Class<?> type = field.getType();
                if (type.equals(byte.class))
                    set(instance, (byte) 0);
                else if (type.equals(short.class))
                    set(instance, (short) 0);
                else if (type.equals(int.class))
                    set(instance, 0);
                else if (type.equals(long.class))
                    set(instance, 0L);
                else if (type.equals(float.class))
                    set(instance, 0f);
                else if (type.equals(double.class))
                    set(instance, 0d);
                else if (type.equals(boolean.class))
                    set(instance, false);
            }
        }

        /**
         * @param instance the instance to get the value from, may be null for static fields
         * @return the value of the field in the given instance
         */
        public Object get(Object instance)
        {
            field.setAccessible(true);
            try
            {
                return field.get(instance);
            }
            catch (IllegalAccessException e)
            {
                Throwables.propagate(e);
            }
            return null;
        }

        @Override
        public int hashCode()
        {
            return Objects.hash(field, nbt, net);
        }

        @Override
        public boolean equals(Object obj)
        {
            if (obj == null)
                return false;
            if (obj.getClass() != this.getClass())
                return false;
            FieldData data = (FieldData) obj;
            return Objects.equals(field, data.field) && nbt == data.nbt && net == data.net;
        }
    }
}


text:
module.exports = function(callback, config) {

  var Nexmo = require('../lib/Nexmo');

  var nexmo = new Nexmo({
    apiKey: config.API_KEY,
    apiSecret: config.API_SECRET
  }, {
    debug: config.DEBUG
  });

  nexmo.number.get({}, callback);
};


text:
<?php

namespace Palor;

require_once('PbFactory.php');
require_once('PbHelper.php');
require_once('Settings.php');
require_once('ChartDrawer.php');

class ActivityClassTimesChartDrawer extends ChartDrawer {

    private $_templateColumn = 'CanvasJS.addColorSet("$$$divName$$$Color", ["$$$colors$$$"]);

var var$$$divName$$$ = new CanvasJS.Chart("$$$divName$$$", {
    title:{ text: "$$$title$$$", fontSize: 24 },
    colorSet: "$$$divName$$$Color",
    legend: {
        verticalAlign: "top",
        horizontalAlign: "center",
        fontSize: 12
    },
    axisX:{
        title: "Date",
        titleFontSize: 14,
        labelFontSize: 12,
        valueFormatString: "$$$dateFormat$$$",
        labelFormatter: function (e) {
            return CanvasJS.formatDate( e.value, "$$$dateFormat$$$");
        },
    },
    axisY:{
        title: "Duration in h",
        titleFontSize: 14,
        labelFontSize: 12,
        maximum: 24,
        interval: 1,
    },
    toolTip:{
        contentFormatter: function ( e ) {
            var content = " ";
            for (var i = 0; i < e.entries.length; i++) {
                content += "Date: ";
                content += CanvasJS.formatDate(e.entries[i].dataPoint.x, "$$$dateFormat$$$");
                content += "<br/>";
                content += e.entries[i].dataSeries.name + ": ";
                content += e.entries[i].dataPoint.y;
                content += " h";
            }
            return content;
        }
    },
    data: [ $$$dataSeries$$$ ]
});
var$$$divName$$$.render();
';

    private $_templateSeries = '{
        type: "stackedColumn",
        showInLegend: true,
        legendText: "$$$legendText$$$index$$$$$$",
        yValueFormatString: "0.0 h",
        dataPoints: [$$$dataPoints$$$index$$$$$$],
        name: "$$$legendText$$$index$$$$$$",
        click: function(e){
            var link = "$$$link$$$&day=" + e.dataPoint.x.getDate();
            link += "&month=" + (e.dataPoint.x.getMonth() + 1);
            link += "&year=" + e.dataPoint.x.getFullYear();
            window.open(link, "_self");
        },
    },';

    public function __construct() {
        parent::setColors(Settings::$CHART_COLOR_EIGHT_DIM);
        parent::setTemplate($this->_templateColumn);
    }

    public function generateColumnChartByDay($dailySummaries,
        $divName, $link, $title = 'Activity class times', $legendText = array('Non wear', 'Sleep', 'Sedentary', 'Light activity', 'Continuous moderate', 'Intermittent moderate', 'Continuous vigorous', 'Intermittent vigorous')) {

        $dataSet = $this->_generateTimesByDate($dailySummaries);

        parent::setTemplate(str_replace('$$$dataSeries$$$',
            $this->_prepareDataSeriesTemplate($dataSet),
            $this->_templateColumn));

        return parent::generateChart($dataSet['x'],
            $dataSet['y'], $divName, $title, $legendText,
            $link);
    }

    private function _prepareDataSeriesTemplate($dataSet) {
        $dataSeries = '';

        foreach ($dataSet['x'] as $xIdx=>$value) {
            $dataSeries .= str_replace('$$$index$$$',
                $xIdx, $this->_templateSeries);
        }

        return $dataSeries;
    }

    private function _generateTimesByDate($dailySummaries) {
        $x = array();
        $y = array();

        for ($i = 0; $i < count($dailySummaries); $i++) {
            if ($dailySummaries[$i] === NULL) {
                continue;
            }

            $timeStr = array(
                'time_non_wear',
                'time_sleep',
                'time_sedentary',
                'time_light_activity',
                'time_continuous_moderate',
                'time_intermittent_moderate',
                'time_continuous_vigorous',
                'time_intermittent_vigorous'
            );

            for ($j = 0; $j < count($timeStr); $j++) {
                $x[$j][$i] = sprintf
                    ('new Date(%d,%d,%d)',
                    $dailySummaries[$i]['date']['year'],
                    $dailySummaries[$i]['date']['month'] - 1,
                    $dailySummaries[$i]['date']['day']);

                $y[$j][$i] = round(PbHelper::toHoursPbDuration(
                    $dailySummaries[$i]['activity_class_times'][$timeStr[$j]]), 1);
            }
        }

        return array('x' => $x, 'y' => $y);
    }
}


text:
<?php

namespace NMEA\Sentence;

use NMEA\AbstractSentence;
use NMEA\DataType;

class BWC extends AbstractSentence
{
    function __construct()
    {
        parent::__construct(DataType::BWC);
    }

    /**
     * @param string $rawSentence
     */
    public function setRawSentence($rawSentence)
    {
        parent::setRawSentence($rawSentence);
        $parts = explode(',', $rawSentence);

        list($val, $checksum) = $this->splitChecksum($parts[12]);

        $this->setValues(array(
            'fix' => $parts[1],
            'latitudOfNextWaypoint' => $parts[2].','.$parts[3],
            'longitudOfNextWaypoint' => $parts[4].','.$parts[5],
            'trueTrackToWaypoint' => $parts[6],
            'trueTrack' => $parts[7],
            'magneticTrackToWaypoint' => $parts[8],
            'magnecticTrack' => $parts[9],
            'rangeToWaypoint' => $parts[10],
            'rangeToWaypointUnit' => $parts[11],
            'waypointId' => $val,
            'checksum' => $checksum,
        ));
    }
}


text:
namespace content {
namespace {

// Default time allowance for the touch ack delay before the touch sequence is
// cancelled, depending on whether the site has a mobile-friendly viewport.
// Note that these constants are effective only when the timeout is supported.
const int kDesktopTouchAckTimeoutDelayMs = 200;
const int kMobileTouchAckTimeoutDelayMs = 1000;

PassthroughTouchEventQueue::Config GetTouchEventQueueConfig() {
  PassthroughTouchEventQueue::Config config;

  config.desktop_touch_ack_timeout_delay =
      base::Milliseconds(kDesktopTouchAckTimeoutDelayMs);
  config.mobile_touch_ack_timeout_delay =
      base::Milliseconds(kMobileTouchAckTimeoutDelayMs);

#if BUILDFLAG(IS_ANDROID)
  // For historical reasons only Android enables the touch ack timeout.
  config.touch_ack_timeout_supported = true;
#else
  config.touch_ack_timeout_supported = false;
#endif

  return config;
}

GestureEventQueue::Config GetGestureEventQueueConfig() {
  GestureEventQueue::Config config;
  ui::GestureConfiguration* gesture_config =
      ui::GestureConfiguration::GetInstance();
  config.debounce_interval =
      base::Milliseconds(gesture_config->scroll_debounce_interval_in_ms());

  config.fling_config.touchscreen_tap_suppression_config.enabled =
      gesture_config->fling_touchscreen_tap_suppression_enabled();
  config.fling_config.touchscreen_tap_suppression_config
      .max_cancel_to_down_time =
      base::Milliseconds(gesture_config->fling_max_cancel_to_down_time_in_ms());

  config.fling_config.touchpad_tap_suppression_config.enabled =
      gesture_config->fling_touchpad_tap_suppression_enabled();
  config.fling_config.touchpad_tap_suppression_config.max_cancel_to_down_time =
      base::Milliseconds(gesture_config->fling_max_cancel_to_down_time_in_ms());

  return config;
}

}  // namespace

InputRouter::Config::Config() {}

InputRouter::Config GetInputRouterConfigForPlatform() {
  InputRouter::Config config;
  config.gesture_config = GetGestureEventQueueConfig();
  config.touch_config = GetTouchEventQueueConfig();
  return config;
}

}  // namespace content


text:
from basics import BaseAttachment

class OOCComands(BaseAttachment):

    character = False

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

        self.action_matrix = [
            ["help", self.do_help,
                "Open the help screen, or receive help on a specific command. \
                \n\tExamples: 'help', 'help quit'"],
            ["quit", self.do_quit, "Quit the game."],
            ["health", self.do_health, "Assess your health.\n\tAliases: 'h'."]
            ]

    def do_help(self, rest):
        output = "Help Information\n\nCOMMAND\tDESCRIPTION"
        for attachment in self.character.attachments:
            output += "\n"
            for action in attachment.action_matrix:
                output += action[0] + "\t" + action[2] + "\n"

        self.character.brain.to_client.append(output)

    def do_quit(self, rest):
        self.character.brain.client.active = False

    def do_health(self, rest):
        self.character.brain.to_client.append("You have " + str(self.character.current_hp) + " hit points.")


text:
package edu.ucsd.coursera.oop;

import processing.core.PApplet;
import de.fhpotsdam.unfolding.UnfoldingMap;
import de.fhpotsdam.unfolding.providers.MBTilesMapProvider;
import de.fhpotsdam.unfolding.utils.MapUtils;

/**
 * This example uses a local MBTiles file. Thus, it does not need an Internet connection to load tiles.
 */
public class OfflineMapApp extends PApplet {

	public static String mbTilesString = "blankLight-1-3.mbtiles";

	UnfoldingMap map;

	public void setup() {
		size(800, 600, OPENGL);

		map = new UnfoldingMap(this, new MBTilesMapProvider(mbTilesString));
		MapUtils.createDefaultEventDispatcher(this, map);
		map.setZoomRange(1, 3);
	}

	public void draw() {
		background(0);
		map.draw();
	}

}


text:
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module    : QStyleOptionMenuItem.hs
    Copyright : (c) David Harley 2010
    Project   : qtHaskell
    Version   : 1.1.4
    Modified  : 2010-09-02 17:02:36

    Warning   : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------

module Qtc.Enums.Gui.QStyleOptionMenuItem (
 QStyleOptionMenuItemStyleOptionType
 , QStyleOptionMenuItemStyleOptionVersion
 , MenuItemType, eDefaultItem, eSeparator, eSubMenu, eScroller, eTearOff, eMargin, eEmptyArea
 , CheckType, eNotCheckable, eExclusive, eNonExclusive
 )
 where

import Qtc.Classes.Base
import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr)
import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int)
import Qtc.Enums.Base
import Qtc.Enums.Classes.Core

data CQStyleOptionMenuItemStyleOptionType a = CQStyleOptionMenuItemStyleOptionType a
type QStyleOptionMenuItemStyleOptionType = QEnum(CQStyleOptionMenuItemStyleOptionType Int)

ieQStyleOptionMenuItemStyleOptionType :: Int -> QStyleOptionMenuItemStyleOptionType
ieQStyleOptionMenuItemStyleOptionType x = QEnum (CQStyleOptionMenuItemStyleOptionType x)

instance QEnumC (CQStyleOptionMenuItemStyleOptionType Int) where
 qEnum_toInt (QEnum (CQStyleOptionMenuItemStyleOptionType x)) = x
 qEnum_fromInt x = QEnum (CQStyleOptionMenuItemStyleOptionType x)
 withQEnumResult x
   = do
     ti <- x
     return $ qEnum_fromInt $ fromIntegral ti
 withQEnumListResult x
   = do
     til <- x
     return $ map qEnum_fromInt til

instance Qcs (QObject c -> QStyleOptionMenuItemStyleOptionType -> IO ()) where
 connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
  = do
    funptr  <- wrapSlotHandler_int slotHandlerWrapper_int
    stptr   <- newStablePtr (Wrap _handler)
    withObjectPtr _qsig_obj $ \cobj_sig ->
      withCWString _qsig_nam $ \cstr_sig ->
      withObjectPtr _qslt_obj $ \cobj_slt ->
      withCWString _qslt_nam $ \cstr_slt ->
      qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
    return ()
  where
    slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
    slotHandlerWrapper_int funptr stptr qobjptr cint
      = do qobj <- qObjectFromPtr qobjptr
           let hint = fromCInt cint
           if (objectIsNull qobj)
            then do when (stptr/=ptrNull)
                      (freeStablePtr (castPtrToStablePtr stptr))
                    when (funptr/=ptrNull)
                      (freeHaskellFunPtr (castPtrToFunPtr funptr))
            else _handler qobj (qEnum_fromInt hint)
           return ()

instance QeType QStyleOptionMenuItemStyleOptionType where
 eType
  = ieQStyleOptionMenuItemStyleOptionType $ 4

data CQStyleOptionMenuItemStyleOptionVersion a = CQStyleOptionMenuItemStyleOptionVersion a
type QStyleOptionMenuItemStyleOptionVersion = QEnum(CQStyleOptionMenuItemStyleOptionVersion Int)

ieQStyleOptionMenuItemStyleOptionVersion :: Int -> QStyleOptionMenuItemStyleOptionVersion
ieQStyleOptionMenuItemStyleOptionVersion x = QEnum (CQStyleOptionMenuItemStyleOptionVersion x)

instance QEnumC (CQStyleOptionMenuItemStyleOptionVersion Int) where
 qEnum_toInt (QEnum (CQStyleOptionMenuItemStyleOptionVersion x)) = x
 qEnum_fromInt x = QEnum (CQStyleOptionMenuItemStyleOptionVersion x)
 withQEnumResult x
   = do
     ti <- x
     return $ qEnum_fromInt $ fromIntegral ti
 withQEnumListResult x
   = do
     til <- x
     return $ map qEnum_fromInt til

instance Qcs (QObject c -> QStyleOptionMenuItemStyleOptionVersion -> IO ()) where
 connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
  = do
    funptr  <- wrapSlotHandler_int slotHandlerWrapper_int
    stptr   <- newStablePtr (Wrap _handler)
    withObjectPtr _qsig_obj $ \cobj_sig ->
      withCWString _qsig_nam $ \cstr_sig ->
      withObjectPtr _qslt_obj $ \cobj_slt ->
      withCWString _qslt_nam $ \cstr_slt ->
      qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
    return ()
  where
    slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
    slotHandlerWrapper_int funptr stptr qobjptr cint
      = do qobj <- qObjectFromPtr qobjptr
           let hint = fromCInt cint
           if (objectIsNull qobj)
            then do when (stptr/=ptrNull)
                      (freeStablePtr (castPtrToStablePtr stptr))
                    when (funptr/=ptrNull)
                      (freeHaskellFunPtr (castPtrToFunPtr funptr))
            else _handler qobj (qEnum_fromInt hint)
           return ()

instance QeVersion QStyleOptionMenuItemStyleOptionVersion where
 eVersion
  = ieQStyleOptionMenuItemStyleOptionVersion $ 1

data CMenuItemType a = CMenuItemType a
type MenuItemType = QEnum(CMenuItemType Int)

ieMenuItemType :: Int -> MenuItemType
ieMenuItemType x = QEnum (CMenuItemType x)

instance QEnumC (CMenuItemType Int) where
 qEnum_toInt (QEnum (CMenuItemType x)) = x
 qEnum_fromInt x = QEnum (CMenuItemType x)
 withQEnumResult x
   = do
     ti <- x
     return $ qEnum_fromInt $ fromIntegral ti
 withQEnumListResult x
   = do
     til <- x
     return $ map qEnum_fromInt til

instance Qcs (QObject c -> MenuItemType -> IO ()) where
 connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
  = do
    funptr  <- wrapSlotHandler_int slotHandlerWrapper_int
    stptr   <- newStablePtr (Wrap _handler)
    withObjectPtr _qsig_obj $ \cobj_sig ->
      withCWString _qsig_nam $ \cstr_sig ->
      withObjectPtr _qslt_obj $ \cobj_slt ->
      withCWString _qslt_nam $ \cstr_slt ->
      qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
    return ()
  where
    slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
    slotHandlerWrapper_int funptr stptr qobjptr cint
      = do qobj <- qObjectFromPtr qobjptr
           let hint = fromCInt cint
           if (objectIsNull qobj)
            then do when (stptr/=ptrNull)
                      (freeStablePtr (castPtrToStablePtr stptr))
                    when (funptr/=ptrNull)
                      (freeHaskellFunPtr (castPtrToFunPtr funptr))
            else _handler qobj (qEnum_fromInt hint)
           return ()

instance QeNormal MenuItemType where
 eNormal
  = ieMenuItemType $ 0
eDefaultItem :: MenuItemType
eDefaultItem
  = ieMenuItemType $ 1
eSeparator :: MenuItemType
eSeparator
  = ieMenuItemType $ 2
eSubMenu :: MenuItemType
eSubMenu
  = ieMenuItemType $ 3
eScroller :: MenuItemType
eScroller
  = ieMenuItemType $ 4
eTearOff :: MenuItemType
eTearOff
  = ieMenuItemType $ 5
eMargin :: MenuItemType
eMargin
  = ieMenuItemType $ 6
eEmptyArea :: MenuItemType
eEmptyArea
  = ieMenuItemType $ 7

data CCheckType a = CCheckType a
type CheckType = QEnum(CCheckType Int)

ieCheckType :: Int -> CheckType
ieCheckType x = QEnum (CCheckType x)

instance QEnumC (CCheckType Int) where
 qEnum_toInt (QEnum (CCheckType x)) = x
 qEnum_fromInt x = QEnum (CCheckType x)
 withQEnumResult x
   = do
     ti <- x
     return $ qEnum_fromInt $ fromIntegral ti
 withQEnumListResult x
   = do
     til <- x
     return $ map qEnum_fromInt til

instance Qcs (QObject c -> CheckType -> IO ()) where
 connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
  = do
    funptr  <- wrapSlotHandler_int slotHandlerWrapper_int
    stptr   <- newStablePtr (Wrap _handler)
    withObjectPtr _qsig_obj $ \cobj_sig ->
      withCWString _qsig_nam $ \cstr_sig ->
      withObjectPtr _qslt_obj $ \cobj_slt ->
      withCWString _qslt_nam $ \cstr_slt ->
      qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
    return ()
  where
    slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
    slotHandlerWrapper_int funptr stptr qobjptr cint
      = do qobj <- qObjectFromPtr qobjptr
           let hint = fromCInt cint
           if (objectIsNull qobj)
            then do when (stptr/=ptrNull)
                      (freeStablePtr (castPtrToStablePtr stptr))
                    when (funptr/=ptrNull)
                      (freeHaskellFunPtr (castPtrToFunPtr funptr))
            else _handler qobj (qEnum_fromInt hint)
           return ()

eNotCheckable :: CheckType
eNotCheckable
  = ieCheckType $ 0
eExclusive :: CheckType
eExclusive
  = ieCheckType $ 1
eNonExclusive :: CheckType
eNonExclusive
  = ieCheckType $ 2


text:
This directory contains a suite of test cases for the Skylark language plugin
for Gazelle.

Please note that there are no `BUILD` or `BUILD.bazel` files in subdirs, insted
there are `BUILD.in` and `BUILD.out` describing what the `BUILD` should look
like initially and what the `BUILD` file should look like after the run. These
names are special because they are not recognized by Bazel as a proper `BUILD`
file, and therefore are included in the data dependency by the recursive data
glob in `//gazelle:go_default_test`. If you would like to include any extremely
complicated tests that contain proper `BUILD` files you will need to manually
add them to the `//gazelle:go_default_test` target's `data` section.

## `simple`

Simple is a base test case that was used to validate the parser.

## `nobuildfiles`

A test just like `simple` that has no `BUILD` files at the beginning.

## `import`

Import is a test case that imports a `.bzl` from the same directory.

## `multidir`

Multidir is a test that has a `.bzl` that imports from a different dirrectory.

## `tests`

Using the skylib as an example, this test has `.bzl` files that end in
`_tests.bzl` which are `load`ed into `BUILD` files and never imported by
another repo.

## `private`

Using the skylib as an example, this test has `.bzl` files that live in a
directory called `private` which is used to indicate that they are repo private.
Note that this is distict from the expectations of go's `internal` where the
relative position in the hierarchy determines the visibility.

## `defaultvisibility`

If the package declares a `default_visibility` the generated `bzl_library`
should not set its own `visibility`.

## `external`

This test demonstrates that if you load from another repo, it is able to
generate a `deps` entry for the dependency.

## `empty`

Gazelle has the ability to remove old and unused targets. Test that.


text:
<?php

/**
 * This code was generated by
 * \ / _    _  _|   _  _
 * | (_)\/(_)(_|\/| |(/_  v1.0.0
 * /       /
 */

namespace Twilio\Rest\Studio\V1\Flow\Engagement\Step;

use Twilio\ListResource;
use Twilio\Version;

class StepContextList extends ListResource {
    /**
     * Construct the StepContextList
     *
     * @param Version $version Version that contains the resource
     * @param string $flowSid The SID of the Flow
     * @param string $engagementSid The SID of the Engagement
     * @param string $stepSid Step SID
     * @return \Twilio\Rest\Studio\V1\Flow\Engagement\Step\StepContextList
     */
    public function __construct(Version $version, $flowSid, $engagementSid, $stepSid) {
        parent::__construct($version);

        // Path Solution
        $this->solution = array(
            'flowSid' => $flowSid,
            'engagementSid' => $engagementSid,
            'stepSid' => $stepSid,
        );
    }

    /**
     * Constructs a StepContextContext
     *
     * @return \Twilio\Rest\Studio\V1\Flow\Engagement\Step\StepContextContext
     */
    public function getContext() {
        return new StepContextContext(
            $this->version,
            $this->solution['flowSid'],
            $this->solution['engagementSid'],
            $this->solution['stepSid']
        );
    }

    /**
     * Provide a friendly representation
     *
     * @return string Machine friendly representation
     */
    public function __toString() {
        return '[Twilio.Studio.V1.StepContextList]';
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <artifactId>odata-server-osgi-sample</artifactId>
  <packaging>bundle</packaging>
  <name>${project.artifactId}</name>

  <parent>
    <groupId>org.apache.olingo</groupId>
    <artifactId>odata-samples</artifactId>
    <version>4.3.0-SNAPSHOT</version>
    <relativePath>../..</relativePath>
  </parent>

  <dependencies>
    <dependency>
      <groupId>org.apache.geronimo.specs</groupId>
      <artifactId>geronimo-servlet_3.0_spec</artifactId>
      <version>1.0</version>
    </dependency>

    <dependency>
      <groupId>org.apache.olingo</groupId>
      <artifactId>odata-server-api</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.olingo</groupId>
      <artifactId>odata-server-core</artifactId>
      <version>${project.version}</version>
    </dependency>

    <dependency>
      <groupId>org.apache.olingo</groupId>
      <artifactId>odata-commons-api</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.olingo</groupId>
      <artifactId>odata-commons-core</artifactId>
      <version>${project.version}</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.7</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <executions>
          <execution>
            <id>add-source</id>
            <phase>generate-sources</phase>
            <goals>
              <goal>add-source</goal>
            </goals>
            <configuration>
              <sources>
                <source>${basedir}/../../server/src/main</source>
              </sources>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <extensions>true</extensions>
        <configuration>
          <instructions>
            <Export-Package>
            </Export-Package>
            <Import-Package>
              org.apache.olingo.server.api*,
              org.apache.catalina;resolution:=optional,
              org.apache.catalina.comet;resolution:=optional,
              org.eclipse.jetty.continuation;resolution:=optional,
              org.eclipse.jetty.server;resolution:=optional,
              org.eclipse.jetty.util.ssl;resolution:=optional,
              *
            </Import-Package>
            <_wab>${basedir}/../../server/src/main/webapp/</_wab>
            <Web-ContextPath>olingo-cars</Web-ContextPath>
          </instructions>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


text:
package com.beng.anytopic.c;

import java.util.List;

import com.beng.anytopic.App;

import lombok.extern.slf4j.Slf4j;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequest;

@Slf4j
public class PathSnooper extends HttpObjectAggregator {

	public PathSnooper(int maxContentLength) {
		super(maxContentLength);
	}

	@Override
	protected void decode(ChannelHandlerContext ctx, HttpObject msg, List<Object> out) throws Exception {
		if(msg instanceof HttpRequest) {
			HttpRequest req = (HttpRequest) msg;
			ctx.channel().attr(App.CHANNEL_PATH).set(req.getUri());
		}
		super.decode(ctx, msg, out);
	}

}