text:
package org.metaborg.intellij.idea.parsing;

import java.util.List;

import javax.annotation.Nullable;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.vfs2.FileObject;
import org.metaborg.core.MetaborgRuntimeException;
import org.metaborg.core.language.ILanguageImpl;
import org.metaborg.core.project.IProject;
import org.metaborg.core.source.ISourceRegion;
import org.metaborg.core.style.IRegionCategory;
import org.metaborg.core.style.IRegionStyle;
import org.metaborg.core.style.IStyle;
import org.metaborg.core.syntax.ParseException;
import org.metaborg.intellij.IntRange;
import org.metaborg.intellij.idea.parsing.elements.SpoofaxTokenType;
import org.metaborg.intellij.idea.parsing.elements.SpoofaxTokenTypeManager;
import org.metaborg.intellij.logging.InjectLogger;
import org.metaborg.spoofax.core.style.ISpoofaxCategorizerService;
import org.metaborg.spoofax.core.style.ISpoofaxStylerService;
import org.metaborg.spoofax.core.syntax.ISpoofaxSyntaxService;
import org.metaborg.spoofax.core.syntax.JSGLRParserConfiguration;
import org.metaborg.spoofax.core.unit.ISpoofaxInputUnit;
import org.metaborg.spoofax.core.unit.ISpoofaxInputUnitService;
import org.metaborg.spoofax.core.unit.ISpoofaxParseUnit;
import org.metaborg.spoofax.core.unit.ISpoofaxUnitService;
import org.metaborg.util.log.ILogger;
import org.spoofax.interpreter.terms.IStrategoTerm;

import com.google.common.collect.Lists;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import com.intellij.lexer.LexerBase;
import com.intellij.psi.tree.IElementType;

/**
 * Adapts the Spoofax SGLR parser to allow it to be used as an IntelliJ IDEA highlighting lexer.
 *
 * When {@link #start} is called, this lexer parses the whole input using the SGLR parser. The resulting tokens are
 * stored as {@link SpoofaxToken} objects from which each IntelliJ IDEA token is created when requested.
 *
 * This class is not thread-safe. Since IntelliJ IDEA will try to highlight multiple files simultaneously from different
 * threads, we have to construct a new lexer for each. As we're creating a lexer for each file, we might as well store
 * the file's information.
 */
public final class SpoofaxHighlightingLexer extends LexerBase {
    // Whether to show debug info from the lexer.
    private static final boolean DEBUG_INFO = false;

    private final @Nullable
    FileObject file;
    private final @Nullable IProject project;
    private final ILanguageImpl languageImpl;
    private final JSGLRParserConfiguration parserConfiguration;
    private final SpoofaxTokenTypeManager tokenTypesManager;
    private final ISpoofaxInputUnitService inputUnitService;
    private final ISpoofaxSyntaxService syntaxService;
    private final ISpoofaxCategorizerService categorizer;
    private final ISpoofaxStylerService styler;
    private final ISpoofaxUnitService unitService;
    @InjectLogger
    private ILogger logger;

    // The character buffer.
    private CharSequence buffer;
    // The range of characters in the buffer to lex.
    private IntRange bufferRange;
    // A list of tokens gathered from the lexed characters.
    private final List<SpoofaxToken> tokens = Lists.newArrayList();
    // The current index in {@link #tokens}.
    private int tokenIndex;

    @Inject
    private SpoofaxHighlightingLexer(@Assisted @Nullable FileObject file, @Assisted @Nullable IProject project,
                                     @Assisted ILanguageImpl languageImpl, @Assisted SpoofaxTokenTypeManager tokenTypesManager,
                                     ISpoofaxInputUnitService inputUnitService, ISpoofaxSyntaxService syntaxService,
                                     ISpoofaxCategorizerService categorizer, ISpoofaxStylerService styler,
                                     JSGLRParserConfiguration parserConfiguration, ISpoofaxUnitService unitService) {
        this.file = file;
        this.project = project;
        this.languageImpl = languageImpl;
        this.parserConfiguration = parserConfiguration;
        this.tokenTypesManager = tokenTypesManager;
        this.inputUnitService = inputUnitService;
        this.syntaxService = syntaxService;
        this.categorizer = categorizer;
        this.styler = styler;
        this.unitService = unitService;
    }

    /**
     * Initiates a lexing session.
     *
     * @param inputBuffer
     *            The character sequence to lex.
     * @param startOffset
     *            The inclusive start offset.
     * @param endOffset
     *            The exclusive end offset.
     * @param initialState
     *            Not used. Must be zero.
     */
    @Override public final void start(final CharSequence inputBuffer, final int startOffset, final int endOffset,
        final int initialState) {
        assert initialState == 0;
        assert 0 <= startOffset && startOffset <= inputBuffer.length();
        assert 0 <= endOffset && endOffset <= inputBuffer.length();

        this.buffer = inputBuffer;
        this.bufferRange = IntRange.between(startOffset, endOffset);
        this.tokenIndex = 0;
        this.tokens.clear();

        if(inputBuffer.length() == 0)
            return;

        this.logger.debug("Parsing ({} characters) to get requested range {} from file: {}", inputBuffer.length(),
                this.bufferRange, this.file);

        final ISpoofaxParseUnit result = parseAll();

        this.logger.debug("Tokenizing the parse result of file: {}", this.file);

        tokenizeAll(result);
    }

    /**
     * Parses the whole buffer.
     *
     * @return The parse result.
     */
    private ISpoofaxParseUnit parseAll() {
        // TODO: Optimize parsing? Is there a parse cache? I think so.
        final ISpoofaxInputUnit input =
            inputUnitService.inputUnit(file, buffer.toString(), languageImpl, null, parserConfiguration);
        try {
            return syntaxService.parse(input);
        } catch(final AssertionError e) {
            logger.error("Assertion failed in parser", e);
            return this.unitService.emptyParseUnit(input);
        } catch(final ParseException e) {
            throw new MetaborgRuntimeException("Unhandled exception", e);
        }
    }

    /**
     * Uses the Spoofax tokenizer to tokenize the parse result, and adds the tokens to the list of tokens.
     *
     * @param result
     *            The parse result to tokenize.
     */
    private void tokenizeAll(ISpoofaxParseUnit result) {
        if(!result.valid()) {
            // An invalid parse result might occur when the input contains an error,
            // and recovery fails or is disabled.
            logger.info("Cannot categorize input of {}, parse result is empty", languageImpl);

            // Return a single token covering all input.
            final IntRange tokenRange = IntRange.between(0, buffer.length());
            final SpoofaxTokenType styledTokenType =
                tokenTypesManager.getTokenType(tokenTypesManager.getDefaultStyle());
            final SpoofaxToken spoofaxToken = new SpoofaxToken(styledTokenType, tokenRange);
            tokens.add(spoofaxToken);
            return;
        }

        // This uses the stratego term tokenizer.

        // Found here:
        // https://github.com/metaborg/spoofax/blob/master/org.metaborg.spoofax.core/src/main/java/org/metaborg/spoofax/core/style/CategorizerService.java#L48

        final Iterable<IRegionCategory<IStrategoTerm>> categorizedTokens = categorizer.categorize(languageImpl, result);
        final Iterable<IRegionStyle<IStrategoTerm>> styledTokens = styler.styleParsed(languageImpl, categorizedTokens);

        for (IRegionStyle<IStrategoTerm> currentRegionStyle : styledTokens) {

            // ASSUME: The list of regions is ordered by offset.
            // ASSUME: No region overlaps another region.
            // ASSUME: Every character in the input is covered by a region.
            ISourceRegion currentRegion = currentRegionStyle.region();
            final IntRange tokenRange = IntRange.between(currentRegion.startOffset(), currentRegion.endOffset() + 1);

            if(tokenRange.overlapsRange(bufferRange)) {
                // ASSUME: The styled tokens are ordered by offset.
                // ASSUME: No styled region overlaps another styled region.

                // Get the style of the token
                @Nullable final IStyle tokenStyle =
                    currentRegion.startOffset() <= tokenRange.start ? currentRegionStyle.style() : null;
                final SpoofaxTokenType styledTokenType = tokenTypesManager.getTokenType(tokenStyle);

                final SpoofaxToken spoofaxToken = new SpoofaxToken(styledTokenType, tokenRange);
                tokens.add(spoofaxToken);

                if(DEBUG_INFO) {
                    if(tokenStyle != null) {
                        logger.trace("Token {} with style: {}", printToken(tokenRange), tokenStyle);
                    } else {
                        logger.trace("Token {} with default style: {}", printToken(tokenRange),
                            tokenTypesManager.getDefaultStyle());
                    }
                }
            } else {
                // Token is not in the requested range. No need to style it.

                if(DEBUG_INFO) {
                    logger.trace("Token {} outside requested range.", printToken(tokenRange));
                }
            }
        }
    }

