text:
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using Moq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Xunit;
using MessagingEventData = Azure.Messaging.EventHubs.EventData;

using Microsoft.Diagnostics.EventFlow.Configuration;

namespace Microsoft.Diagnostics.EventFlow.Outputs.Tests
{
    public class EventHubOutputTests
    {
        [Fact]
        public void UsesIsoDateFormat()
        {
            EventData e = new EventData();
            e.Payload.Add("DateTimeProperty", new DateTime(2017, 4, 19, 10, 15, 23, DateTimeKind.Utc));
            e.Payload.Add("DateTimeOffsetProperty", new DateTimeOffset(2017, 4, 19, 10, 16, 07, TimeSpan.Zero));

            var messagingData = EventDataExtensions.ToMessagingEventData(e, EventFlowJsonUtilities.GetDefaultSerializerSettings(), out int messageSize);
            var messagingDataBytes = messagingData.EventBody.ToArray();
            string messageBody = Encoding.UTF8.GetString(messagingDataBytes, (int)messagingData.Offset, messagingDataBytes.Length);

            var dateTimeRegex = new Regex(@"""DateTimeProperty"" \s* : \s* ""2017-04-19T10:15:23Z""", RegexOptions.IgnorePatternWhitespace, TimeSpan.FromMilliseconds(100));
            Assert.Matches(dateTimeRegex, messageBody);

            var dateTimeOffsetRegex = new Regex(@"""DateTimeOffsetProperty"" \s* : \s* ""2017-04-19T10:16:07\+00:00""", RegexOptions.IgnorePatternWhitespace, TimeSpan.FromMilliseconds(100));
            Assert.Matches(dateTimeOffsetRegex, messageBody);
        }