    /**
     * Return a string representation of a token, for debugging and logging.
     *
     * @param tokenRange
     *            The token range.
     * @return The string representation.
     */
    private String printToken(final IntRange tokenRange) {
        return logger.format("\"{}\" @ {}",
            StringEscapeUtils.escapeJava(buffer.subSequence(tokenRange.start, tokenRange.end).toString()), tokenRange);
    }

    /**
     * Gets the range of the last added token, for debugging and logging.
     *
     * @return The range of the last added token, or an empty range if there is none.
     */
    private IntRange getLastTokenRange() {
        if(tokens.isEmpty()) {
            return IntRange.EMPTY;
        } else {
            return tokens.get(tokens.size() - 1).range();
        }
    }

    /**
     * Gets the current state of the lexer.
     *
     * @return An integer that indicates the current state.
     */
    @Override public int getState() {
        // Unused: always zero.
        return 0;
    }

    /**
     * The current token type, or null.
     *
     * @return The current token type, or null when lexing is finished.
     */
    @Nullable @Override public IElementType getTokenType() {
        if(0 <= tokenIndex && tokenIndex < tokens.size())
            return tokens.get(tokenIndex).type();
        else
            return null;
    }

    /**
     * Gets the start of the current token.
     *
     * @return The zero-based offset of the start of the current token in the character buffer.
     */
    @Override public int getTokenStart() {
        assert 0 <= tokenIndex && tokenIndex < tokens.size();
        return tokens.get(tokenIndex).range().start;
    }

    /**
     * Gets the end of the current token.
     *
     * @return The zero-based offset of the end of the current token in the character buffer.
     */
    @Override public int getTokenEnd() {
        assert 0 <= tokenIndex && tokenIndex < tokens.size();
        return tokens.get(tokenIndex).range().end;
    }

    /**
     * Advance the lexer to the next token.
     */
    @Override public void advance() {
        tokenIndex++;
    }

    /**
     * Gets the character buffer.
     *
     * @return The character buffer.
     */
    @Override public CharSequence getBufferSequence() {
        return buffer;
    }

    /**
     * Gets the end of the relevant range of characters.
     *
     * @return The zero-based offset of the end of the relevant range of characters in the character buffer.
     */
    @Override public int getBufferEnd() {
        return bufferRange.end;
    }
}


text:
class AntimalwareCommon
    #region Protection Status Codes and Rankings
    ThreatDetectedProtectionCode = [550, "Threat Detected"]
    UnknownProtectionCode = [ 470, "Unknown" ]
    NotReportingProtectionCode = [ 450, "Not Reporting" ]
    ActionRequiredProtectionCode = [ 350, "Action Required" ]
    NoRealTimeProtectionProtectionCode = [ 270, "No real time protection" ]
    SignaturesOutOfDateProtectionCode = [ 250, "Signatures out of date" ]
    RealTimeProtectionCode = [ 150, "Real time protection" ]
    #endregion

    #region Threat Status Codes and Rankings
    ActiveThreatCode = [ 550, "Active" ]
    UnknownThreatCode = [ 470, "Unknown" ]
    RemediatedThreatThreatCode = [ 370, "Remediated" ]
    QuarantinedThreatCode = [ 350, "Quarantined" ]
    BlockedThreatCode = [ 330, "Blocked" ]
    AllowedThreatCode = [ 250, "Allowed" ]
    NoThreatsDetectedThreatCode = [ 150, "No threats detected" ]
    #endregion
end

redpajama_set_name: RedPajamaGithub


text:
module SpreeCore::Ext::String
  def is_integer?
    begin
      Integer(self.to_s)
      return true
    rescue ArgumentError
      return false
    end
  end
end


text:
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE Arrows #-}
{-# LANGUAGE TupleSections #-}
{-# OPTIONS -fno-warn-orphans #-}

module Main (main) where

import Control.Auto
import Control.Auto.Blip
import Control.Auto.Serialize
import Control.Auto.Switch
import Control.Concurrent
import Control.Exception
import Control.Monad
import Control.Monad.IO.Class
import Data.Map.Strict                 (Map)
import Data.Serialize
import Data.Time
import Network.SimpleIRC
import Prelude hiding                  ((.), id)
import qualified Data.ByteString.Char8 as C8
import qualified Data.Map.Strict       as M

-- | Types

-- A Chat bot; takes in a message and outputs a map of (Channel, Messages)
--   pairs
type ChatBot m = Auto m InMessage OutMessages
-- A simplified chat bot which only outputs messages to the channel it
--   received the incoming message from
type ChatBot' m = Auto m InMessage (Blip [Message])

type Nick    = String
type Channel = String
type Message = String

data InMessage = InMessage { _inMessageNick   :: Nick
                           , _inMessageBody   :: Message
                           , _inMessageSource :: Channel
                           , _inMessageTime   :: UTCTime
                           } deriving Show

-- Output map; the keys are channels and the values are messages to send to
--   each channel.
data OutMessages = OutMessages (Map Channel [Message])

instance Monoid OutMessages where
    mempty  = OutMessages M.empty
    mappend (OutMessages m1) (OutMessages m2)
            = OutMessages (M.unionWith (++) m1 m2)

-- config
botName :: Nick
botName = "autobot-test"

channels :: [Channel]
channels = ["#autobot-test"]

chatbotFP :: FilePath
chatbotFP = "data/save/chatbot"

-- main
main :: IO ()
main = launchIRC chatBot

-- The bot!  Basically a monoid sum of smaller bots.  Note that each
--   component bot is selectively serialized.
chatBot :: ChatBot IO
chatBot = mconcat [ s "seen"  $ perRoom seenBot     -- seenBot, self-serializing
                  ,             perRoom karmaBot
                  , s "ann"             announceBot
                  ]
  where
    -- transforms an Auto into a self-serializing and self-reloading Auto,
    --   saving at that given filepath.
    s fp = serializing' (chatbotFP ++ "-" ++ fp)

-- Helper function to transform a Chatbot' into a Chatbot --- chatbots
--   written for single-channel intput/output to multi-channel-aware
--   input/output.
perRoom :: Monad m => ChatBot' m -> ChatBot m
perRoom cb' = proc im -> do
    outs <- fromBlips [] . cb' -< im
    id -< OutMessages $ M.singleton (_inMessageSource im) outs

-- | The Modules/bots

-- seenBot: Maintains a map of nicks and their last received message.  On
--   the command '@seen [nick]', looks up that nick and reports the last
--   seen time.
seenBot :: Monad m => ChatBot' m
seenBot = proc (InMessage nick msg _ time) -> do
    -- seens :: Map Nick UTCTime
    -- Map containing last time each nick has spoken.  Uses `accum` and the
    --   helper function `addToMap` to update the Map on every message.
    seens <- accum addToMap M.empty -< (nick, time)

    -- query :: Blip Nick
    -- blip stream emits whenever someone queries for a last time seen;
    -- emits with the nick queried for
    query <- emitJusts getRequest -< words msg

        -- a function to get a response from a nick query
    let respond :: Nick -> [Message]
        respond qry = case M.lookup qry seens of
                        Just t  -> [qry ++ " last seen at " ++ show t ++ "."]
                        Nothing -> ["No record of " ++ qry ++ "."]

    -- output is, whenever the `query` stream emits, map `respond` to it.
    id -< respond <$> query
  where
    addToMap :: Map Nick UTCTime -> (Nick, UTCTime) -> Map Nick UTCTime
    addToMap mp (nick, time) = M.insert nick time mp
    getRequest ("@seen":request:_) = Just request
    getRequest _                   = Nothing

-- karmaBot: Maintains a map of nicks and associated "karma", imaginary
--   internet points. --- users can increase a nick's karma by saying
--   `@addKarma [nick]`...can subtract by saying `@subKarma [nick]`...or
--   just query the map by saying `@karma [nick]`.  In all cases, the
--   current karma is reported.
karmaBot :: Monad m => ChatBot' m
karmaBot = proc (InMessage _ msg _ _) -> do
    -- karmaBlip :: Blip (Nick, Int)
    -- blip stream emits when someone modifies karma, with nick and increment
    karmaBlip <- emitJusts getComm -< msg

    -- karmas :: Map Nick Int
    -- keeps track of the total karma for each user by updating with karmaBlip
    karmas    <- scanB updateMap M.empty -< karmaBlip

    -- function to look up a nick, if one is asked for
    let lookupKarma :: Nick -> [Message]
        lookupKarma nick = let karm = M.findWithDefault 0 nick karmas
                           in  [nick ++ " has a karma of " ++ show karm ++ "."]

    -- output is, whenever `karmaBlip` stream emits, look up the result
    id -< lookupKarma . fst <$> karmaBlip
  where
    getComm :: String -> Maybe (Nick, Int)
    getComm msg = case words msg of
                    "@addKarma":nick:_ -> Just (nick, 1 )
                    "@subKarma":nick:_ -> Just (nick, -1)
                    "@karma":nick:_    -> Just (nick, 0)
                    _                  -> Nothing
    updateMap :: Map Nick Int -> (Nick, Int) -> Map Nick Int
    updateMap mp (nick, change) = M.insertWith (+) nick change mp

-- announceBot: Listen on all channels (including private messages) for
--   announcements of the form `@ann [message]`; when received, broadcast
--   the message to all channels the bot is in.  However, rate-limit the
--   broadcasts and only allow 3 announcements per day per user, reset
--   every day at midnight.
announceBot :: forall m. Monad m => ChatBot m
announceBot = proc (InMessage nick msg src time) -> do
    -- annBlip :: Blip [Message]
    -- blip stream emits when someone wants an echo, with the message
    annBlip <- emitJusts getAnnounce -< (nick, msg)

    -- newDayBlip :: Blip UTCTime
    -- blip stream emits whenever the day changes
    newDayBlip <- onChange           -< utctDay time

    -- annCounts :: Map Nick Int
    -- `countEchos` counts the number of times each user asks for an echo, and
    -- `resetOn` makes it "reset" itself whenever `newDayBlip` emits.
    annCounts <- resetOn countAnns -< (nick <$ annBlip, newDayBlip)

        -- has this user flooded today...?
    let hasFlooded = M.lookup nick annCounts > Just floodLimit
        -- toRooms :: Blip [Message]
        -- blip stream emits whenever someone asks for an echo, limiting flood
        outMsg  | hasFlooded = ["No flooding!"] <$ annBlip
                | otherwise  = annBlip
        -- targets :: [Channel]
        -- the rooms to announce to.  if flooded, only echo back to source.
        targets | hasFlooded = [src]
                | otherwise  = channels

        -- outputs :: Blip (Map Channel [Message])
        -- blip stream that emits a map of messages to send to each
        -- channel.
        outputs = M.fromList . zip targets . repeat <$> outMsg

    -- when 'outputs' is not emitting, just pop out an empty 'OutMessages'.
    -- Otherwise, make one from the 'Map' that was emitted.
    fromBlipsWith mempty OutMessages -< outputs
  where
    getAnnounce :: (Nick, Message) -> Maybe [Message]
    getAnnounce (nick, msg) =
        case words msg of
          "@ann":ann -> Just [nick ++ " says \"" ++ unwords ann ++ "\"."]
          _          -> Nothing
    floodLimit = 5
    isEcho msg = case words msg of
                   "@echo":xs -> Just [unwords xs]
                   _          -> Nothing
    countAnns :: Auto m (Blip Nick) (Map Nick Int)
    countAnns = scanB countingFunction M.empty
    countingFunction :: Map Nick Int -> Nick -> Map Nick Int
    countingFunction mp nick = M.insertWith (+) nick 1 mp

-- | Serialize instances for the time types.
instance Serialize UTCTime where
    get = read <$> get      -- haha don't do this in real life.
    put = put . show

instance Serialize Day where
    get = ModifiedJulianDay <$> get
    put = put . toModifiedJulianDay

-- | Boring low-level MIRC stuff; mostly stuff from the simpleirc library.
--   Don't worry about this too much :)  For more information, read the
--   simpleirc documentation.

-- ircConf: IRC configuration for simpleirc.  Specifies server, name,
--   channels, and the Privmsg handler.
ircConf :: MVar (ChatBot IO) -> IrcConfig
ircConf a = (mkDefaultConfig "irc.freenode.org" botName)
              { cChannels = channels
              , cEvents   = [Privmsg (onMessage a)]
              }

-- begin the IRC process with stdout logging.
launchIRC :: ChatBot IO -> IO ()
launchIRC a0 = do
    amvr <- newMVar a0
    let launch = connect (ircConf amvr) False True
    void launch `catch` \(_ :: AsyncException) -> return ()

-- onMessage: the Privmsg handler.  On every Privmsg, pull the Auto out of
--   the MVar, step it to get the results, and put the modified Auto back
--   into the MVar.  Check out the documentation for simpleirc and
--   `Control.Concurrent` for more information.
onMessage :: MVar (ChatBot IO) -> EventFunc
onMessage amvr server msg = do
    OutMessages resps <- modifyMVar amvr $ \a ->
      case (mNick msg, mOrigin msg) of
        (Just nick, Just orig) -> do
          t <- getCurrentTime
          let inmsg = InMessage (C8.unpack nick) (C8.unpack (mMsg msg))
                                (C8.unpack orig) t
          (out, a') <- stepAuto a inmsg
          return (a', out   )
        _   ->
          return (a , mempty)
    _ <- flip M.traverseWithKey resps $ \k v ->
        mapM_ (sendMsg server (C8.pack k) . C8.pack) v
    return ()


text:
angular.module('app.coverart', [
  'app.coverart.archive',
  'app.coverart.lastfm',
  'app.coverart.mopidy'
]);


text:
// Copyright (c) 2004 Brian Wellington (bwelling@xbill.org)

package org.xbill.DNS;

import java.io.*;

/**
 * X.400 mail mapping record.
 *
 * @author Brian Wellington
 */

public class PXRecord extends Record {

private static final long serialVersionUID = 1811540008806660667L;

private int preference;
private Name map822;
private Name mapX400;

PXRecord() {}

Record
getObject() {
	return new PXRecord();
}

/**
 * Creates an PX Record from the given data
 * @param preference The preference of this mail address.
 * @param map822 The RFC 822 component of the mail address.
 * @param mapX400 The X.400 component of the mail address.
 */
public
PXRecord(Name name, int dclass, long ttl, int preference,
	 Name map822, Name mapX400)
{
	super(name, Type.PX, dclass, ttl);

	this.preference = checkU16("preference", preference);
	this.map822 = checkName("map822", map822);
	this.mapX400 = checkName("mapX400", mapX400);
}

void
rrFromWire(DNSInput in) throws IOException {
	preference = in.readU16();
	map822 = new Name(in);
	mapX400 = new Name(in);
}

void
rdataFromString(Tokenizer st, Name origin) throws IOException {
	preference = st.getUInt16();
	map822 = st.getName(origin);
	mapX400 = st.getName(origin);
}

/** Converts the PX Record to a String */
public String rrToString() {
	StringBuffer sb = new StringBuffer();
	sb.append(preference);
	sb.append(" ");
	sb.append(map822);
	sb.append(" ");
	sb.append(mapX400);
	return sb.toString();
}

void
rrToWire(DNSOutput out, Compression c, boolean canonical) {
	out.writeU16(preference);
	map822.toWire(out, null, canonical);
	mapX400.toWire(out, null, canonical);
}

/** Gets the preference of the route. */
public int
getPreference() {
	return preference;
}

/** Gets the RFC 822 component of the mail address. */
public Name
getMap822() {
	return map822;
}

/** Gets the X.400 component of the mail address. */
public Name
getMapX400() {
	return mapX400;
}

}


text:
Sections
========

Word supports the notion of a *section*, having distinct page layout settings.
This is how, for example, a document can contain some pages in portrait layout
and others in landscape. Section breaks are implemented completely differently
from line, page, and column breaks. The former adds a ``<w:pPr><w:sectPr>``
element to the last paragraph in the new section. The latter inserts
a ``<w:br>`` element in a run.

Implementation notes
--------------------

It's probably not going to make a lot of sense to implement this before having
the ability to set at least a core subset of the section properties. First ones
are probably:

* page size
* margins

The other thing it will entail is locating the next ``<w:sectPr>`` element in
document order and copying its child elements.

I'm thinking the sequence is:

1. document.sections
2. section page setup properties
3. paragraph.make_section_break() (or whatever, something better perhaps)

Candidate protocol
------------------

The following interactive session demonstrates the protocol for working with
sections::

    >>> sections = document.sections
    >>> len(sections)
    3
    >>> first_section = sections[0]
    >>> last_section = sections[-1]

    >>> p = body.add_paragraph()
    >>> p.section_properties
    None
    >>> p.add_section_break()

Word behavior
-------------

When inserting a section break in Word, there is no dialog box presented and no
parameters are supplied. Word simply copies the section details from the
current section (the next ``<w:sectPr>`` element in the document) to provide
the starting point. Experimentation would be required to determine exactly what
items are copied, but it at least includes the page size, margins, and column
spacing.

Specimen XML
------------

.. highlight:: xml

Inserting a section break (next page) produces this XML::

    <w:p>
      <w:pPr>
        <w:sectPr>
          <w:pgSz w:w="12240" w:h="15840"/>
          <w:pgMar w:top="1440" w:right="1800" w:bottom="1440" w:left="1800" w:header="720" w:footer="720" w:gutter="0"/>
          <w:cols w:space="720"/>
          <w:docGrid w:linePitch="360"/>
        </w:sectPr>
      </w:pPr>
      <w:r>
        <w:t>Text before section break insertion point}</w:t>
      </w:r>
    </w:p>

Schema excerpt
--------------

.. highlight:: xml

::

  <xsd:complexType name="CT_PPr">  <!-- denormalized -->
    <xsd:sequence>
      <xsd:element name="pStyle"              type="CT_String"           minOccurs="0"/>
      <xsd:element name="keepNext"            type="CT_OnOff"            minOccurs="0"/>
      <xsd:element name="keepLines"           type="CT_OnOff"            minOccurs="0"/>
      <xsd:element name="pageBreakBefore"     type="CT_OnOff"            minOccurs="0"/>
      <xsd:element name="framePr"             type="CT_FramePr"          minOccurs="0"/>
      <xsd:element name="widowControl"        type="CT_OnOff"            minOccurs="0"/>
      <xsd:element name="numPr"               type="CT_NumPr"            minOccurs="0"/>
      <xsd:element name="suppressLineNumbers" type="CT_OnOff"            minOccurs="0"/>
      <xsd:element name="pBdr"                type="CT_PBdr"             minOccurs="0"/>
      <xsd:element name="shd"                 type="CT_Shd"              minOccurs="0"/>
      <xsd:element name="tabs"                type="CT_Tabs"             minOccurs="0"/>
      <xsd:element name="suppressAutoHyphens" type="CT_OnOff"            minOccurs="0"/>
      <xsd:element name="kinsoku"             type="CT_OnOff"            minOccurs="0"/>
      <xsd:element name="wordWrap"            type="CT_OnOff"            minOccurs="0"/>
      <xsd:element name="overflowPunct"       type="CT_OnOff"            minOccurs="0"/>
      <xsd:element name="topLinePunct"        type="CT_OnOff"            minOccurs="0"/>
      <xsd:element name="autoSpaceDE"         type="CT_OnOff"            minOccurs="0"/>
      <xsd:element name="autoSpaceDN"         type="CT_OnOff"            minOccurs="0"/>
      <xsd:element name="bidi"                type="CT_OnOff"            minOccurs="0"/>
      <xsd:element name="adjustRightInd"      type="CT_OnOff"            minOccurs="0"/>
      <xsd:element name="snapToGrid"          type="CT_OnOff"            minOccurs="0"/>
      <xsd:element name="spacing"             type="CT_Spacing"          minOccurs="0"/>
      <xsd:element name="ind"                 type="CT_Ind"              minOccurs="0"/>
      <xsd:element name="contextualSpacing"   type="CT_OnOff"            minOccurs="0"/>
      <xsd:element name="mirrorIndents"       type="CT_OnOff"            minOccurs="0"/>
      <xsd:element name="suppressOverlap"     type="CT_OnOff"            minOccurs="0"/>
      <xsd:element name="jc"                  type="CT_Jc"               minOccurs="0"/>
      <xsd:element name="textDirection"       type="CT_TextDirection"    minOccurs="0"/>
      <xsd:element name="textAlignment"       type="CT_TextAlignment"    minOccurs="0"/>
      <xsd:element name="textboxTightWrap"    type="CT_TextboxTightWrap" minOccurs="0"/>
      <xsd:element name="outlineLvl"          type="CT_DecimalNumber"    minOccurs="0"/>
      <xsd:element name="divId"               type="CT_DecimalNumber"    minOccurs="0"/>
      <xsd:element name="cnfStyle"            type="CT_Cnf"              minOccurs="0"/>
      <xsd:element name="rPr"                 type="CT_ParaRPr"          minOccurs="0"/>
      <xsd:element name="sectPr"              type="CT_SectPr"           minOccurs="0"/>
      <xsd:element name="pPrChange"           type="CT_PPrChange"        minOccurs="0"/>
    </xsd:sequence>
  </xsd:complexType>

  <xsd:complexType name="CT_SectPr">  <!-- denormalized -->
    <xsd:sequence>
      <xsd:group   ref="EG_HdrFtrReferences" minOccurs="0" maxOccurs="6"/>
      <xsd:element name="footnotePr"      type="CT_FtnProps"      minOccurs="0"/>
      <xsd:element name="endnotePr"       type="CT_EdnProps"      minOccurs="0"/>
      <xsd:element name="type"            type="CT_SectType"      minOccurs="0"/>
      <xsd:element name="pgSz"            type="CT_PageSz"        minOccurs="0"/>
      <xsd:element name="pgMar"           type="CT_PageMar"       minOccurs="0"/>
      <xsd:element name="paperSrc"        type="CT_PaperSource"   minOccurs="0"/>
      <xsd:element name="pgBorders"       type="CT_PageBorders"   minOccurs="0"/>
      <xsd:element name="lnNumType"       type="CT_LineNumber"    minOccurs="0"/>
      <xsd:element name="pgNumType"       type="CT_PageNumber"    minOccurs="0"/>
      <xsd:element name="cols"            type="CT_Columns"       minOccurs="0"/>
      <xsd:element name="formProt"        type="CT_OnOff"         minOccurs="0"/>
      <xsd:element name="vAlign"          type="CT_VerticalJc"    minOccurs="0"/>
      <xsd:element name="noEndnote"       type="CT_OnOff"         minOccurs="0"/>
      <xsd:element name="titlePg"         type="CT_OnOff"         minOccurs="0"/>
      <xsd:element name="textDirection"   type="CT_TextDirection" minOccurs="0"/>
      <xsd:element name="bidi"            type="CT_OnOff"         minOccurs="0"/>
      <xsd:element name="rtlGutter"       type="CT_OnOff"         minOccurs="0"/>
      <xsd:element name="docGrid"         type="CT_DocGrid"       minOccurs="0"/>
      <xsd:element name="printerSettings" type="CT_Rel"           minOccurs="0"/>
      <xsd:element name="sectPrChange"    type="CT_SectPrChange"  minOccurs="0"/>
    </xsd:sequence>
    <xsd:attributeGroup ref="AG_SectPrAttributes"/>
  </xsd:complexType>

  <xsd:group name="EG_HdrFtrReferences">
    <xsd:choice>
      <xsd:element name="headerReference" type="CT_HdrFtrRef" minOccurs="0"/>
      <xsd:element name="footerReference" type="CT_HdrFtrRef" minOccurs="0"/>
    </xsd:choice>
  </xsd:group>

  <xsd:attributeGroup name="AG_SectPrAttributes">
    <xsd:attribute name="rsidRPr"  type="ST_LongHexNumber"/>
    <xsd:attribute name="rsidDel"  type="ST_LongHexNumber"/>
    <xsd:attribute name="rsidR"    type="ST_LongHexNumber"/>
    <xsd:attribute name="rsidSect" type="ST_LongHexNumber"/>
  </xsd:attributeGroup>


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using System.Management.Automation;

using Microsoft.Azure.Commands.Batch.Models;
using Constants = Microsoft.Azure.Commands.Batch.Utils.Constants;

namespace Microsoft.Azure.Commands.Batch
{
    [Cmdlet(VerbsCommon.New, Constants.AzureRmBatchApplicationPackage, DefaultParameterSetName = UploadAndActivateSet), OutputType(typeof(PSApplicationPackage))]
    public class NewBatchApplicationPackageCommand : BatchCmdletBase
    {
        internal const string ActivateOnlySet = "ActivateOnly";
        internal const string UploadAndActivateSet = "UploadAndActivate";

        [Parameter(Position = 0, ParameterSetName = UploadAndActivateSet, ValueFromPipelineByPropertyName = true, Mandatory = true, HelpMessage = "Specifies the name of the Batch account.")]
        [Parameter(Position = 0, ParameterSetName = ActivateOnlySet, ValueFromPipelineByPropertyName = true, Mandatory = true, HelpMessage = "Specifies the name of the Batch account.")]
        [ValidateNotNullOrEmpty]
        public string AccountName { get; set; }

        [Parameter(Position = 1, ParameterSetName = UploadAndActivateSet, ValueFromPipelineByPropertyName = true, Mandatory = true, HelpMessage = "Specifies the name of the resource group that contains the Batch account.")]
        [Parameter(Position = 1, ParameterSetName = ActivateOnlySet, ValueFromPipelineByPropertyName = true, Mandatory = true, HelpMessage = "Specifies the name of the resource group that contains the Batch account.")]
        [ValidateNotNullOrEmpty]
        public string ResourceGroupName { get; set; }

        [Parameter(Position = 2, ParameterSetName = UploadAndActivateSet, ValueFromPipelineByPropertyName = true, Mandatory = true, HelpMessage = "Specifies the id of the application.")]
        [Parameter(Position = 2, ParameterSetName = ActivateOnlySet, ValueFromPipelineByPropertyName = true, Mandatory = true, HelpMessage = "Specifies the id of the application.")]
        [ValidateNotNullOrEmpty]
        public string ApplicationId { get; set; }

        [Parameter(Position = 3, ParameterSetName = UploadAndActivateSet, ValueFromPipelineByPropertyName = true, Mandatory = true, HelpMessage = "Specifies the version of the application.")]
        [Parameter(Position = 3, ParameterSetName = ActivateOnlySet, ValueFromPipelineByPropertyName = true, Mandatory = true, HelpMessage = "Specifies the version of the application.")]
        [ValidateNotNullOrEmpty]
        public string ApplicationVersion { get; set; }

        [Parameter(Position = 4, ParameterSetName = UploadAndActivateSet, ValueFromPipelineByPropertyName = true, Mandatory = true, HelpMessage = "Specifies the format of the application package binary file.")]
        [Parameter(Position = 4, ParameterSetName = ActivateOnlySet, ValueFromPipelineByPropertyName = true, Mandatory = true, HelpMessage = "Specifies the format of the application package binary file.")]
        [ValidateNotNullOrEmpty]
        public string Format { get; set; }

        [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = UploadAndActivateSet, Mandatory = true, HelpMessage = "Specifies the file path of the application that will be uploaded to Azure Storage.")]
        [ValidateNotNullOrEmpty]
        public string FilePath { get; set; }

        [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = ActivateOnlySet)]
        [ValidateNotNullOrEmpty]
        public SwitchParameter ActivateOnly { get; set; }

        public override void ExecuteCmdlet()
        {
            PSApplicationPackage response = BatchClient.UploadAndActivateApplicationPackage(
                this.ResourceGroupName,
                this.AccountName,
                this.ApplicationId,
                this.ApplicationVersion,
                this.FilePath,
                this.Format,
                this.ActivateOnly.IsPresent);
            WriteObject(response);
        }
    }
}


text:
'use strict';

export default class OnboardingController {
    constructor() {

    }
}


text:
package cache

import (
	"encoding/json"
	"time"

	"github.com/pkg/errors"
	"github.com/ryanuber/go-glob"

	fluxerr "github.com/fluxcd/flux/pkg/errors"
	"github.com/fluxcd/flux/pkg/image"
	"github.com/fluxcd/flux/pkg/registry"
)

var (
	ErrNotCached = &fluxerr.Error{
		Type: fluxerr.Missing,
		Err:  errors.New("item not in cache"),
		Help: `Image not yet cached

It takes time to initially cache all the images. Please wait.

If you have waited for a long time, check the Flux logs. Potential
reasons for the error are: no internet, no cache, error with the remote
repository.
`,
	}
)

// Cache is a local cache of image metadata.
type Cache struct {
	Reader     Reader
	Decorators []Decorator
}

// Decorator is for decorating an ImageRepository before it is returned.
type Decorator interface {
	apply(*ImageRepository)
}

// TimestampLabelWhitelist contains a string slice of glob patterns. Any
// canonical image reference that matches one of the glob patterns will
// prefer creation timestamps from labels over the one it received from
// the registry.
type TimestampLabelWhitelist []string

// apply checks if any of the canonical image references from the
// repository matches a glob pattern from the list. If it does, and the
// image record has a valid timestamp label, it will replace the Created
// field with the value from the label for all images in the repository.
func (l TimestampLabelWhitelist) apply(r *ImageRepository) {
	var match bool
	for k, i := range r.Images {
		if !match {
			for _, exp := range l {
				if glob.Glob(exp, i.ID.CanonicalName().String()) {
					match = true
					break
				}
			}
			if !match {
				return
			}
		}

		switch {
		case !i.Labels.Created.IsZero():
			i.CreatedAt = i.Labels.Created
		case !i.Labels.BuildDate.IsZero():
			i.CreatedAt = i.Labels.BuildDate
		}
		r.Images[k] = i
	}
}

// GetImageRepositoryMetadata returns the metadata from an image
// repository (e.g,. at "docker.io/fluxcd/flux")
func (c *Cache) GetImageRepositoryMetadata(id image.Name) (image.RepositoryMetadata, error) {
	repoKey := NewRepositoryKey(id.CanonicalName())
	bytes, _, err := c.Reader.GetKey(repoKey)
	if err != nil {
		return image.RepositoryMetadata{}, err
	}
	var repo ImageRepository
	if err = json.Unmarshal(bytes, &repo); err != nil {
		return image.RepositoryMetadata{}, err
	}

	// We only care about the error if we've never successfully
	// updated the result.
	if repo.LastUpdate.IsZero() {
		if repo.LastError != "" {
			return image.RepositoryMetadata{}, errors.New(repo.LastError)
		}
		return image.RepositoryMetadata{}, ErrNotCached
	}

	// (Maybe) decorate the image repository.
	for _, d := range c.Decorators {
		d.apply(&repo)
	}

	return repo.RepositoryMetadata, nil
}

// GetImage gets the manifest of a specific image ref, from its
// registry.
func (c *Cache) GetImage(id image.Ref) (image.Info, error) {
	key := NewManifestKey(id.CanonicalRef())

	val, _, err := c.Reader.GetKey(key)
	if err != nil {
		return image.Info{}, err
	}
	var img registry.ImageEntry
	err = json.Unmarshal(val, &img)
	if err != nil {
		return image.Info{}, err
	}
	if img.ExcludedReason != "" {
		return image.Info{}, errors.New(img.ExcludedReason)
	}
	return img.Info, nil
}

// ImageRepository holds the last good information on an image
// repository.
//
// Whenever we successfully fetch a set (partial or full) of image metadata,
// `LastUpdate`, `Tags` and `Images` shall each be assigned a value, and
// `LastError` will be cleared.
//
// If we cannot for any reason obtain the set of image metadata,
// `LastError` shall be assigned a value, and the other fields left
// alone.
//
// It's possible to have all fields populated: this means at some
// point it was successfully fetched, but since then, there's been an
// error. It's then up to the caller to decide what to do with the
// value (show the images, but also indicate there's a problem, for
// example).
type ImageRepository struct {
	image.RepositoryMetadata
	LastError  string
	LastUpdate time.Time
}


text: enum annoying { annoying_0 };


text:
using System.ComponentModel.DataAnnotations;

namespace BgeniiusUniversity.Models
{
    public enum Grade
    {
        A, B, C, D, F
    }

    public class Enrollment
    {
        public int EnrollmentID { get; set; }
        public int CourseID { get; set; }
        public int StudentID { get; set; }
        [DisplayFormat(NullDisplayText = "No grade")]
        public Grade? Grade { get; set; }

        public virtual Course Course { get; set; }
        public virtual Student Student { get; set; }
    }
}


text:
<?php

// ApplicationBlogBundle:Post:show.html.twig
return array (
);


text:
package com.github.davidmoten.rtree;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.charset.Charset;

import com.esotericsoftware.kryo.Kryo;
import com.github.davidmoten.guavamini.Preconditions;
import com.github.davidmoten.rtree.fbs.SerializerFlatBuffers;
import com.github.davidmoten.rtree.geometry.Geometry;
import com.github.davidmoten.rtree.internal.Functions;
import com.github.davidmoten.rtree.kryo.SerializerKryo;

import rx.functions.Func0;
import rx.functions.Func1;

public final class Serializers {

    private Serializers() {
        // prevent instantiation
    }

    public static class SerializerBuilder {

        private Method method = Method.FLATBUFFERS;

        private SerializerBuilder() {

        }

        public <T> SerializerTypedBuilder<T> serializer(Func1<? super T, byte[]> serializer) {
            return new SerializerTypedBuilder<T>(serializer, null, method);
        }

        public <T> SerializerTypedBuilder<T> deserializer(Func1<byte[], ? extends T> deserializer) {
            return new SerializerTypedBuilder<T>(null, deserializer, method);
        }

        public <S extends Geometry> Serializer<String, S> string(Charset charset) {
            Func1<String, byte[]> serializer = createStringSerializer(charset);
            Func1<byte[], String> deserializer = createStringDeserializer(charset);
            return new SerializerTypedBuilder<String>(serializer, deserializer, method).create();
        }

        @SuppressWarnings("unchecked")
        public <T extends Serializable, S extends Geometry> Serializer<T, S> javaIo() {
            Func1<T, byte[]> serializer = (Func1<T, byte[]>) javaIoSerializer();
            Func1<byte[], T> deserializer = (Func1<byte[], T>) javaIoDeserializer();
            return new SerializerTypedBuilder<T>(serializer, deserializer, method).create();
        }

        public <S extends Geometry> Serializer<String, S> utf8() {
            return string(Charset.forName("UTF-8"));
        }

        public <S extends Geometry> Serializer<byte[], S> bytes() {
            Func1<byte[], byte[]> serializer = Functions.identity();
            Func1<byte[], byte[]> deserializer = Functions.identity();
            return new SerializerTypedBuilder<byte[]>(serializer, deserializer, method).create();
        }

        public SerializerBuilder method(Method method) {
            this.method = method;
            return this;
        }

    }

    public static final class SerializerTypedBuilder<T> {

        private Func1<? super T, byte[]> serializer;
        private Func1<byte[], ? extends T> deserializer;
        private Method method;
        private Func0<Kryo> kryoFactory = new Func0<Kryo>() {
            @Override
            public Kryo call() {
                return new Kryo();
            }
        };

        private SerializerTypedBuilder(Func1<? super T, byte[]> serializer,
                Func1<byte[], ? extends T> deserializer, Method method) {
            this.serializer = serializer;
            this.deserializer = deserializer;
            this.method = method;
        }

        public SerializerTypedBuilder<T> serializer(Func1<? super T, byte[]> serializer) {
            this.serializer = serializer;
            return this;
        }

        public SerializerTypedBuilder<T> deserializer(Func1<byte[], ? extends T> deserializer) {
            this.deserializer = deserializer;
            return this;
        }

        public SerializerTypedBuilder<T> method(Method method) {
            // TODO remove this check when kryo ready
            Preconditions.checkArgument(method != Method.KRYO,
                    "kryo serialization not implemented yet");
            this.method = method;
            return this;
        }

        // TODO enable when ready
        @SuppressWarnings("unused")
        private SerializerTypedBuilder<T> kryo(Func0<Kryo> kryoFactory) {
            this.method = Method.KRYO;
            this.kryoFactory = kryoFactory;
            return this;
        }

        @SuppressWarnings("unchecked")
        public <S extends Geometry> Serializer<T, S> create() {
            if (method == Method.FLATBUFFERS) {
                if (serializer == null) {
                    serializer = (Func1<T, byte[]>) javaIoSerializer();
                }
                if (deserializer == null) {
                    deserializer = (Func1<byte[], T>) javaIoDeserializer();
                }
                return SerializerFlatBuffers.create(serializer, deserializer);
            } else {
                return SerializerKryo.create(serializer, deserializer, kryoFactory);
            }
        }

    }

    public static <T, S extends Geometry> SerializerBuilder flatBuffers() {
        return new SerializerBuilder().method(Method.FLATBUFFERS);
    }

    public enum Method {
        FLATBUFFERS, KRYO;
    }

    private static Func1<String, byte[]> createStringSerializer(final Charset charset) {
        return new Func1<String, byte[]>() {
            @Override
            public byte[] call(String s) {
                return s.getBytes(charset);
            }
        };
    }

    private static <T> Func1<byte[], String> createStringDeserializer(final Charset charset) {
        return new Func1<byte[], String>() {
            @Override
            public String call(byte[] bytes) {
                return new String(bytes, charset);
            }
        };
    }

    private static Func1<Serializable, byte[]> javaIoSerializer() {
        return new Func1<Serializable, byte[]>() {
            @Override
            public byte[] call(Serializable o) {
                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                ObjectOutputStream oos = null;
                try {
                    oos = new ObjectOutputStream(bytes);
                    oos.writeObject(o);
                    oos.close();
                    return bytes.toByteArray();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } finally {
                    try {
                        if (oos != null)
                            oos.close();
                    } catch (IOException e) {
                        // ignore
                    }
                }
            }
        };
    }

    private static Func1<byte[], Serializable> javaIoDeserializer() {
        return new Func1<byte[], Serializable>() {
            @Override
            public Serializable call(byte[] bytes) {
                ByteArrayInputStream is = new ByteArrayInputStream(bytes);
                ObjectInputStream ois = null;
                try {
                    ois = new ObjectInputStream(is);
                    return (Serializable) ois.readObject();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                } finally {
                    if (ois != null)
                        try {
                            ois.close();
                        } catch (IOException e) {
                            // ignore
                        }
                }
            }
        };
    }

}


text:
using namespace Cooper;

// Set params for DB connection
void loadParams() {
	config["dbname"] = "videocube";
	config["user"] = "postgres";
	config["password"] = "1we2q3";
	config["hostaddr"] = "93.73.16.132";
	config["port"] = "5432";
}


text:
import { mockBundleAndRun } from './utils'

test('named exports', async () => {
  const { exports } = await mockBundleAndRun({
    entry: 'named-exports.vue',
  })
  expect(exports.default.name).toBe('named-exports')
  expect(exports.foo()).toBe(1)
})

test('experimental <script setup>', async () => {
  await mockBundleAndRun({ entry: 'ScriptSetup.vue' })
})

test('should handle custom resource query', async () => {
  const { exports } = await mockBundleAndRun({
    entry: 'custom-query.vue',
  })

  expect(exports.default.data().msg).toBe('Hello from Component A!')
})


text:
@interface MMXLessonsViewController ()

@property (nonatomic, strong) NSArray *fetchedTopScores;

@end

NSString * const kMMXLessonsViewControolerDidShowNotification = @"MMXLessonsViewControolerDidShowNotification";

@implementation MMXLessonsViewController

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self)
    {
        [[NSNotificationCenter defaultCenter] addObserverForName:kMMXResultsDidSaveGameNotification
                                                          object:nil
                                                           queue:[NSOperationQueue mainQueue]
                                                      usingBlock:^(NSNotification *note)
                                                      {
                                                          [self fetchTopScoresForLessonsInThisClass];

                                                          [self.tableView reloadData];
                                                      }];

        [[NSNotificationCenter defaultCenter] addObserverForName:kMMXLessonsViewControolerDidShowNotification
                                                          object:nil
                                                           queue:[NSOperationQueue mainQueue]
                                                      usingBlock:^(NSNotification *note)
                                                      {
                                                          if (self.indexOfNextLesson > 0)
                                                          {
                                                              [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:self.indexOfNextLesson inSection:0]
                                                                                animated:YES
                                                                                scrollPosition:UITableViewScrollPositionBottom];

                                                              self.indexOfNextLesson = 0;

                                                              [self performSegueWithIdentifier:@"MMXBeginLessonSegue" sender:nil];
                                                          }
                                                      }];
    }

    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self fetchTopScoresForLessonsInThisClass];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    self.navigationController.navigationBar.barTintColor = [UIColor mmx_blueColor];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    if (self.isMovingFromParentViewController)
    {
        [MMXAudioManager sharedManager].soundEffect = MMXAudioSoundEffectTapBackward;
        [[MMXAudioManager sharedManager] playSoundEffect];
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.lessons.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *lesson = self.lessons[indexPath.row];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"lessonID == %@", lesson[@"lessonID"]];
    NSArray *results = [self.fetchedTopScores filteredArrayUsingPredicate:predicate];

    MMXLessonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MMXLessonCell" forIndexPath:indexPath];
    cell.lessonTitleLabel.text = lesson[@"title"];

    if (results.count > 0)
    {
        MMXTopScore *topScore = results[0];
        cell.starCountLabel.text = [NSString stringWithFormat:@"%ld", (long)topScore.stars.integerValue];
        cell.starCountLabel.hidden = NO;
        cell.starImageView.hidden = NO;

        NSString *pluralStars = @"Stars";
        if ([cell.starCountLabel.text isEqualToString:@"1"])
        {
            pluralStars = @"Star";
        }
        cell.accessibilityLabel = [NSString stringWithFormat:@"%@, %@ %@", cell.lessonTitleLabel.text, cell.starCountLabel.text, pluralStars];
    }
    else
    {
        cell.starCountLabel.hidden = YES;
        cell.starImageView.hidden = YES;
    }

    return cell;
}

#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"MMXBeginLessonSegue"])
    {
        [MMXAudioManager sharedManager].soundEffect = MMXAudioSoundEffectTapForward;
        [[MMXAudioManager sharedManager] playSoundEffect];

        NSDictionary *lesson = self.lessons[self.tableView.indexPathForSelectedRow.row];
        MMXGameData *gameConfiguration = [self gameConfigurationFromLesson:lesson];

        MMXGameViewController *gameViewController = (MMXGameViewController *)segue.destinationViewController;
        gameViewController.managedObjectContext = self.managedObjectContext;
        gameViewController.gameData = gameConfiguration;
        gameViewController.manuallySpecifiedCardValues = lesson[@"cardValues"];

        if (self.tableView.indexPathForSelectedRow.row < (self.lessons.count - 1))
        {
            gameViewController.indexOfNextLesson = self.tableView.indexPathForSelectedRow.row + 1;
        }
    }
}

- (IBAction)unwindToLessonsSegue:(UIStoryboardSegue *)unwindSegue
{

}

#pragma mark - Helpers

- (void)fetchTopScoresForLessonsInThisClass
{
    NSMutableArray *lessonIDsInThisClass = [NSMutableArray arrayWithCapacity:self.lessons.count];
    for (NSDictionary *lesson in self.lessons)
    {
        [lessonIDsInThisClass addObject:lesson[@"lessonID"]];
    }

    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"MMXTopScore"
                                                         inManagedObjectContext:self.managedObjectContext];

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:entityDescription];
    [fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"lessonID IN %@", lessonIDsInThisClass]];

    NSError *fetchError = nil;
    self.fetchedTopScores = [self.managedObjectContext executeFetchRequest:fetchRequest error:&fetchError];
}

- (MMXGameData *)gameConfigurationFromLesson:(NSDictionary *)lesson
{
    MMXGameData *gameConfiguration = [NSEntityDescription insertNewObjectForEntityForName:@"MMXGameData"
                                                                   inManagedObjectContext:self.managedObjectContext];

    gameConfiguration.gameType = MMXGameTypeCourse;
    gameConfiguration.lessonID = lesson[@"lessonID"];

    gameConfiguration.targetNumber = lesson[@"targetNumber"];
    gameConfiguration.numberOfCards = lesson[@"numberOfCards"];

    if ([lesson[@"arithmeticType"] isEqualToString:@"addition"])
    {
        gameConfiguration.arithmeticType = MMXArithmeticTypeAddition;
    }
    else if ([lesson[@"arithmeticType"] isEqualToString:@"subtraction"])
    {
        gameConfiguration.arithmeticType = MMXArithmeticTypeSubtraction;
    }
    else if ([lesson[@"arithmeticType"] isEqualToString:@"multiplication"])
    {
        gameConfiguration.arithmeticType = MMXArithmeticTypeMultiplication;
    }
    else if ([lesson[@"arithmeticType"] isEqualToString:@"division"])
    {
        gameConfiguration.arithmeticType = MMXArithmeticTypeDivision;
    }
    else
    {
        NSAssert(YES, @"MMX: Arithmetic Type in JSON is not valid.");
    }

    if ([lesson[@"startingPositionType"] isEqualToString:@"face up"])
    {
        gameConfiguration.startingPositionType = MMXStartingPositionTypeFaceUp;
    }
    else if ([lesson[@"startingPositionType"] isEqualToString:@"memorize"])
    {
        gameConfiguration.startingPositionType = MMXStartingPositionTypeMemorize;
    }
    else if ([lesson[@"startingPositionType"] isEqualToString:@"face down"])
    {
        gameConfiguration.startingPositionType = MMXStartingPositionTypeFaceDown;
    }
    else
    {
        NSAssert(YES, @"MMX: Starting position type in JSON is not valid.");
    }

    if ([lesson[@"musicTrackType"] isEqualToString:@"easy"])
    {
        gameConfiguration.musicTrack = MMXMusicTrackEasy;
    }
    else if ([lesson[@"musicTrackType"] isEqualToString:@"medium"])
    {
        gameConfiguration.musicTrack = MMXMusicTrackMedium;
    }
    else if ([lesson[@"musicTrackType"] isEqualToString:@"hard"])
    {
        gameConfiguration.musicTrack = MMXMusicTrackHard;
    }
    else
    {
        gameConfiguration.musicTrack = MMXMusicTrackEasy;
    }

    gameConfiguration.cardStyle = [MMXGameData selectRandomCardStyle];

    gameConfiguration.penaltyMultiplier = lesson[@"penaltyMultiplier"];

    NSArray *starTimes = lesson[@"starTimes"];
    gameConfiguration.twoStarTime = starTimes[0];
    gameConfiguration.threeStarTime = starTimes[1];

    return gameConfiguration;
}

@end


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/pull_to_refresh_head"
    android:layout_width="match_parent"
    android:layout_height="60dip" >

    <LinearLayout
        android:layout_width="200dip"
        android:layout_height="60dip"
        android:layout_centerInParent="true"
        android:orientation="horizontal" >

        <FrameLayout
            android:layout_width="0dip"
            android:layout_height="60dip"
            android:layout_weight="3" >

            <ImageView
                android:id="@+id/arrow"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:contentDescription="@null"
                android:src="@drawable/arrow" />

            <ProgressBar
                android:id="@+id/progress_bar"
                android:layout_width="30dip"
                android:layout_height="30dip"
                android:layout_gravity="center"
                android:visibility="gone" />
        </FrameLayout>

        <LinearLayout
            android:layout_width="0dip"
            android:layout_height="60dip"
            android:layout_weight="12"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/description"
                android:layout_width="fill_parent"
                android:layout_height="30dip"
                android:gravity="center_horizontal|bottom"
                android:text="@string/pull_to_refresh" />

            <TextView
                android:id="@+id/updated_at"
                android:layout_width="fill_parent"
                android:layout_height="30dip"
                android:gravity="center_horizontal|top"
                android:text="@string/updated_at" />
        </LinearLayout>
    </LinearLayout>

</RelativeLayout>


text:
"""
Test that the lldb driver's batch mode works correctly.
"""

from __future__ import print_function

import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
from lldbsuite.test.lldbpexpect import PExpectTest

class DriverBatchModeTest(PExpectTest):

    mydir = TestBase.compute_mydir(__file__)
    source = 'main.c'

    @skipIfRemote  # test not remote-ready llvm.org/pr24813
    @expectedFlakeyFreeBSD("llvm.org/pr25172 fails rarely on the buildbot")
    def test_batch_mode_run_crash(self):
        """Test that the lldb driver's batch mode works correctly."""
        self.build()

        exe = self.getBuildArtifact("a.out")

        # Pass CRASH so the process will crash and stop in batch mode.
        extra_args = ['-b',
            '-o', 'break set -n main',
            '-o', 'run',
            '-o', 'continue',
            '-k', 'frame var touch_me_not',
            '--', 'CRASH',
        ]
        self.launch(executable=exe, extra_args=extra_args)
        child = self.child

        # We should see the "run":
        child.expect_exact("run")
        # We should have hit the breakpoint & continued:
        child.expect_exact("continue")
        # The App should have crashed:
        child.expect_exact("About to crash")
        # The -k option should have printed the frame variable once:
        child.expect_exact('(char *) touch_me_not')
        # Then we should have a live prompt:
        self.expect_prompt()
        self.expect("frame variable touch_me_not", substrs='(char *) touch_me_not')

    @skipIfRemote  # test not remote-ready llvm.org/pr24813
    @expectedFlakeyFreeBSD("llvm.org/pr25172 fails rarely on the buildbot")
    def test_batch_mode_run_exit(self):
        """Test that the lldb driver's batch mode works correctly."""
        self.build()

        exe = self.getBuildArtifact("a.out")

        # Now do it again, and make sure if we don't crash, we quit:
        extra_args = ['-b',
            '-o', 'break set -n main',
            '-o', 'run',
            '-o', 'continue',
            '--', 'NOCRASH',
        ]
        self.launch(executable=exe, extra_args=extra_args)
        child = self.child

        # We should see the "run":
        child.expect_exact("run")
        # We should have hit the breakpoint & continued:
        child.expect_exact("continue")
        # The App should have not have crashed:
        child.expect_exact("Got there on time and it did not crash.")

        # Then lldb should exit.
        child.expect_exact("exited")
        import pexpect
        child.expect(pexpect.EOF)

    @expectedFlakeyFreeBSD("llvm.org/pr25172 fails rarely on the buildbot")
    def test_batch_mode_launch_stop_at_entry(self):
        """Test that the lldb driver's batch mode works correctly for process launch."""
        self.build()

        exe = self.getBuildArtifact("a.out")

        # Launch with the option '--stop-at-entry' stops with a signal (usually SIGSTOP)
        # that should be suppressed since it doesn't imply a crash and
        # this is not a reason to exit batch mode.
        extra_args = ['-b',
            '-o', 'process launch --stop-at-entry',
            '-o', 'continue',
        ]
        self.launch(executable=exe, extra_args=extra_args)
        child = self.child

        # Check that the process has been launched:
        child.expect("Process ([0-9]+) launched:")
        # We should have continued:
        child.expect_exact("continue")
        # The App should have not have crashed:
        child.expect_exact("Got there on time and it did not crash.")

        # Then lldb should exit.
        child.expect_exact("exited")
        import pexpect
        child.expect(pexpect.EOF)

    def closeVictim(self):
        if self.victim is not None:
            self.victim.close()
            self.victim = None

    @skipIfRemote  # test not remote-ready llvm.org/pr24813
    @expectedFlakeyFreeBSD("llvm.org/pr25172 fails rarely on the buildbot")
    @expectedFailureNetBSD
    def test_batch_mode_attach_exit(self):
        """Test that the lldb driver's batch mode works correctly."""
        self.build()
        self.setTearDownCleanup()

        exe = self.getBuildArtifact("a.out")

        # Start up the process by hand, attach to it, and wait for its completion.
        # Attach is funny, since it looks like it stops with a signal on most Unixen so
        # care must be taken not to treat that as a reason to exit batch mode.

        # Start up the process by hand and wait for it to get to the wait loop.
        import pexpect
        self.victim = pexpect.spawn('%s WAIT' % (exe))
        if self.victim is None:
            self.fail("Could not spawn ", exe, ".")

        self.addTearDownHook(self.closeVictim)

        self.victim.expect("PID: ([0-9]+) END")
        victim_pid = int(self.victim.match.group(1))

        self.victim.expect("Waiting")

        extra_args = [
            '-b',
            '-o', 'process attach -p %d'%victim_pid,
            '-o', "breakpoint set --file '%s' -p 'Stop here to unset keep_waiting' -N keep_waiting"%self.source,
            '-o', 'continue',
            '-o', 'break delete keep_waiting',
            '-o', 'expr keep_waiting = 0',
            '-o', 'continue',
        ]
        self.launch(executable=exe, extra_args=extra_args)
        child = self.child

        child.expect_exact("attach")

        child.expect_exact(self.PROMPT + "continue")

        child.expect_exact(self.PROMPT + "continue")

        # Then we should see the process exit:
        child.expect_exact("Process %d exited with status" % (victim_pid))

        self.victim.expect(pexpect.EOF)
        child.expect(pexpect.EOF)