        [Fact]
        public async Task SendsDataToEventHub()
        {
            var client = new Mock<IEventHubClient>();
            var healthReporter = new Mock<IHealthReporter>();
            var configuration = new EventHubOutputConfiguration();
            configuration.ConnectionString = "Connection string";
            configuration.EventHubName = "foo";

            EventData e = new EventData();
            e.ProviderName = "TestProvider";
            e.Timestamp = DateTimeOffset.UtcNow;
            e.Level = LogLevel.Warning;
            e.Payload.Add("IntProperty", 42);
            e.Payload.Add("StringProperty", "perfection");

            EventHubOutput eho = new EventHubOutput(configuration, healthReporter.Object, connectionString => client.Object);
            await eho.SendEventsAsync(new EventData[] {e,}, 17, CancellationToken.None);

            Func<IEnumerable<MessagingEventData>, bool> verifyBatch = batch =>
            {
                if (batch.Count() != 1) return false;

                var data = batch.First();
                var dataBytes = data.EventBody.ToArray();
                var bodyString = Encoding.UTF8.GetString(dataBytes, (int)data.Offset, dataBytes.Length);
                var recordSet = JObject.Parse(bodyString);
                var message = recordSet["records"][0];

                return (string) message["level"] == "Warning"
                       && (string) message["properties"]["ProviderName"] == "TestProvider"
                       && (int) message["properties"]["IntProperty"] == 42
                       && (string) message["properties"]["StringProperty"] == "perfection";
            };

            client.Verify(c => c.SendAsync(It.Is<IEnumerable<MessagingEventData>>(b => verifyBatch(b))), Times.Once);
            healthReporter.Verify(hr => hr.ReportWarning(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
            healthReporter.Verify(hr => hr.ReportProblem(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
        }

        [Fact]
        public async Task SendsDataToPartitionedEventHub()
        {
            var client = new Mock<IEventHubClient>();
            var healthReporter = new Mock<IHealthReporter>();
            var configuration = new EventHubOutputConfiguration();
            configuration.ConnectionString = "Connection string";
            configuration.EventHubName = "foo";
            configuration.PartitionKeyProperty = "PartitionByProperty";

            EventData e1 = new EventData();
            e1.ProviderName = "TestProvider";
            e1.Timestamp = DateTimeOffset.UtcNow;
            e1.Level = LogLevel.Warning;
            e1.Payload.Add("IntProperty", 23);
            e1.Payload.Add("StringProperty", "partition-perfection");
            e1.Payload.Add("PartitionByProperty", "partition1");

            EventData e2 = new EventData();
            e2.ProviderName = "TestProvider";
            e2.Timestamp = DateTimeOffset.UtcNow;
            e2.Level = LogLevel.Warning;
            e2.Payload.Add("IntProperty", 23);
            e2.Payload.Add("StringProperty", "partition-perfection");

            EventData e3 = new EventData();
            e3.ProviderName = "TestProvider";
            e3.Timestamp = DateTimeOffset.UtcNow;
            e3.Level = LogLevel.Warning;
            e3.Payload.Add("IntProperty", 23);
            e3.Payload.Add("StringProperty", new string('a', 150000));
            e3.Payload.Add("PartitionByProperty", "partition2");

            EventData e4 = new EventData();
            e4.ProviderName = "TestProvider";
            e4.Timestamp = DateTimeOffset.UtcNow;
            e4.Level = LogLevel.Warning;
            e4.Payload.Add("IntProperty", 23);
            e4.Payload.Add("StringProperty", new string('b', 150000));
            e4.Payload.Add("PartitionByProperty", "partition2");

            EventData e5 = new EventData();
            e5.ProviderName = "TestProvider";
            e5.Timestamp = DateTimeOffset.UtcNow;
            e5.Level = LogLevel.Warning;
            e5.Payload.Add("IntProperty", 23);
            e5.Payload.Add("StringProperty", new string('c', 150000));
            e5.Payload.Add("PartitionByProperty", "partition2");

            EventHubOutput eho = new EventHubOutput(configuration, healthReporter.Object, connectionString => client.Object);
            await eho.SendEventsAsync(new[] {e1, e2, e3, e4, e5}, 17, CancellationToken.None);

            Func<IEnumerable<MessagingEventData>, bool> verifyBatch = batch =>
            {
                if (batch.Count() != 1) return false;
                return true;
            };

            client.Verify(c => c.SendAsync(It.Is<IEnumerable<MessagingEventData>>(b => verifyBatch(b))), Times.Once);
            client.Verify(c => c.SendAsync(It.Is<IEnumerable<MessagingEventData>>(b => verifyBatch(b)), "partition1"), Times.Once);
            client.Verify(c => c.SendAsync(It.Is<IEnumerable<MessagingEventData>>(b => verifyBatch(b)), "partition2"), Times.Exactly(3));
            healthReporter.Verify(hr => hr.ReportWarning(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
            healthReporter.Verify(hr => hr.ReportProblem(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
        }

        [Fact]
        public Task Sends512ItemsToPartitionedEventHub()
        {
            return SendsManyItemsToPartitionedEventHub(512);
        }

        private async Task SendsManyItemsToPartitionedEventHub(int itemCount)
        {
            var client = new Mock<IEventHubClient>();
            var healthReporter = new Mock<IHealthReporter>();
            var configuration = new EventHubOutputConfiguration();
            configuration.ConnectionString = "Connection string";
            configuration.EventHubName = "foo";
            configuration.PartitionKeyProperty = "PartitionByProperty";

            EventHubOutput eho = new EventHubOutput(configuration, healthReporter.Object, connectionString => client.Object);

            //send `itemCount` EventData items with payload of 55Kb+ each and targeting PartitionKey "partition3"
            string payload = new string('a', 55000);
            await eho.SendEventsAsync(Enumerable.Range(0, itemCount)
                .Select(r =>
                {
                    var eventData = new EventData();
                    eventData.ProviderName = "TestProvider";
                    eventData.Timestamp = DateTimeOffset.UtcNow;
                    eventData.Level = LogLevel.Warning;
                    eventData.Payload.Add("IntProperty", r);
                    eventData.Payload.Add("StringProperty", payload);
                    eventData.Payload.Add("PartitionByProperty", "partition3");
                    return eventData;
                })
                .ToList(), 17, CancellationToken.None);

            Func<IEnumerable<MessagingEventData>, bool> verifyBatch = batch =>
            {
                if (batch.Count() != 4)
                {
                    return false;
                }
                return true;
            };

            //the individual messages are 55Kb in size each, so a maximum of 4 messages total byte size fits within EventHubMessageSizeLimit limits.
            //so we expect `itemCount` / 4 batches executed against EventHubClient.SendAsync()
            client.Verify(c => c.SendAsync(It.Is<IEnumerable<MessagingEventData>>(b => verifyBatch(b)), "partition3"), Times.Exactly(itemCount / 4));
            healthReporter.Verify(hr => hr.ReportWarning(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
            healthReporter.Verify(hr => hr.ReportProblem(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
        }

        [Fact]
        public async Task MethodInfoIsSerializedAsFullyQualifiedName()
        {
            var client = new Mock<IEventHubClient>();
            var healthReporter = new Mock<IHealthReporter>();
            var configuration = new EventHubOutputConfiguration();
            configuration.ConnectionString = "Connection string";
            configuration.EventHubName = "foo";

            EventData e = new EventData();
            e.ProviderName = "TestProvider";
            e.Timestamp = DateTimeOffset.UtcNow;
            e.Level = LogLevel.Warning;
            e.Payload.Add("Method", typeof(EventHubOutputTests).GetMethod(nameof(MethodInfoIsSerializedAsFullyQualifiedName)));

            EventHubOutput eho = new EventHubOutput(configuration, healthReporter.Object, connectionString => client.Object);
            await eho.SendEventsAsync(new EventData[] { e, }, 17, CancellationToken.None);

            Func<IEnumerable<MessagingEventData>, bool> verifyBatch = batch =>
            {
                if (batch.Count() != 1) return false;

                var data = batch.First();
                var dataBytes = data.EventBody.ToArray();
                var bodyString = Encoding.UTF8.GetString(dataBytes, (int)data.Offset, dataBytes.Length);
                var recordSet = JObject.Parse(bodyString);
                var message = recordSet["records"][0];

                return (string)message["level"] == "Warning"
                       && (string)message["properties"]["ProviderName"] == "TestProvider"
                       && (string)message["properties"]["Method"] == "Microsoft.Diagnostics.EventFlow.Outputs.Tests.EventHubOutputTests.MethodInfoIsSerializedAsFullyQualifiedName";
            };

            client.Verify(c => c.SendAsync(It.Is<IEnumerable<MessagingEventData>>(b => verifyBatch(b))), Times.Once);
            healthReporter.Verify(hr => hr.ReportWarning(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
            healthReporter.Verify(hr => hr.ReportProblem(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
        }

        [Fact]
        public async Task UsesCustomJsonSerializerSettings()
        {
            var client = new Mock<IEventHubClient>();
            var healthReporter = new Mock<IHealthReporter>();
            var configuration = new EventHubOutputConfiguration();
            configuration.ConnectionString = "Connection string";
            configuration.EventHubName = "foo";

            EventData e = new EventData();
            e.ProviderName = "TestProvider";
            e.Timestamp = DateTimeOffset.UtcNow;
            e.Level = LogLevel.Warning;
            e.Payload.Add("InfinityProperty", Double.PositiveInfinity);

            EventHubOutput eho = new EventHubOutput(configuration, healthReporter.Object, connectionString => client.Object);
            await eho.SendEventsAsync(new EventData[] { e, }, 17, CancellationToken.None);

            Func<IEnumerable<MessagingEventData>, bool> verifyBatch = batch =>
            {
                if (batch.Count() != 1) return false;

                var data = batch.First();
                var dataBytes = data.EventBody.ToArray();
                var bodyString = Encoding.UTF8.GetString(dataBytes, (int)data.Offset, dataBytes.Length);
                var recordSet = JObject.Parse(bodyString);
                var message = recordSet["records"][0];

                return (string)message["level"] == "Warning"
                       && (string)message["properties"]["ProviderName"] == "TestProvider"
                       // By default floating-point infinity values are converted to strings
                       && (string)message["properties"]["InfinityProperty"] == "Infinity";
            };

            client.Verify(c => c.SendAsync(It.Is<IEnumerable<MessagingEventData>>(b => verifyBatch(b))), Times.Once);
            healthReporter.Verify(hr => hr.ReportWarning(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
            healthReporter.Verify(hr => hr.ReportProblem(It.IsAny<string>(), It.IsAny<string>()), Times.Never);

            // Now verify changing serializer settings is effective
            eho.SerializerSettings.FloatFormatHandling = FloatFormatHandling.DefaultValue;
            client.ResetCalls();

            verifyBatch = batch =>
            {
                if (batch.Count() != 1) return false;

                var data = batch.First();
                var dataBytes = data.EventBody.ToArray();
                var bodyString = Encoding.UTF8.GetString(dataBytes, (int)data.Offset, dataBytes.Length);
                var recordSet = JObject.Parse(bodyString);
                var message = recordSet["records"][0];

                return (string)message["level"] == "Warning"
                       && (string)message["properties"]["ProviderName"] == "TestProvider"
                       && (double)message["properties"].OfType<JProperty>().First(p => p.Name == "InfinityProperty").OfType<JValue>().First().Value == 0.0;
            };

            await eho.SendEventsAsync(new EventData[] { e, }, 18, CancellationToken.None);

            client.Verify(c => c.SendAsync(It.Is<IEnumerable<MessagingEventData>>(b => verifyBatch(b))), Times.Once);
            healthReporter.Verify(hr => hr.ReportWarning(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
            healthReporter.Verify(hr => hr.ReportProblem(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
        }
    }
}


text:
Introduction
============

Demo images.

`.xar` files were created with Xara Xtreme (or compatible).

The file "load_indicator.gif" has been generated using [ajaxload.info][1].

Legal
=====

All files in this directory are copyright 2010-2012
[Felix E. Klee](felix.klee@inka.de)

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.

[1]: http://www.ajaxload.info/

redpajama_set_name: RedPajamaGithub


text:
CKEDITOR.plugins.setLang( 'devtools', 'et', {
	title: 'Elemendi andmed',
	dialogName: 'Dialoogiakna nimi',
	tabName: 'Saki nimi',
	elementId: 'Elemendi ID',
	elementType: 'Elemendi liik'
} );


text:
@interface TestTableCell : UITableViewCell

- (void)setIcon:(NSString *)iconName string:(NSString *)str;
@end


text:
© Copyright mininiss

          powered by...


text:
u"""
Created on 2016-12-27

@author: cheng.li
"""

import datetime as dt
import numpy as np
import pandas as pd
from PyFin.api import *
from PyFin.Math.Accumulators import MovingAverage

n = 300
m = 60

index = pd.date_range(dt.datetime(2021, 1, 1), dt.datetime(2021, 1, 1) + dt.timedelta(days=m-1))
index = np.repeat(index, n)

df = pd.DataFrame(np.random.randn(n*m, 3), columns=['x', 'y', 'z'], index=index)
df['c'] = np.concatenate([np.linspace(0, n-1, n, dtype=int)] * m)

start = dt.datetime.now()
t = MA(20, 'x') / MA(30, 'y')
res = t.transform(df, category_field='c')
print("Finance-Python (group ma): {0}s".format(dt.datetime.now() - start))

start = dt.datetime.now()
groups = df.groupby('c')
res = groups['x'].rolling(20).mean() / groups['y'].rolling(30).mean()
print("Pandas (group ma): {0}s".format(dt.datetime.now() - start))

start = dt.datetime.now()
t = MovingAverage(20, 'x') / MovingAverage(30, 'x')
res = t.transform(df)
print("\nFinance-Python (rolling ma): {0}s".format(dt.datetime.now() - start))

start = dt.datetime.now()
res = df['x'].rolling(20).mean() / df['x'].rolling(30).mean()
print("Pandas (rolling ma): {0}s".format(dt.datetime.now() - start))

"""
Cross section analysis examples ...
"""

# rank

index = pd.date_range(dt.datetime(1990, 1, 1), dt.datetime(1990, 1, 1) + dt.timedelta(days=m-1))
index = np.repeat(index, n)

df = pd.DataFrame(np.random.randn(n*m, 1), columns=['x'], index=index)
ind = np.random.randint(0, int(n / 100), len(df))
df['c'] = np.concatenate([np.linspace(0, n-1, n, dtype=int)] * m)
df['ind'] = ind

start = dt.datetime.now()
t = CSRank('x', groups='ind')
res1 = t.transform(df, category_field='c')
print("\nFinance-Python (cs rank): {0}s".format(dt.datetime.now() - start))

start = dt.datetime.now()
df2 = df.reset_index()
res2 = df2.groupby(['index', 'ind']).apply(lambda x: x['x'].rank())
print("Pandas (cs rank): {0}s".format(dt.datetime.now() - start))

res2 = pd.DataFrame({'index': res2.index.get_level_values(2), 'exp_rank': res2.values})
res2.sort_values('index', inplace=True)
res1['exp_rank'] = res2['exp_rank'].values
diff = res1['transformed'] - res1['exp_rank']
print("total rank difference: {0}".format(np.abs(diff).sum()))

# percentile

start = dt.datetime.now()
t = CSQuantiles('x', groups='ind')
res1 = t.transform(df, category_field='c')
print("\nFinance-Python (cs percentile): {0}s".format(dt.datetime.now() - start))

start = dt.datetime.now()
df2 = df.reset_index()
res2 = df2.groupby(['index', 'ind']).apply(lambda x: x['x'].rank() / (len(x) + 1))
print("Pandas (cs percentile): {0}s".format(dt.datetime.now() - start))

res2 = pd.DataFrame({'index': res2.index.get_level_values(2), 'exp_rank': res2.values})
res2.sort_values('index', inplace=True)
res1['exp_rank'] = res2['exp_rank'].values
diff = res1['transformed'] - res1['exp_rank']
print("total percentile difference: {0}".format(np.abs(diff).sum()))

# zscore

start = dt.datetime.now()
t = CSZScore('x', groups='ind')
res1 = t.transform(df, category_field='c')
print("\nFinance-Python (cs zscore): {0}s".format(dt.datetime.now() - start))

start = dt.datetime.now()
df2 = df.reset_index()
res2 = df2.groupby(['index', 'ind']).apply(lambda x: (x['x'] - x['x'].mean()) / x['x'].std(ddof=0))
print("Pandas (cs zscore): {0}s".format(dt.datetime.now() - start))

res2 = pd.DataFrame({'index': res2.index.get_level_values(2), 'exp_rank': res2.values})
res2.sort_values('index', inplace=True)
res1['exp_rank'] = res2['exp_rank'].values
diff = res1['transformed'] - res1['exp_rank']
print("total zscore difference: {0}".format(np.abs(diff).sum()))


text:
package com.airbnb.epoxy;

import androidx.annotation.NonNull;

/**
 * Thrown if a model is changed after it is added to an {@link com.airbnb.epoxy.EpoxyController}.
 */
class ImmutableModelException extends RuntimeException {
  private static final String MODEL_CANNOT_BE_CHANGED_MESSAGE =
      "Epoxy attribute fields on a model cannot be changed once the model is added to a "
          + "controller. Check that these fields are not updated, or that the assigned objects "
          + "are not mutated, outside of the buildModels method. The only exception is if "
          + "the change is made inside an Interceptor callback. Consider using an interceptor"
          + " if you need to change a model after it is added to the controller and before it"
          + " is set on the adapter. If the model is already set on the adapter then you must"
          + " call `requestModelBuild` instead to recreate all models.";

  ImmutableModelException(EpoxyModel model, int modelPosition) {
    this(model, "", modelPosition);
  }

  ImmutableModelException(EpoxyModel model,
      String descriptionOfWhenChangeHappened, int modelPosition) {
    super(buildMessage(model, descriptionOfWhenChangeHappened, modelPosition));
  }

  @NonNull
  private static String buildMessage(EpoxyModel model,
      String descriptionOfWhenChangeHappened, int modelPosition) {
    return new StringBuilder(descriptionOfWhenChangeHappened)
        .append(" Position: ")
        .append(modelPosition)
        .append(" Model: ")
        .append(model.toString())
        .append("\n\n")
        .append(MODEL_CANNOT_BE_CHANGED_MESSAGE)
        .toString();
  }
}


text:
module Text.Noise.Compiler
( compile
, CompileError(..)
, FunctionError(..)
) where

import Data.Function
import Data.Either (partitionEithers)
import Control.Monad
import Control.Applicative
import qualified Data.Map as Map
import qualified Data.List as List
import qualified Text.Noise.Parser.AST as AST
import qualified Text.Noise.Compiler.Document as D
import qualified Text.Noise.Compiler.Document.Color as Color
import qualified Text.Noise.Compiler.Function as F
import qualified Text.Noise.Compiler.Builtin as Builtin
import Text.Noise.Compiler.Error (CompileError(..), FunctionError(..))

type Compiled a = Either CompileError a

type Definitions = Map.Map AST.IdentifierPath (F.Function F.Value)

data CompileState a = CompileState Definitions [a]

throw :: CompileError -> Compiled a
throw = Left

compile :: AST.SourceFile -> Compiled D.Document
compile (AST.SourceFile statements _) = do
  CompileState _ elems <- compileStatements statements
  return $ D.Document elems

compileStatementsWithDefs :: (F.FromValue a) => Definitions -> [AST.Statement] -> Compiled (CompileState a)
compileStatementsWithDefs defs = foldM compileStatement (CompileState defs [])

compileStatements :: (F.FromValue a) => [AST.Statement] -> Compiled (CompileState a)
compileStatements = compileStatementsWithDefs Builtin.definitions

compileStatement :: (F.FromValue a) => CompileState a -> AST.Statement -> Compiled (CompileState a)
compileStatement (CompileState defs xs) (AST.ExpressionStatement expression) = do
  value <- evaluate defs expression
  case F.fromValue value of
    Just x  -> return $ CompileState defs (xs ++ [x])
    Nothing -> throw $ ExpressionStatementTypeError expression
compileStatement (CompileState defs elems) (AST.DefinitionStatement _ fnPrototype expression _) = do
  (functionPath, argNames) <- compileFunctionPrototype fnPrototype
  let definition = compileFunctionDef defs argNames expression
  return $ CompileState (Map.insert functionPath definition defs) elems

compileFunctionDef :: Definitions -> [AST.Identifier] -> AST.Expression -> F.Function F.Value
compileFunctionDef defs argNames expression = do
  argValues <- map return <$> mapM F.requireArg argNames
  let argDefs = Map.fromList $ zip (map return argNames) argValues
  let localDefs = argDefs `Map.union` defs
  case evaluate localDefs expression of
    Left err    -> F.throw (F.CompileError err)
    Right value -> return value
  where

compileFunctionPrototype :: AST.FunctionPrototype -> Compiled (AST.IdentifierPath, [AST.Identifier])
compileFunctionPrototype (AST.FunctionPrototype (AST.QualifiedIdentifier path _) args _)
  | not $ null duplicateArgs = throw $ DuplicatedArgumentPrototypeError (head duplicateArgs)
  | otherwise                = return (path, argNames)
  where duplicateArgs = duplicatesBy ((==) `on` argName) args
        argNames = [name | AST.RequiredArgumentPrototype name _ <- args]
        argName (AST.RequiredArgumentPrototype n _) = n

duplicatesBy :: (a -> a -> Bool) -> [a] -> [a]
duplicatesBy _ [] = []
duplicatesBy cmp (x:xs) =
  filter (cmp x) xs ++ duplicatesBy cmp (List.deleteBy cmp x xs)

evaluate :: Definitions -> AST.Expression -> Compiled F.Value
evaluate _ (AST.FloatLiteral x _)  = return (F.NumberValue x)
evaluate _ (AST.StringLiteral x _) = return (F.StringValue x)
evaluate _ (AST.ColorLiteral x _)  = case Color.fromHex x of
  Just c  -> return (F.ColorValue c)
evaluate defs (AST.FunctionCall identifier args block _) = do
  function <- lookUpFunction defs identifier
  (posArgs, kwArgs) <- evaluateArguments defs args
  blockArgs <- evaluateBlock defs block
  case F.call function posArgs kwArgs blockArgs of
    Left callError -> throw (FunctionCallError identifier callError)
    Right value    -> return value
evaluate defs (AST.InfixOperation (AST.Operator op _) left right) =
  fmap F.NumberValue $ operationFn
    <$> evaluateOperand defs left
    <*> evaluateOperand defs right
  where operationFn = case op of
          AST.Add -> (+)
          AST.Sub -> (-)
          AST.Mul -> (*)
          AST.Div -> (/)
evaluate defs (AST.PrefixOperation (AST.Operator op _) expr) =
  fmap F.NumberValue $ operationFn <$> evaluateOperand defs expr
  where operationFn = case op of
          AST.Sub -> negate
          _       -> id

evaluateOperand :: Definitions -> AST.Expression -> Compiled D.Number
evaluateOperand defs expression = do
  value <- evaluate defs expression
  case F.fromValue value of
    Just x  -> return x
    Nothing -> throw (OperandTypeError expression)

evaluateBlock :: Definitions -> Maybe AST.Block -> Compiled [F.Value]
evaluateBlock _ Nothing = return []
evaluateBlock defs (Just (AST.Block _ statements _ _)) = do
  CompileState _ elems <- compileStatementsWithDefs defs statements
  return elems

lookUpFunction :: Definitions -> AST.QualifiedIdentifier -> Compiled (F.Function F.Value)
lookUpFunction defs identifier@(AST.QualifiedIdentifier path _) =
  case Map.lookup path defs of
    Just fn -> return fn
    Nothing -> throw (UndefinedFunctionError identifier)

evaluateArguments :: Definitions -> [AST.Argument] -> Compiled ([F.Value], [(String, F.Value)])
evaluateArguments defs args
  | not $ null duplicateArgs   = throw $ DuplicatedKeywordArgumentError (head duplicateArgs)
  | not $ null trailingPosArgs = throw $ PositionalArgumentError (head trailingPosArgs)
  | otherwise                  = partitionEithers <$> mapM (evaluateArgument defs) args
  where duplicateArgs = duplicatesBy ((==) `on` keyword) keywordArgs
        keywordArgs = filter (not . isPosArg) args
        keyword (AST.KeywordArgument k _ _) = k
        keyword _ = ""
        trailingPosArgs = dropWhile (not . isPosArg) $ dropWhile isPosArg args
        isPosArg (AST.PositionalArgument _) = True
        isPosArg _ = False

evaluateArgument :: Definitions -> AST.Argument -> Compiled (Either F.Value (String, F.Value))
evaluateArgument defs arg = case arg of
  AST.PositionalArgument expression ->
    Left <$> evaluate defs expression
  AST.KeywordArgument keyword expression _ ->
    Right . (,) keyword <$> evaluate defs expression


text:
from unittest.mock import patch

from django.contrib.auth.models import User
from django.core.management import call_command
from django.db.models import BigAutoField
from django.test import TestCase

from rest_framework_simplejwt.exceptions import TokenError
from rest_framework_simplejwt.serializers import TokenVerifySerializer
from rest_framework_simplejwt.settings import api_settings
from rest_framework_simplejwt.token_blacklist.models import (
    BlacklistedToken, OutstandingToken,
)
from rest_framework_simplejwt.tokens import (
    AccessToken, RefreshToken, SlidingToken,
)
from rest_framework_simplejwt.utils import aware_utcnow, datetime_from_epoch

from .utils import MigrationTestCase, override_api_settings

class TestTokenBlacklist(TestCase):
    def setUp(self):
        self.user = User.objects.create(
            username='test_user',
            password='test_password',
        )

    def test_sliding_tokens_are_added_to_outstanding_list(self):
        token = SlidingToken.for_user(self.user)

        qs = OutstandingToken.objects.all()
        outstanding_token = qs.first()

        self.assertEqual(qs.count(), 1)
        self.assertEqual(outstanding_token.user, self.user)
        self.assertEqual(outstanding_token.jti, token['jti'])
        self.assertEqual(outstanding_token.token, str(token))
        self.assertEqual(outstanding_token.created_at, token.current_time)
        self.assertEqual(outstanding_token.expires_at, datetime_from_epoch(token['exp']))

    def test_refresh_tokens_are_added_to_outstanding_list(self):
        token = RefreshToken.for_user(self.user)

        qs = OutstandingToken.objects.all()
        outstanding_token = qs.first()

        self.assertEqual(qs.count(), 1)
        self.assertEqual(outstanding_token.user, self.user)
        self.assertEqual(outstanding_token.jti, token['jti'])
        self.assertEqual(outstanding_token.token, str(token))
        self.assertEqual(outstanding_token.created_at, token.current_time)
        self.assertEqual(outstanding_token.expires_at, datetime_from_epoch(token['exp']))

    def test_access_tokens_are_not_added_to_outstanding_list(self):
        AccessToken.for_user(self.user)

        qs = OutstandingToken.objects.all()

        self.assertFalse(qs.exists())

    def test_token_will_not_validate_if_blacklisted(self):
        token = RefreshToken.for_user(self.user)
        outstanding_token = OutstandingToken.objects.first()

        # Should raise no exception
        RefreshToken(str(token))

        # Add token to blacklist
        BlacklistedToken.objects.create(token=outstanding_token)

        with self.assertRaises(TokenError) as e:
            # Should raise exception
            RefreshToken(str(token))
            self.assertIn('blacklisted', e.exception.args[0])

    def test_tokens_can_be_manually_blacklisted(self):
        token = RefreshToken.for_user(self.user)

        # Should raise no exception
        RefreshToken(str(token))

        self.assertEqual(OutstandingToken.objects.count(), 1)

        # Add token to blacklist
        blacklisted_token, created = token.blacklist()

        # Should not add token to outstanding list if already present
        self.assertEqual(OutstandingToken.objects.count(), 1)

        # Should return blacklist record and boolean to indicate creation
        self.assertEqual(blacklisted_token.token.jti, token['jti'])
        self.assertTrue(created)

        with self.assertRaises(TokenError) as e:
            # Should raise exception
            RefreshToken(str(token))
            self.assertIn('blacklisted', e.exception.args[0])

        # If blacklisted token already exists, indicate no creation through
        # boolean
        blacklisted_token, created = token.blacklist()
        self.assertEqual(blacklisted_token.token.jti, token['jti'])
        self.assertFalse(created)

        # Should add token to outstanding list if not already present
        new_token = RefreshToken()
        blacklisted_token, created = new_token.blacklist()
        self.assertEqual(blacklisted_token.token.jti, new_token['jti'])
        self.assertTrue(created)

        self.assertEqual(OutstandingToken.objects.count(), 2)

class TestTokenBlacklistFlushExpiredTokens(TestCase):
    def setUp(self):
        self.user = User.objects.create(
            username='test_user',
            password='test_password',
        )

    def test_it_should_delete_any_expired_tokens(self):
        # Make some tokens that won't expire soon
        not_expired_1 = RefreshToken.for_user(self.user)
        not_expired_2 = RefreshToken.for_user(self.user)
        not_expired_3 = RefreshToken()

        # Blacklist fresh tokens
        not_expired_2.blacklist()
        not_expired_3.blacklist()

        # Make tokens with fake exp time that will expire soon
        fake_now = aware_utcnow() - api_settings.REFRESH_TOKEN_LIFETIME

        with patch('rest_framework_simplejwt.tokens.aware_utcnow') as fake_aware_utcnow:
            fake_aware_utcnow.return_value = fake_now
            expired_1 = RefreshToken.for_user(self.user)
            expired_2 = RefreshToken()

        # Blacklist expired tokens
        expired_1.blacklist()
        expired_2.blacklist()

        # Make another token that won't expire soon
        not_expired_4 = RefreshToken.for_user(self.user)

        # Should be certain number of outstanding tokens and blacklisted
        # tokens
        self.assertEqual(OutstandingToken.objects.count(), 6)
        self.assertEqual(BlacklistedToken.objects.count(), 4)

        call_command('flushexpiredtokens')

        # Expired outstanding *and* blacklisted tokens should be gone
        self.assertEqual(OutstandingToken.objects.count(), 4)
        self.assertEqual(BlacklistedToken.objects.count(), 2)

        self.assertEqual(
            [i.jti for i in OutstandingToken.objects.order_by('id')],
            [not_expired_1['jti'], not_expired_2['jti'], not_expired_3['jti'], not_expired_4['jti']],
        )
        self.assertEqual(
            [i.token.jti for i in BlacklistedToken.objects.order_by('id')],
            [not_expired_2['jti'], not_expired_3['jti']],
        )

class TestPopulateJtiHexMigration(MigrationTestCase):
    migrate_from = ('token_blacklist', '0002_outstandingtoken_jti_hex')
    migrate_to = ('token_blacklist', '0003_auto_20171017_2007')

    def setUp(self):
        self.user = User.objects.create(
            username='test_user',
            password='test_password',
        )

        super().setUp()

    def setUpBeforeMigration(self, apps):
        # Ensure some tokens are present in the outstanding list
        RefreshToken.for_user(self.user)
        RefreshToken.for_user(self.user)

        OutstandingToken = apps.get_model('token_blacklist', 'OutstandingToken')

        self.expected_hexes = [i.jti.hex for i in OutstandingToken.objects.all()]

    def test_jti_field_should_contain_uuid_hex_strings(self):
        OutstandingToken = self.apps.get_model('token_blacklist', 'OutstandingToken')

        actual_hexes = [i.jti_hex for i in OutstandingToken.objects.all()]

        self.assertEqual(actual_hexes, self.expected_hexes)

class TokenVerifySerializerShouldHonourBlacklist(MigrationTestCase):
    migrate_from = ('token_blacklist', '0002_outstandingtoken_jti_hex')
    migrate_to = ('token_blacklist', '0003_auto_20171017_2007')

    def setUp(self):
        self.user = User.objects.create(
            username='test_user',
            password='test_password',
        )

        super().setUp()

    def test_token_verify_serializer_should_honour_blacklist_if_blacklisting_enabled(self):
        with override_api_settings(BLACKLIST_AFTER_ROTATION=True):
            refresh_token = RefreshToken.for_user(self.user)
            refresh_token.blacklist()

            serializer = TokenVerifySerializer(data={"token": str(refresh_token)})
            self.assertFalse(serializer.is_valid())

    def test_token_verify_serializer_should_not_honour_blacklist_if_blacklisting_not_enabled(self):
        with override_api_settings(BLACKLIST_AFTER_ROTATION=False):
            refresh_token = RefreshToken.for_user(self.user)
            refresh_token.blacklist()

            serializer = TokenVerifySerializer(data={"token": str(refresh_token)})
            self.assertTrue(serializer.is_valid())

class TestBigAutoFieldIDMigration(MigrationTestCase):
    migrate_from = ('token_blacklist', '0007_auto_20171017_2214')
    migrate_to = ('token_blacklist', '0008_migrate_to_bigautofield')

    def test_outstandingtoken_id_field_is_biagauto_field(self):
        OutstandingToken = self.apps.get_model('token_blacklist', 'OutstandingToken')
        assert isinstance(OutstandingToken._meta.get_field('id'), BigAutoField)

    def test_blacklistedtoken_id_field_is_biagauto_field(self):
        BlacklistedToken = self.apps.get_model('token_blacklist', 'BlacklistedToken')
        assert isinstance(BlacklistedToken._meta.get_field('id'), BigAutoField)


text:
#pragma once
#include <aws/appconfig/AppConfig_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/appconfig/model/Application.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace AppConfig
{
namespace Model
{
  class AWS_APPCONFIG_API ListApplicationsResult
  {
  public:
    ListApplicationsResult();
    ListApplicationsResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    ListApplicationsResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
The elements from this collection.

     */
    inline const Aws::Vector<Application>& GetItems() const{ return m_items; }

    /**
     *
The elements from this collection.

     */
    inline void SetItems(const Aws::Vector<Application>& value) { m_items = value; }

    /**
     *
The elements from this collection.

     */
    inline void SetItems(Aws::Vector<Application>&& value) { m_items = std::move(value); }

    /**
     *
The elements from this collection.

     */
    inline ListApplicationsResult& WithItems(const Aws::Vector<Application>& value) { SetItems(value); return *this;}

    /**
     *
The elements from this collection.

     */
    inline ListApplicationsResult& WithItems(Aws::Vector<Application>&& value) { SetItems(std::move(value)); return *this;}

    /**
     *
The elements from this collection.

     */
    inline ListApplicationsResult& AddItems(const Application& value) { m_items.push_back(value); return *this; }

    /**
     *
The elements from this collection.

     */
    inline ListApplicationsResult& AddItems(Application&& value) { m_items.push_back(std::move(value)); return *this; }

    /**
     *
The token for the next set of items to return. Use this token to get the next
     * set of results.

     */
    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    /**
     *
The token for the next set of items to return. Use this token to get the next
     * set of results.

     */
    inline void SetNextToken(const Aws::String& value) { m_nextToken = value; }

    /**
     *
The token for the next set of items to return. Use this token to get the next
     * set of results.

     */
    inline void SetNextToken(Aws::String&& value) { m_nextToken = std::move(value); }

    /**
     *
The token for the next set of items to return. Use this token to get the next
     * set of results.

     */
    inline void SetNextToken(const char* value) { m_nextToken.assign(value); }

    /**
     *
The token for the next set of items to return. Use this token to get the next
     * set of results.

     */
    inline ListApplicationsResult& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    /**
     *
The token for the next set of items to return. Use this token to get the next
     * set of results.

     */
    inline ListApplicationsResult& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}

    /**
     *
The token for the next set of items to return. Use this token to get the next
     * set of results.

     */
    inline ListApplicationsResult& WithNextToken(const char* value) { SetNextToken(value); return *this;}

  private:

    Aws::Vector<Application> m_items;

    Aws::String m_nextToken;
  };

} // namespace Model
} // namespace AppConfig
} // namespace Aws


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>calendar module — ArcherBashPYDocs 1.0.0. documentation</title>

  <link href='https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic|Roboto+Slab:400,700|Inconsolata:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>

    <link rel="stylesheet" href="_static/css/theme.css" type="text/css" />

    <link rel="top" title="ArcherBashPYDocs 1.0.0. documentation" href="index.html"/>

           ArcherBashPYDocs

  <form id="rtd-search-form" class="wy-form" action="search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

        ArcherBashPYDocs

Docs »

calendar module

           View page source

calendar module¶

Calendar printing functions

Note when comparing these calendars to the ones printed by cal(1): By
default, these calendars have Monday as the first day of the week, and
Sunday as the last (the European convention). Use setfirstweekday() to
set the first day of the week (0=Monday, 6=Sunday).

exception calendar.IllegalMonthError(month)[source]¶

Bases: ValueError

exception calendar.IllegalWeekdayError(weekday)[source]¶

Bases: ValueError

calendar.setfirstweekday(firstweekday)[source]¶

calendar.isleap(year)[source]¶

Return True for leap years, False for non-leap years.

calendar.leapdays(y1, y2)[source]¶

Return number of leap years in range [y1, y2).
Assume y1 <= y2.

calendar.weekday(year, month, day)[source]¶

Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12),
day (1-31).

calendar.monthrange(year, month)[source]¶

Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for
year, month.

calendar.timegm(tuple)[source]¶

Unrelated but handy function to calculate Unix timestamp from GMT.

        © Copyright 2015, Weldon Henson.

  Built with Sphinx using a theme provided by Read the Docs.


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Shared.Extensions;

namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.Structure
{
    internal static class OmniSharpBlockStructureService
    {
        public static async Task<OmniSharpBlockStructure> GetBlockStructureAsync(Document document, CancellationToken cancellationToken)
        {
            var service = document.GetRequiredLanguageService<BlockStructureService>();
            var blockStructure = await service.GetBlockStructureAsync(document, cancellationToken).ConfigureAwait(false);
            if (blockStructure != null)
            {
                return new OmniSharpBlockStructure(blockStructure.Spans.SelectAsArray(x => new OmniSharpBlockSpan(x.Type, x.IsCollapsible, x.TextSpan, x.HintSpan, x.BannerText, x.AutoCollapse, x.IsDefaultCollapsed)));
            }
            else
            {
                return null;
            }
        }
    }
}


text:
<?xml version="1.0"?>
<doc>
    <assembly>
        <name>Autofac.Extras.Moq</name>
    </assembly>
    <members>
        <member name="T:Autofac.Extras.Moq.AutoMock">
            <summary>
            Wrapper around <see cref="N:Autofac"/> and <see cref="N:Autofac.Extras.Moq"/>
            </summary>
        </member>
        <member name="M:Autofac.Extras.Moq.AutoMock.Finalize">
            <summary>
            Finalizes an instance of the <see cref="T:Autofac.Extras.Moq.AutoMock"/> class.
            </summary>
        </member>
        <member name="M:Autofac.Extras.Moq.AutoMock.GetLoose">
            <summary>
            Create new <see cref="T:Autofac.Extras.Moq.AutoMock"/> instance with loose mock behavior.
            </summary>
            <seealso cref="P:Autofac.Extras.Moq.AutoMock.MockRepository"/>
            <returns>Container initialized for loose behavior.</returns>
        </member>
        <member name="M:Autofac.Extras.Moq.AutoMock.GetStrict">
            <summary>
            Create new <see cref="T:Autofac.Extras.Moq.AutoMock"/> instance with strict mock behavior.
            </summary>
            <seealso cref="P:Autofac.Extras.Moq.AutoMock.MockRepository"/>
            <returns>Container initialized for loose behavior.</returns>
        </member>
        <member name="M:Autofac.Extras.Moq.AutoMock.GetFromRepository(Moq.MockRepository)">
            <summary>
            Create new <see cref="T:Autofac.Extras.Moq.AutoMock"/> instance that will create mocks with behavior defined by <c>repository</c>.
            </summary>
            <param name="repository"></param>
            <returns></returns>
        </member>
        <member name="M:Autofac.Extras.Moq.AutoMock.Dispose">
            <summary>
            Verifies mocks and disposes internal container.
            </summary>
        </member>
        <member name="M:Autofac.Extras.Moq.AutoMock.Dispose(System.Boolean)">
            <summary>
            Handles disposal of managed and unmanaged resources.
            </summary>
            <param name="disposing">
            <see langword="true"/> to dispose of managed resources (during a manual execution
            of <see cref="M:Autofac.Extras.Moq.AutoMock.Dispose"/>); or
            <see langword="false"/> if this is getting run as part of finalization where
            managed resources may have already been cleaned up.
            </param>
        </member>
        <member name="M:Autofac.Extras.Moq.AutoMock.Mock``1(Autofac.Core.Parameter[])">
            <summary>
            Finds (creating if needed) the actual mock for the provided type
            </summary>
            <typeparam name="T">Type to mock</typeparam>
            <param name="parameters">Optional parameters</param>
            <returns>Mock</returns>
        </member>
        <member name="M:Autofac.Extras.Moq.AutoMock.Create``1(Autofac.Core.Parameter[])">
            <summary>
            Resolve the specified type in the container (register it if needed)
            </summary>
            <typeparam name="T">Service</typeparam>
            <param name="parameters">Optional parameters</param>
            <returns>The service.</returns>
        </member>
        <member name="M:Autofac.Extras.Moq.AutoMock.Provide``2(Autofac.Core.Parameter[])">
            <summary>
            Resolve the specified type in the container (register it if needed)
            </summary>
            <typeparam name="TService">Service</typeparam>
            <typeparam name="TImplementation">The implementation of the service.</typeparam>
            <param name="parameters">Optional parameters</param>
            <returns>The service.</returns>
        </member>
        <member name="M:Autofac.Extras.Moq.AutoMock.Provide``1(``0)">
            <summary>
            Resolve the specified type in the container (register specified instance if needed)
            </summary>
            <typeparam name="TService">Service</typeparam>
            <returns>The instance resolved from container.</returns>
        </member>
        <member name="P:Autofac.Extras.Moq.AutoMock.MockRepository">
            <summary>
            <see cref="P:Autofac.Extras.Moq.AutoMock.MockRepository"/> instance responsible for expectations and mocks.
            </summary>
        </member>
        <member name="P:Autofac.Extras.Moq.AutoMock.Container">
            <summary>
            <see cref="T:Autofac.IContainer"/> that handles the component resolution.
            </summary>
        </member>
        <member name="P:Autofac.Extras.Moq.AutoMock.VerifyAll">
            <summary>
            Gets or sets a value indicating whether all mocks are verified.
            </summary>
            <value><c>true</c> to verify all mocks. <c>false</c> (default) to verify only mocks marked Verifiable.</value>
        </member>
        <member name="T:Autofac.Extras.Moq.MoqRegistrationHandler">
            <summary> Resolves unknown interfaces and Mocks using the <see cref="T:Moq.MockRepository"/> from the scope. </summary>
        </member>
        <member name="M:Autofac.Extras.Moq.MoqRegistrationHandler.#ctor">
            <summary>
            </summary>
        </member>
        <member name="M:Autofac.Extras.Moq.MoqRegistrationHandler.RegistrationsFor(Autofac.Core.Service,System.Func{Autofac.Core.Service,System.Collections.Generic.IEnumerable{Autofac.Core.IComponentRegistration}})">
            <summary>
            Retrieve a registration for an unregistered service, to be used
            by the container.
            </summary>
            <param name="service">The service that was requested.</param>
            <param name="registrationAccessor">Not used; required by the interface</param>
            <returns>
            Registrations for the service.
            </returns>
        </member>
        <member name="M:Autofac.Extras.Moq.MoqRegistrationHandler.CreateMock(Autofac.IComponentContext,Autofac.Core.TypedService)">
            <summary>
            Creates a mock object.
            </summary>
            <param name="context">The component context.</param>
            <param name="typedService">The typed service.</param>
            <returns></returns>
        </member>
    </members>
</doc>


text:
from __future__ import unicode_literals

from django.db import models
from django.utils.translation import ugettext_lazy as _
from future.utils import python_2_unicode_compatible

from fluent_contents.models import ContentItemManager
from fluent_contents.models.db import ContentItem

@python_2_unicode_compatible
class TwitterRecentEntriesItem(ContentItem):
    """
    Content item to display recent entries of a twitter user.
    """

    title = models.CharField(
        _("Title"),
        max_length=200,
        blank=True,
        help_text=_(
            "You may use Twitter markup here, such as a #hashtag or @username."
        ),
    )

    twitter_user = models.CharField(_("Twitter user"), max_length=75)
    amount = models.PositiveSmallIntegerField(_("Number of results"), default=5)

    footer_text = models.CharField(
        _("Footer text"),
        max_length=200,
        blank=True,
        help_text=_(
            "You may use Twitter markup here, such as a #hashtag or @username."
        ),
    )
    include_retweets = models.BooleanField(_("Include retweets"), default=False)
    include_replies = models.BooleanField(_("Include replies"), default=False)

    objects = ContentItemManager()  # Avoid Django 1.10 migrations

    def __str__(self):
        return self.title or self.twitter_user

    class Meta:
        verbose_name = _("Recent twitter entries")
        verbose_name_plural = _("Recent twitter entries")

@python_2_unicode_compatible
class TwitterSearchItem(ContentItem):
    """
    Content item to display recent entries of a twitter user.
    """

    title = models.CharField(
        _("Title"),
        max_length=200,
        blank=True,
        help_text=_(
            "You may use Twitter markup here, such as a #hashtag or @username."
        ),
    )

    query = models.CharField(
        _("Search for"),
        max_length=200,
        default="",
        help_text=_(
            'Twitter search syntax is allowed.'
        ),
    )
    amount = models.PositiveSmallIntegerField(_("Number of results"), default=5)

    footer_text = models.CharField(
        _("Footer text"),
        max_length=200,
        blank=True,
        help_text=_(
            "You may use Twitter markup here, such as a #hashtag or @username."
        ),
    )
    include_retweets = models.BooleanField(_("Include retweets"), default=False)
    include_replies = models.BooleanField(_("Include replies"), default=False)

    objects = ContentItemManager()  # Avoid Django 1.10 migrations

    def __str__(self):
        return self.title or self.query

    class Meta:
        verbose_name = _("Twitter search feed")
        verbose_name_plural = _("Twitter search feed")


text:
package org.apache.skywalking.oap.server.receiver.clr.module;

import org.apache.skywalking.oap.server.library.module.ModuleDefine;

/**
 *
 **/
public class CLRModule extends ModuleDefine {

    public CLRModule() {
        super("receiver-clr");
    }

    @Override
    public Class[] services() {
        return new Class[0];
    }
}


text:
module Unimatrix
  module Authorization

    module ClassMethods
      def requires_resource_owner( name, options = {} )
        before_action( RequiresResourceOwner.new, options )
      end
    end

    class RequiresResourceOwner
      def before( controller )
        access_token = controller.params[ 'access_token' ]

        resource_owner =
          controller.request_resource_owner( access_token )
      end
    end

    def self.included( controller )
      controller.extend( ClassMethods )
    end

    def request_resource_owner( access_token )
      user = Unimatrix::Authorization::Operation.new( '/resource_owner' ).
      where( { access_token: access_token } ).
      query
    end

    def resource_owner=( attributes )
      @resource_owner = attributes
    end

    def resource_owner
      @resource_owner ||= begin
        request_resource_owner( params[ :access_token ] )
      end
    end

  end
end


text:
<?php

declare(strict_types=1);

namespace Pdp;

interface DomainNameResolver
{
    /**
     * Returns the effective TLD info for a given domain against an data source.
     *
     * If the effective TLD can not be resolved it returns a ResolvedDomainName with a null suffix
     * If the host is not a valid domain it returns a ResolvedDomainName with a null Domain name
     */
    public function resolve(Host $host): ResolvedDomainName;
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE762_Mismatched_Memory_Management_Routines__strdup_delete_array_wchar_t_84.h
Label Definition File: CWE762_Mismatched_Memory_Management_Routines__strdup_delete_array.label.xml
Template File: sources-sinks-84.tmpl.h
*/
/*
 * @description
 * CWE: 762 Mismatched Memory Management Routines
 * BadSource:  Allocate data using wcsdup()
 * GoodSource: Allocate data using new []
 * Sinks:
 *    GoodSink: Deallocate data using free()
 *    BadSink : Deallocate data using delete []
 * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

namespace CWE762_Mismatched_Memory_Management_Routines__strdup_delete_array_wchar_t_84
{

#ifndef OMITBAD

class CWE762_Mismatched_Memory_Management_Routines__strdup_delete_array_wchar_t_84_bad
{
public:
    CWE762_Mismatched_Memory_Management_Routines__strdup_delete_array_wchar_t_84_bad(wchar_t * dataCopy);
    ~CWE762_Mismatched_Memory_Management_Routines__strdup_delete_array_wchar_t_84_bad();

private:
    wchar_t * data;
};

#endif /* OMITBAD */

#ifndef OMITGOOD

class CWE762_Mismatched_Memory_Management_Routines__strdup_delete_array_wchar_t_84_goodG2B
{
public:
    CWE762_Mismatched_Memory_Management_Routines__strdup_delete_array_wchar_t_84_goodG2B(wchar_t * dataCopy);
    ~CWE762_Mismatched_Memory_Management_Routines__strdup_delete_array_wchar_t_84_goodG2B();

private:
    wchar_t * data;
};

class CWE762_Mismatched_Memory_Management_Routines__strdup_delete_array_wchar_t_84_goodB2G
{
public:
    CWE762_Mismatched_Memory_Management_Routines__strdup_delete_array_wchar_t_84_goodB2G(wchar_t * dataCopy);
    ~CWE762_Mismatched_Memory_Management_Routines__strdup_delete_array_wchar_t_84_goodB2G();

private:
    wchar_t * data;
};

#endif /* OMITGOOD */

}


text:
import React from 'react';
import RentalItem from './RentalItem'
import ExpenseItem from './ExpenseItem'

import VenueExpensesFooter from './VenueExpensesFooter'
export default class VenueExpenses extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      item1: '',
      price1: '',
      quantity1: '',
      total1: '',
      item2: '',
      price2: '',
      quantity2: '',
      total2: '',
      rentalFee: '',
      grandTotal: ''

    };
    this.handleMount = this.handleMount.bind(this)

  }
  handleMount() {
    var that = this
    setTimeout(function() {
      that.setState({
        item1: 'Meals'
      })
    }, 2800)

    setTimeout(function() {
      that.setState({

        price1: that.props.mealPackagePrice
      })
    }, 3200)
    setTimeout(function() {
      that.setState({

        quantity1: that.props.mealPackageQuantity,
        total1: '$20,000'
      })
    }, 3500)
    setTimeout(function() {
      that.setState({

        item2: 'Valet'
      })
    }, 3600)
    setTimeout(function() {
      that.setState({

        price2: that.props.valetParkingPrice
      })
    }, 3900)
    setTimeout(function() {
      that.setState({
        quantity2: that.props.valetParkingQuantity,
        total2: '$2,000'
      })
    }, 4100)
    setTimeout(function() {
      that.setState({

        rentalFee: '$5,000'
      })
    }, 4200)

    setTimeout(function() {
      that.setState({

        grandTotal: '$27,000'
      })
    }, 4200)

  }
  componentDidMount() {
    this.handleMount()
  }
  render() {
    return (

 EXPENSES:

        <ExpenseItem item={this.state.item1} price={this.state.price1} quantity={this.state.quantity1} total={this.state.total1}/>
        <ExpenseItem item={this.state.item2} price={this.state.price2} quantity={this.state.quantity2} total={this.state.total2}/>
        <RentalItem price={this.state.rentalFee}/>
        <VenueExpensesFooter onPayChange={this.props.onHandlePayChange} pay={this.props.pay} total={this.state.grandTotal}/>

    );
  }
}


text:
#ifndef AGG_PIXFMT_RGB_INCLUDED
#define AGG_PIXFMT_RGB_INCLUDED

#include <cstring>
#include "agg_pixfmt_base.h"
#include "agg_rendering_buffer.h"

namespace agg
{

    //=====================================================apply_gamma_dir_rgb
    template<class ColorT, class Order, class GammaLut> class apply_gamma_dir_rgb
    {
    public:
        typedef typename ColorT::value_type value_type;

        apply_gamma_dir_rgb(const GammaLut& gamma) : m_gamma(gamma) {}

        AGG_INLINE void operator () (value_type* p)
        {
            p[Order::R] = m_gamma.dir(p[Order::R]);
            p[Order::G] = m_gamma.dir(p[Order::G]);
            p[Order::B] = m_gamma.dir(p[Order::B]);
        }

    private:
        const GammaLut& m_gamma;
    };

    //=====================================================apply_gamma_inv_rgb
    template<class ColorT, class Order, class GammaLut> class apply_gamma_inv_rgb
    {
    public:
        typedef typename ColorT::value_type value_type;

        apply_gamma_inv_rgb(const GammaLut& gamma) : m_gamma(gamma) {}

        AGG_INLINE void operator () (value_type* p)
        {
            p[Order::R] = m_gamma.inv(p[Order::R]);
            p[Order::G] = m_gamma.inv(p[Order::G]);
            p[Order::B] = m_gamma.inv(p[Order::B]);
        }

    private:
        const GammaLut& m_gamma;
    };

    //=========================================================blender_rgb
    template<class ColorT, class Order>
    struct blender_rgb
    {
        typedef ColorT color_type;
        typedef Order order_type;
        typedef typename color_type::value_type value_type;
        typedef typename color_type::calc_type calc_type;
        typedef typename color_type::long_type long_type;

        // Blend pixels using the non-premultiplied form of Alvy-Ray Smith's
        // compositing function. Since the render buffer is opaque we skip the
        // initial premultiply and final demultiply.

        //--------------------------------------------------------------------
        static AGG_INLINE void blend_pix(value_type* p,
            value_type cr, value_type cg, value_type cb, value_type alpha, cover_type cover)
        {
            blend_pix(p, cr, cg, cb, color_type::mult_cover(alpha, cover));
        }

        //--------------------------------------------------------------------
        static AGG_INLINE void blend_pix(value_type* p,
            value_type cr, value_type cg, value_type cb, value_type alpha)
        {
            p[Order::R] = color_type::lerp(p[Order::R], cr, alpha);
            p[Order::G] = color_type::lerp(p[Order::G], cg, alpha);
            p[Order::B] = color_type::lerp(p[Order::B], cb, alpha);
        }
    };

    //======================================================blender_rgb_pre
    template<class ColorT, class Order>
    struct blender_rgb_pre
    {
        typedef ColorT color_type;
        typedef Order order_type;
        typedef typename color_type::value_type value_type;
        typedef typename color_type::calc_type calc_type;
        typedef typename color_type::long_type long_type;

        // Blend pixels using the premultiplied form of Alvy-Ray Smith's
        // compositing function.

        //--------------------------------------------------------------------
        static AGG_INLINE void blend_pix(value_type* p,
            value_type cr, value_type cg, value_type cb, value_type alpha, cover_type cover)
        {
            blend_pix(p,
                color_type::mult_cover(cr, cover),
                color_type::mult_cover(cg, cover),
                color_type::mult_cover(cb, cover),
                color_type::mult_cover(alpha, cover));
        }

        //--------------------------------------------------------------------
        static AGG_INLINE void blend_pix(value_type* p,
            value_type cr, value_type cg, value_type cb, value_type alpha)
        {
            p[Order::R] = color_type::prelerp(p[Order::R], cr, alpha);
            p[Order::G] = color_type::prelerp(p[Order::G], cg, alpha);
            p[Order::B] = color_type::prelerp(p[Order::B], cb, alpha);
        }
    };

    //===================================================blender_rgb_gamma
    template<class ColorT, class Order, class Gamma>
    class blender_rgb_gamma : public blender_base<ColorT, Order>
    {
    public:
        typedef ColorT color_type;
        typedef Order order_type;
        typedef Gamma gamma_type;
        typedef typename color_type::value_type value_type;
        typedef typename color_type::calc_type calc_type;
        typedef typename color_type::long_type long_type;

        //--------------------------------------------------------------------
        blender_rgb_gamma() : m_gamma(0) {}
        void gamma(const gamma_type& g) { m_gamma = &g; }

        //--------------------------------------------------------------------
        AGG_INLINE void blend_pix(value_type* p,
            value_type cr, value_type cg, value_type cb, value_type alpha, cover_type cover)
        {
            blend_pix(p, cr, cg, cb, color_type::mult_cover(alpha, cover));
        }

        //--------------------------------------------------------------------
        AGG_INLINE void blend_pix(value_type* p,
            value_type cr, value_type cg, value_type cb, value_type alpha)
        {
            calc_type r = m_gamma->dir(p[Order::R]);
            calc_type g = m_gamma->dir(p[Order::G]);
            calc_type b = m_gamma->dir(p[Order::B]);
            p[Order::R] = m_gamma->inv(color_type::downscale((m_gamma->dir(cr) - r) * alpha) + r);
            p[Order::G] = m_gamma->inv(color_type::downscale((m_gamma->dir(cg) - g) * alpha) + g);
            p[Order::B] = m_gamma->inv(color_type::downscale((m_gamma->dir(cb) - b) * alpha) + b);
        }

    private:
        const gamma_type* m_gamma;
    };

    //==================================================pixfmt_alpha_blend_rgb
    template<class Blender, class RenBuf, unsigned Step, unsigned Offset = 0>
    class pixfmt_alpha_blend_rgb
    {
    public:
        typedef pixfmt_rgb_tag pixfmt_category;
        typedef RenBuf   rbuf_type;
        typedef Blender  blender_type;
        typedef typename rbuf_type::row_data row_data;
        typedef typename blender_type::color_type color_type;
        typedef typename blender_type::order_type order_type;
        typedef typename color_type::value_type value_type;
        typedef typename color_type::calc_type calc_type;
        enum
        {
            num_components = 3,
            pix_step = Step,
            pix_offset = Offset,
            pix_width = sizeof(value_type) * pix_step
        };
        struct pixel_type
        {
            value_type c[num_components];

            void set(value_type r, value_type g, value_type b)
            {
                c[order_type::R] = r;
                c[order_type::G] = g;
                c[order_type::B] = b;
            }

            void set(const color_type& color)
            {
                set(color.r, color.g, color.b);
            }

            void get(value_type& r, value_type& g, value_type& b) const
            {
                r = c[order_type::R];
                g = c[order_type::G];
                b = c[order_type::B];
            }

            color_type get() const
            {
                return color_type(
                    c[order_type::R],
                    c[order_type::G],
                    c[order_type::B]);
            }

            pixel_type* next()
            {
                return (pixel_type*)(c + pix_step);
            }

            const pixel_type* next() const
            {
                return (const pixel_type*)(c + pix_step);
            }

            pixel_type* advance(int n)
            {
                return (pixel_type*)(c + n * pix_step);
            }

            const pixel_type* advance(int n) const
            {
                return (const pixel_type*)(c + n * pix_step);
            }
        };

    private:
        //--------------------------------------------------------------------
        AGG_INLINE void blend_pix(pixel_type* p,
            value_type r, value_type g, value_type b, value_type a,
            unsigned cover)
        {
            m_blender.blend_pix(p->c, r, g, b, a, cover);
        }

        //--------------------------------------------------------------------
        AGG_INLINE void blend_pix(pixel_type* p,
            value_type r, value_type g, value_type b, value_type a)
        {
            m_blender.blend_pix(p->c, r, g, b, a);
        }

        //--------------------------------------------------------------------
        AGG_INLINE void blend_pix(pixel_type* p, const color_type& c, unsigned cover)
        {
            m_blender.blend_pix(p->c, c.r, c.g, c.b, c.a, cover);
        }

        //--------------------------------------------------------------------
        AGG_INLINE void blend_pix(pixel_type* p, const color_type& c)
        {
            m_blender.blend_pix(p->c, c.r, c.g, c.b, c.a);
        }

        //--------------------------------------------------------------------
        AGG_INLINE void copy_or_blend_pix(pixel_type* p, const color_type& c, unsigned cover)
        {
            if (!c.is_transparent())
            {
                if (c.is_opaque() && cover == cover_mask)
                {
                    p->set(c);
                }
                else
                {
                    blend_pix(p, c, cover);
                }
            }
        }

        //--------------------------------------------------------------------
        AGG_INLINE void copy_or_blend_pix(pixel_type* p, const color_type& c)
        {
            if (!c.is_transparent())
            {
                if (c.is_opaque())
                {
                    p->set(c);
                }
                else
                {
                    blend_pix(p, c);
                }
            }
        }

    public:
        //--------------------------------------------------------------------
        explicit pixfmt_alpha_blend_rgb(rbuf_type& rb) :
            m_rbuf(&rb)
        {}
        void attach(rbuf_type& rb) { m_rbuf = &rb; }

        //--------------------------------------------------------------------
        template<class PixFmt>
        bool attach(PixFmt& pixf, int x1, int y1, int x2, int y2)
        {
            rect_i r(x1, y1, x2, y2);
            if (r.clip(rect_i(0, 0, pixf.width()-1, pixf.height()-1)))
            {
                int stride = pixf.stride();
                m_rbuf->attach(pixf.pix_ptr(r.x1, stride < 0 ? r.y2 : r.y1),
                               (r.x2 - r.x1) + 1,
                               (r.y2 - r.y1) + 1,
                               stride);
                return true;
            }
            return false;
        }

        //--------------------------------------------------------------------
        Blender& blender() { return m_blender; }

        //--------------------------------------------------------------------
        AGG_INLINE unsigned width()  const { return m_rbuf->width();  }
        AGG_INLINE unsigned height() const { return m_rbuf->height(); }
        AGG_INLINE int      stride() const { return m_rbuf->stride(); }

        //--------------------------------------------------------------------
        AGG_INLINE       int8u* row_ptr(int y)       { return m_rbuf->row_ptr(y); }
        AGG_INLINE const int8u* row_ptr(int y) const { return m_rbuf->row_ptr(y); }
        AGG_INLINE row_data     row(int y)     const { return m_rbuf->row(y); }

        //--------------------------------------------------------------------
        AGG_INLINE int8u* pix_ptr(int x, int y)
        {
            return m_rbuf->row_ptr(y) + sizeof(value_type) * (x * pix_step + pix_offset);
        }

        AGG_INLINE const int8u* pix_ptr(int x, int y) const
        {
            return m_rbuf->row_ptr(y) + sizeof(value_type) * (x * pix_step + pix_offset);
        }

        // Return pointer to pixel value, forcing row to be allocated.
        AGG_INLINE pixel_type* pix_value_ptr(int x, int y, unsigned len)
        {
            return (pixel_type*)(m_rbuf->row_ptr(x, y, len) + sizeof(value_type) * (x * pix_step + pix_offset));
        }

        // Return pointer to pixel value, or null if row not allocated.
        AGG_INLINE const pixel_type* pix_value_ptr(int x, int y) const
        {
            int8u* p = m_rbuf->row_ptr(y);
            return p ? (pixel_type*)(p + sizeof(value_type) * (x * pix_step + pix_offset)) : 0;
        }

        // Get pixel pointer from raw buffer pointer.
        AGG_INLINE static pixel_type* pix_value_ptr(void* p)
        {
            return (pixel_type*)((value_type*)p + pix_offset);
        }

        // Get pixel pointer from raw buffer pointer.
        AGG_INLINE static const pixel_type* pix_value_ptr(const void* p)
        {
            return (const pixel_type*)((const value_type*)p + pix_offset);
        }

        //--------------------------------------------------------------------
        AGG_INLINE static void write_plain_color(void* p, color_type c)
        {
            // RGB formats are implicitly premultiplied.
            c.premultiply();
            pix_value_ptr(p)->set(c);
        }

        //--------------------------------------------------------------------
        AGG_INLINE static color_type read_plain_color(const void* p)
        {
            return pix_value_ptr(p)->get();
        }

        //--------------------------------------------------------------------
        AGG_INLINE static void make_pix(int8u* p, const color_type& c)
        {
            ((pixel_type*)p)->set(c);
        }

        //--------------------------------------------------------------------
        AGG_INLINE color_type pixel(int x, int y) const
        {
            if (const pixel_type* p = pix_value_ptr(x, y))
            {
                return p->get();
            }
            return color_type::no_color();
        }

        //--------------------------------------------------------------------
        AGG_INLINE void copy_pixel(int x, int y, const color_type& c)
        {
            pix_value_ptr(x, y, 1)->set(c);
        }

        //--------------------------------------------------------------------
        AGG_INLINE void blend_pixel(int x, int y, const color_type& c, int8u cover)
        {
            copy_or_blend_pix(pix_value_ptr(x, y, 1), c, cover);
        }

        //--------------------------------------------------------------------
        AGG_INLINE void copy_hline(int x, int y,
                                   unsigned len,
                                   const color_type& c)
        {
            pixel_type* p = pix_value_ptr(x, y, len);
            do
            {
                p->set(c);
                p = p->next();
            }
            while(--len);
        }

        //--------------------------------------------------------------------
        AGG_INLINE void copy_vline(int x, int y,
                                   unsigned len,
                                   const color_type& c)
        {
            do
            {
                pix_value_ptr(x, y++, 1)->set(c);
            }
            while (--len);
        }

        //--------------------------------------------------------------------
        void blend_hline(int x, int y,
                         unsigned len,
                         const color_type& c,
                         int8u cover)
        {
            if (!c.is_transparent())
            {
                pixel_type* p = pix_value_ptr(x, y, len);

                if (c.is_opaque() && cover == cover_mask)
                {
                    do
                    {
                        p->set(c);
                        p = p->next();
                    }
                    while (--len);
                }
                else
                {
                    do
                    {
                        blend_pix(p, c, cover);
                        p = p->next();
                    }
                    while (--len);
                }
            }
        }

        //--------------------------------------------------------------------
        void blend_vline(int x, int y,
                         unsigned len,
                         const color_type& c,
                         int8u cover)
        {
            if (!c.is_transparent())
            {
                if (c.is_opaque() && cover == cover_mask)
                {
                    do
                    {
                        pix_value_ptr(x, y++, 1)->set(c);
                    }
                    while (--len);
                }
                else
                {
                    do
                    {
                        blend_pix(pix_value_ptr(x, y++, 1), c, cover);
                    }
                    while (--len);
                }
            }
        }

        //--------------------------------------------------------------------
        void blend_solid_hspan(int x, int y,
                               unsigned len,
                               const color_type& c,
                               const int8u* covers)
        {
            if (!c.is_transparent())
            {
                pixel_type* p = pix_value_ptr(x, y, len);

                do
                {
                    if (c.is_opaque() && *covers == cover_mask)
                    {
                        p->set(c);
                    }
                    else
                    {
                        blend_pix(p, c, *covers);
                    }
                    p = p->next();
                    ++covers;
                }
                while (--len);
            }
        }

        //--------------------------------------------------------------------
        void blend_solid_vspan(int x, int y,
                               unsigned len,
                               const color_type& c,
                               const int8u* covers)
        {
            if (!c.is_transparent())
            {
                do
                {
                    pixel_type* p = pix_value_ptr(x, y++, 1);

                    if (c.is_opaque() && *covers == cover_mask)
                    {
                        p->set(c);
                    }
                    else
                    {
                        blend_pix(p, c, *covers);
                    }
                    ++covers;
                }
                while (--len);
            }
        }

        //--------------------------------------------------------------------
        void copy_color_hspan(int x, int y,
                              unsigned len,
                              const color_type* colors)
        {
            pixel_type* p = pix_value_ptr(x, y, len);

            do
            {
                p->set(*colors++);
                p = p->next();
            }
            while (--len);
        }

        //--------------------------------------------------------------------
        void copy_color_vspan(int x, int y,
                              unsigned len,
                              const color_type* colors)
        {
            do
            {
                pix_value_ptr(x, y++, 1)->set(*colors++);
            }
            while (--len);
        }

        //--------------------------------------------------------------------
        void blend_color_hspan(int x, int y,
                               unsigned len,
                               const color_type* colors,
                               const int8u* covers,
                               int8u cover)
        {
            pixel_type* p = pix_value_ptr(x, y, len);

            if (covers)
            {
                do
                {
                    copy_or_blend_pix(p, *colors++, *covers++);
                    p = p->next();
                }
                while (--len);
            }
            else
            {
                if (cover == cover_mask)
                {
                    do
                    {
                        copy_or_blend_pix(p, *colors++);
                        p = p->next();
                    }
                    while (--len);
                }
                else
                {
                    do
                    {
                        copy_or_blend_pix(p, *colors++, cover);
                        p = p->next();
                    }
                    while (--len);
                }
            }
        }

        //--------------------------------------------------------------------
        void blend_color_vspan(int x, int y,
                               unsigned len,
                               const color_type* colors,
                               const int8u* covers,
                               int8u cover)
        {
            if (covers)
            {
                do
                {
                    copy_or_blend_pix(pix_value_ptr(x, y++, 1), *colors++, *covers++);
                }
                while (--len);
            }
            else
            {
                if (cover == cover_mask)
                {
                    do
                    {
                        copy_or_blend_pix(pix_value_ptr(x, y++, 1), *colors++);
                    }
                    while (--len);
                }
                else
                {
                    do
                    {
                        copy_or_blend_pix(pix_value_ptr(x, y++, 1), *colors++, cover);
                    }
                    while (--len);
                }
            }
        }

        //--------------------------------------------------------------------
        template<class Function> void for_each_pixel(Function f)
        {
            for (unsigned y = 0; y < height(); ++y)
            {
                row_data r = m_rbuf->row(y);
                if (r.ptr)
                {
                    unsigned len = r.x2 - r.x1 + 1;
                    pixel_type* p = pix_value_ptr(r.x1, y, len);
                    do
                    {
                        f(p->c);
                        p = p->next();
                    }
                    while (--len);
                }
            }
        }

        //--------------------------------------------------------------------
        template<class GammaLut> void apply_gamma_dir(const GammaLut& g)
        {
            for_each_pixel(apply_gamma_dir_rgb<color_type, order_type, GammaLut>(g));
        }

        //--------------------------------------------------------------------
        template<class GammaLut> void apply_gamma_inv(const GammaLut& g)
        {
            for_each_pixel(apply_gamma_inv_rgb<color_type, order_type, GammaLut>(g));
        }

        //--------------------------------------------------------------------
        template<class RenBuf2>
        void copy_from(const RenBuf2& from,
                       int xdst, int ydst,
                       int xsrc, int ysrc,
                       unsigned len)
        {
            if (const int8u* p = from.row_ptr(ysrc))
            {
                std::memmove(m_rbuf->row_ptr(xdst, ydst, len) + xdst * pix_width,
                        p + xsrc * pix_width,
                        len * pix_width);
            }
        }

        //--------------------------------------------------------------------
        // Blend from an RGBA surface.
        template<class SrcPixelFormatRenderer>
        void blend_from(const SrcPixelFormatRenderer& from,
                        int xdst, int ydst,
                        int xsrc, int ysrc,
                        unsigned len,
                        int8u cover)
        {
            typedef typename SrcPixelFormatRenderer::pixel_type src_pixel_type;
            typedef typename SrcPixelFormatRenderer::order_type src_order;

            if (const src_pixel_type* psrc = from.pix_value_ptr(xsrc, ysrc))
            {
                pixel_type* pdst = pix_value_ptr(xdst, ydst, len);

                if (cover == cover_mask)
                {
                    do
                    {
                        value_type alpha = psrc->c[src_order::A];
                        if (alpha <= color_type::empty_value())
                        {
                            if (alpha >= color_type::full_value())
                            {
                                pdst->c[order_type::R] = psrc->c[src_order::R];
                                pdst->c[order_type::G] = psrc->c[src_order::G];
                                pdst->c[order_type::B] = psrc->c[src_order::B];
                            }
                            else
                            {
                                blend_pix(pdst,
                                    psrc->c[src_order::R],
                                    psrc->c[src_order::G],
                                    psrc->c[src_order::B],
                                    alpha);
                            }
                        }
                        psrc = psrc->next();
                        pdst = pdst->next();
                    }
                    while(--len);
                }
                else
                {
                    do
                    {
                        copy_or_blend_pix(pdst, psrc->get(), cover);
                        psrc = psrc->next();
                        pdst = pdst->next();
                    }
                    while (--len);
                }
            }
        }

        //--------------------------------------------------------------------
        // Blend from single color, using grayscale surface as alpha channel.
        template<class SrcPixelFormatRenderer>
        void blend_from_color(const SrcPixelFormatRenderer& from,
                              const color_type& color,
                              int xdst, int ydst,
                              int xsrc, int ysrc,
                              unsigned len,
                              int8u cover)
        {
            typedef typename SrcPixelFormatRenderer::pixel_type src_pixel_type;
            typedef typename SrcPixelFormatRenderer::color_type src_color_type;

            if (const src_pixel_type* psrc = from.pix_value_ptr(xsrc, ysrc))
            {
                pixel_type* pdst = pix_value_ptr(xdst, ydst, len);

                do
                {
                    copy_or_blend_pix(pdst, color, src_color_type::scale_cover(cover, psrc->c[0]));
                    psrc = psrc->next();
                    pdst = pdst->next();
                }
                while (--len);
            }
        }

        //--------------------------------------------------------------------
        // Blend from color table, using grayscale surface as indexes into table.
        // Obviously, this only works for integer value types.
        template<class SrcPixelFormatRenderer>
        void blend_from_lut(const SrcPixelFormatRenderer& from,
                            const color_type* color_lut,
                            int xdst, int ydst,
                            int xsrc, int ysrc,
                            unsigned len,
                            int8u cover)
        {
            typedef typename SrcPixelFormatRenderer::pixel_type src_pixel_type;

            if (const src_pixel_type* psrc = from.pix_value_ptr(xsrc, ysrc))
            {
                pixel_type* pdst = pix_value_ptr(xdst, ydst, len);

                if (cover == cover_mask)
                {
                    do
                    {
                        const color_type& color = color_lut[psrc->c[0]];
                        blend_pix(pdst, color);
                        psrc = psrc->next();
                        pdst = pdst->next();
                    }
                    while(--len);
                }
                else
                {
                    do
                    {
                        copy_or_blend_pix(pdst, color_lut[psrc->c[0]], cover);
                        psrc = psrc->next();
                        pdst = pdst->next();
                    }
                    while(--len);
                }
            }
        }

    private:
        rbuf_type* m_rbuf;
        Blender    m_blender;
    };

    //-----------------------------------------------------------------------
    typedef blender_rgb<rgba8, order_rgb> blender_rgb24;
    typedef blender_rgb<rgba8, order_bgr> blender_bgr24;
    typedef blender_rgb<srgba8, order_rgb> blender_srgb24;
    typedef blender_rgb<srgba8, order_bgr> blender_sbgr24;
    typedef blender_rgb<rgba16, order_rgb> blender_rgb48;
    typedef blender_rgb<rgba16, order_bgr> blender_bgr48;
    typedef blender_rgb<rgba32, order_rgb> blender_rgb96;
    typedef blender_rgb<rgba32, order_bgr> blender_bgr96;

    typedef blender_rgb_pre<rgba8, order_rgb> blender_rgb24_pre;
    typedef blender_rgb_pre<rgba8, order_bgr> blender_bgr24_pre;
    typedef blender_rgb_pre<srgba8, order_rgb> blender_srgb24_pre;
    typedef blender_rgb_pre<srgba8, order_bgr> blender_sbgr24_pre;
    typedef blender_rgb_pre<rgba16, order_rgb> blender_rgb48_pre;
    typedef blender_rgb_pre<rgba16, order_bgr> blender_bgr48_pre;
    typedef blender_rgb_pre<rgba32, order_rgb> blender_rgb96_pre;
    typedef blender_rgb_pre<rgba32, order_bgr> blender_bgr96_pre;

    typedef pixfmt_alpha_blend_rgb<blender_rgb24, rendering_buffer, 3> pixfmt_rgb24;
    typedef pixfmt_alpha_blend_rgb<blender_bgr24, rendering_buffer, 3> pixfmt_bgr24;
    typedef pixfmt_alpha_blend_rgb<blender_srgb24, rendering_buffer, 3> pixfmt_srgb24;
    typedef pixfmt_alpha_blend_rgb<blender_sbgr24, rendering_buffer, 3> pixfmt_sbgr24;
    typedef pixfmt_alpha_blend_rgb<blender_rgb48, rendering_buffer, 3> pixfmt_rgb48;
    typedef pixfmt_alpha_blend_rgb<blender_bgr48, rendering_buffer, 3> pixfmt_bgr48;
    typedef pixfmt_alpha_blend_rgb<blender_rgb96, rendering_buffer, 3> pixfmt_rgb96;
    typedef pixfmt_alpha_blend_rgb<blender_bgr96, rendering_buffer, 3> pixfmt_bgr96;

    typedef pixfmt_alpha_blend_rgb<blender_rgb24_pre, rendering_buffer, 3> pixfmt_rgb24_pre;
    typedef pixfmt_alpha_blend_rgb<blender_bgr24_pre, rendering_buffer, 3> pixfmt_bgr24_pre;
    typedef pixfmt_alpha_blend_rgb<blender_srgb24_pre, rendering_buffer, 3> pixfmt_srgb24_pre;
    typedef pixfmt_alpha_blend_rgb<blender_sbgr24_pre, rendering_buffer, 3> pixfmt_sbgr24_pre;
    typedef pixfmt_alpha_blend_rgb<blender_rgb48_pre, rendering_buffer, 3> pixfmt_rgb48_pre;
    typedef pixfmt_alpha_blend_rgb<blender_bgr48_pre, rendering_buffer, 3> pixfmt_bgr48_pre;
    typedef pixfmt_alpha_blend_rgb<blender_rgb96_pre, rendering_buffer, 3> pixfmt_rgb96_pre;
    typedef pixfmt_alpha_blend_rgb<blender_bgr96_pre, rendering_buffer, 3> pixfmt_bgr96_pre;

    typedef pixfmt_alpha_blend_rgb<blender_rgb24, rendering_buffer, 4, 0> pixfmt_rgbx32;
    typedef pixfmt_alpha_blend_rgb<blender_rgb24, rendering_buffer, 4, 1> pixfmt_xrgb32;
    typedef pixfmt_alpha_blend_rgb<blender_bgr24, rendering_buffer, 4, 1> pixfmt_xbgr32;
    typedef pixfmt_alpha_blend_rgb<blender_bgr24, rendering_buffer, 4, 0> pixfmt_bgrx32;
    typedef pixfmt_alpha_blend_rgb<blender_srgb24, rendering_buffer, 4, 0> pixfmt_srgbx32;
    typedef pixfmt_alpha_blend_rgb<blender_srgb24, rendering_buffer, 4, 1> pixfmt_sxrgb32;
    typedef pixfmt_alpha_blend_rgb<blender_sbgr24, rendering_buffer, 4, 1> pixfmt_sxbgr32;
    typedef pixfmt_alpha_blend_rgb<blender_sbgr24, rendering_buffer, 4, 0> pixfmt_sbgrx32;
    typedef pixfmt_alpha_blend_rgb<blender_rgb48, rendering_buffer, 4, 0> pixfmt_rgbx64;
    typedef pixfmt_alpha_blend_rgb<blender_rgb48, rendering_buffer, 4, 1> pixfmt_xrgb64;
    typedef pixfmt_alpha_blend_rgb<blender_bgr48, rendering_buffer, 4, 1> pixfmt_xbgr64;
    typedef pixfmt_alpha_blend_rgb<blender_bgr48, rendering_buffer, 4, 0> pixfmt_bgrx64;
    typedef pixfmt_alpha_blend_rgb<blender_rgb96, rendering_buffer, 4, 0> pixfmt_rgbx128;
    typedef pixfmt_alpha_blend_rgb<blender_rgb96, rendering_buffer, 4, 1> pixfmt_xrgb128;
    typedef pixfmt_alpha_blend_rgb<blender_bgr96, rendering_buffer, 4, 1> pixfmt_xbgr128;
    typedef pixfmt_alpha_blend_rgb<blender_bgr96, rendering_buffer, 4, 0> pixfmt_bgrx128;

    typedef pixfmt_alpha_blend_rgb<blender_rgb24_pre, rendering_buffer, 4, 0> pixfmt_rgbx32_pre;
    typedef pixfmt_alpha_blend_rgb<blender_rgb24_pre, rendering_buffer, 4, 1> pixfmt_xrgb32_pre;
    typedef pixfmt_alpha_blend_rgb<blender_bgr24_pre, rendering_buffer, 4, 1> pixfmt_xbgr32_pre;
    typedef pixfmt_alpha_blend_rgb<blender_bgr24_pre, rendering_buffer, 4, 0> pixfmt_bgrx32_pre;
    typedef pixfmt_alpha_blend_rgb<blender_srgb24_pre, rendering_buffer, 4, 0> pixfmt_srgbx32_pre;
    typedef pixfmt_alpha_blend_rgb<blender_srgb24_pre, rendering_buffer, 4, 1> pixfmt_sxrgb32_pre;
    typedef pixfmt_alpha_blend_rgb<blender_sbgr24_pre, rendering_buffer, 4, 1> pixfmt_sxbgr32_pre;
    typedef pixfmt_alpha_blend_rgb<blender_sbgr24_pre, rendering_buffer, 4, 0> pixfmt_sbgrx32_pre;
    typedef pixfmt_alpha_blend_rgb<blender_rgb48_pre, rendering_buffer, 4, 0> pixfmt_rgbx64_pre;
    typedef pixfmt_alpha_blend_rgb<blender_rgb48_pre, rendering_buffer, 4, 1> pixfmt_xrgb64_pre;
    typedef pixfmt_alpha_blend_rgb<blender_bgr48_pre, rendering_buffer, 4, 1> pixfmt_xbgr64_pre;
    typedef pixfmt_alpha_blend_rgb<blender_bgr48_pre, rendering_buffer, 4, 0> pixfmt_bgrx64_pre;
    typedef pixfmt_alpha_blend_rgb<blender_rgb96_pre, rendering_buffer, 4, 0> pixfmt_rgbx128_pre;
    typedef pixfmt_alpha_blend_rgb<blender_rgb96_pre, rendering_buffer, 4, 1> pixfmt_xrgb128_pre;
    typedef pixfmt_alpha_blend_rgb<blender_bgr96_pre, rendering_buffer, 4, 1> pixfmt_xbgr128_pre;
    typedef pixfmt_alpha_blend_rgb<blender_bgr96_pre, rendering_buffer, 4, 0> pixfmt_bgrx128_pre;

    //-----------------------------------------------------pixfmt_rgb24_gamma
    template<class Gamma> class pixfmt_rgb24_gamma :
    public pixfmt_alpha_blend_rgb<blender_rgb_gamma<rgba8, order_rgb, Gamma>, rendering_buffer, 3>
    {
    public:
        pixfmt_rgb24_gamma(rendering_buffer& rb, const Gamma& g) :
            pixfmt_alpha_blend_rgb<blender_rgb_gamma<rgba8, order_rgb, Gamma>, rendering_buffer, 3>(rb)
        {
            this->blender().gamma(g);
        }
    };

    //-----------------------------------------------------pixfmt_srgb24_gamma
    template<class Gamma> class pixfmt_srgb24_gamma :
    public pixfmt_alpha_blend_rgb<blender_rgb_gamma<srgba8, order_rgb, Gamma>, rendering_buffer, 3>
    {
    public:
        pixfmt_srgb24_gamma(rendering_buffer& rb, const Gamma& g) :
            pixfmt_alpha_blend_rgb<blender_rgb_gamma<srgba8, order_rgb, Gamma>, rendering_buffer, 3>(rb)
        {
            this->blender().gamma(g);
        }
    };

    //-----------------------------------------------------pixfmt_bgr24_gamma
    template<class Gamma> class pixfmt_bgr24_gamma :
    public pixfmt_alpha_blend_rgb<blender_rgb_gamma<rgba8, order_bgr, Gamma>, rendering_buffer, 3>
    {
    public:
        pixfmt_bgr24_gamma(rendering_buffer& rb, const Gamma& g) :
            pixfmt_alpha_blend_rgb<blender_rgb_gamma<rgba8, order_bgr, Gamma>, rendering_buffer, 3>(rb)
        {
            this->blender().gamma(g);
        }
    };

    //-----------------------------------------------------pixfmt_sbgr24_gamma
    template<class Gamma> class pixfmt_sbgr24_gamma :
    public pixfmt_alpha_blend_rgb<blender_rgb_gamma<srgba8, order_bgr, Gamma>, rendering_buffer, 3>
    {
    public:
        pixfmt_sbgr24_gamma(rendering_buffer& rb, const Gamma& g) :
            pixfmt_alpha_blend_rgb<blender_rgb_gamma<srgba8, order_bgr, Gamma>, rendering_buffer, 3>(rb)
        {
            this->blender().gamma(g);
        }
    };

    //-----------------------------------------------------pixfmt_rgb48_gamma
    template<class Gamma> class pixfmt_rgb48_gamma :
    public pixfmt_alpha_blend_rgb<blender_rgb_gamma<rgba16, order_rgb, Gamma>, rendering_buffer, 3>
    {
    public:
        pixfmt_rgb48_gamma(rendering_buffer& rb, const Gamma& g) :
            pixfmt_alpha_blend_rgb<blender_rgb_gamma<rgba16, order_rgb, Gamma>, rendering_buffer, 3>(rb)
        {
            this->blender().gamma(g);
        }
    };

    //-----------------------------------------------------pixfmt_bgr48_gamma
    template<class Gamma> class pixfmt_bgr48_gamma :
    public pixfmt_alpha_blend_rgb<blender_rgb_gamma<rgba16, order_bgr, Gamma>, rendering_buffer, 3>
    {
    public:
        pixfmt_bgr48_gamma(rendering_buffer& rb, const Gamma& g) :
            pixfmt_alpha_blend_rgb<blender_rgb_gamma<rgba16, order_bgr, Gamma>, rendering_buffer, 3>(rb)
        {
            this->blender().gamma(g);
        }
    };

}

#endif


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>LALT - page2</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="css/main.css" type="text/css" media="all">

index | page2 | page3

Test .1 jaygrid

Hello World - page2

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean sagittis enim vel lectus malesuada dignissim. Aenean a faucibus arcu, eget dictum turpis. Integer tellus mi, fermentum et aliquam quis, placerat nec metus. Suspendisse fermentum sodales est, a consequat arcu congue nec. Quisque auctor neque dui, vel posuere nisi aliquam ac. Nullam neque nunc, placerat vel aliquet et, accumsan sit amet odio. Etiam a neque enim. Nam blandit a diam vel interdum. Quisque imperdiet mollis porttitor. Vivamus eu nulla a sem ornare suscipit. Nunc venenatis quam vitae diam pretium vestibulum. Quisque non aliquam justo, vitae egestas ex. Donec malesuada lacus eget magna aliquet, ac molestie arcu porttitor. Suspendisse at interdum sem.

Hello World Again

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean sagittis enim vel lectus malesuada dignissim. Aenean a faucibus arcu, eget dictum turpis. Integer tellus mi, fermentum et aliquam quis, placerat nec metus. Suspendisse fermentum sodales est, a consequat arcu congue nec. Quisque auctor neque dui, vel posuere nisi aliquam ac. Nullam neque nunc, placerat vel aliquet et, accumsan sit amet odio. Etiam a neque enim. Nam blandit a diam vel interdum. Quisque imperdiet mollis porttitor. Vivamus eu nulla a sem ornare suscipit. Nunc venenatis quam vitae diam pretium vestibulum. Quisque non aliquam justo, vitae egestas ex. Donec malesuada lacus eget magna aliquet, ac molestie arcu porttitor. Suspendisse at interdum sem.

end test .1

Test .2 stupidtable

        int
        float
        string

        15
        -.18
        banana

        95
        36
        coke

        2
        -152.5
        apple

        -53
        88.5
        zebra

        195
        -858
        orange

end test .2

Test .3 iconfont

end test .3

Test .5 scroll reveal

Hello world!

end test .5


text:
:mod:`errors`
=============

.. module:: errors
   :synopsis:

This module provides the custom exceptions that are used throughout the package.

Exceptions
----------

.. autoexception:: king_phisher.errors.KingPhisherError
   :show-inheritance:

.. autoexception:: king_phisher.errors.KingPhisherAbortError
   :show-inheritance:
   :members:

.. autoexception:: king_phisher.errors.KingPhisherAbortRequestError
   :show-inheritance:
   :members:
   :special-members: __init__

.. autoexception:: king_phisher.errors.KingPhisherDatabaseError
   :show-inheritance:

.. autoexception:: king_phisher.errors.KingPhisherInputValidationError
   :show-inheritance:

.. autoexception:: king_phisher.errors.KingPhisherPermissionError
   :show-inheritance:

.. autoexception:: king_phisher.errors.KingPhisherPluginError
   :show-inheritance:
   :members:
   :special-members: __init__

.. autoexception:: king_phisher.errors.KingPhisherResourceError
   :show-inheritance:

.. autoexception:: king_phisher.errors.KingPhisherTimeoutError
   :show-inheritance: