text:
package org.knowm.xchange.btce.v3;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;

import org.knowm.xchange.btce.v3.dto.account.BTCEAccountInfo;
import org.knowm.xchange.btce.v3.dto.marketdata.BTCEExchangeInfo;
import org.knowm.xchange.btce.v3.dto.marketdata.BTCEPairInfo;
import org.knowm.xchange.btce.v3.dto.marketdata.BTCETicker;
import org.knowm.xchange.btce.v3.dto.marketdata.BTCETrade;
import org.knowm.xchange.btce.v3.dto.meta.BTCEMetaData;
import org.knowm.xchange.btce.v3.dto.trade.BTCEOrder;
import org.knowm.xchange.btce.v3.dto.trade.BTCEOrderInfoResult;
import org.knowm.xchange.btce.v3.dto.trade.BTCETradeHistoryResult;
import org.knowm.xchange.currency.Currency;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.Order.OrderStatus;
import org.knowm.xchange.dto.Order.OrderType;
import org.knowm.xchange.dto.account.Balance;
import org.knowm.xchange.dto.account.Wallet;
import org.knowm.xchange.dto.marketdata.Ticker;
import org.knowm.xchange.dto.marketdata.Trade;
import org.knowm.xchange.dto.marketdata.Trades;
import org.knowm.xchange.dto.marketdata.Trades.TradeSortType;
import org.knowm.xchange.dto.meta.CurrencyMetaData;
import org.knowm.xchange.dto.meta.CurrencyPairMetaData;
import org.knowm.xchange.dto.meta.ExchangeMetaData;
import org.knowm.xchange.dto.meta.RateLimit;
import org.knowm.xchange.dto.trade.LimitOrder;
import org.knowm.xchange.dto.trade.MarketOrder;
import org.knowm.xchange.dto.trade.OpenOrders;
import org.knowm.xchange.dto.trade.UserTrade;
import org.knowm.xchange.dto.trade.UserTrades;
import org.knowm.xchange.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Various adapters for converting from BTCE DTOs to XChange DTOs
 */
public final class BTCEAdapters {

  public static final Logger log = LoggerFactory.getLogger(BTCEAdapters.class);

  /**
   * private Constructor
   */
  private BTCEAdapters() {

  }

  /**
   * Adapts a List of BTCEOrders to a List of LimitOrders
   *
   * @param bTCEOrders
   * @param currencyPair
   * @param orderTypeString
   * @param id
   * @return
   */
  public static List<LimitOrder> adaptOrders(List<BigDecimal[]> bTCEOrders, CurrencyPair currencyPair, String orderTypeString, String id) {

    List<LimitOrder> limitOrders = new ArrayList<>();
    OrderType orderType = orderTypeString.equalsIgnoreCase("bid") ? OrderType.BID : OrderType.ASK;

    for (BigDecimal[] btceOrder : bTCEOrders) {
      limitOrders.add(adaptOrder(btceOrder[1], btceOrder[0], currencyPair, orderType, id));
    }

    return limitOrders;
  }

  /**
   * Adapts a BTCEOrder to a LimitOrder
   *
   * @param amount
   * @param price
   * @param currencyPair
   * @param orderType
   * @param id
   * @return
   */
  public static LimitOrder adaptOrder(BigDecimal amount, BigDecimal price, CurrencyPair currencyPair, OrderType orderType, String id) {

    return new LimitOrder(orderType, amount, currencyPair, id, null, price);
  }

  /**
   * Adapts a BTCETradeV3 to a Trade Object
   *
   * @param bTCETrade BTCE trade object v.3
   * @param currencyPair the currency pair
   * @return The XChange Trade
   */
  public static Trade adaptTrade(BTCETrade bTCETrade, CurrencyPair currencyPair) {

    OrderType orderType = bTCETrade.getTradeType().equalsIgnoreCase("bid") ? OrderType.BID : OrderType.ASK;
    BigDecimal amount = bTCETrade.getAmount();
    BigDecimal price = bTCETrade.getPrice();
    Date date = DateUtils.fromMillisUtc(bTCETrade.getDate() * 1000L);

    final String tradeId = String.valueOf(bTCETrade.getTid());
    return new Trade(orderType, amount, currencyPair, price, date, tradeId);
  }

  /**
   * Adapts a BTCETradeV3[] to a Trades Object
   *
   * @param bTCETrades The BTCE trade data returned by API v.3
   * @param currencyPair the currency pair
   * @return The trades
   */
  public static Trades adaptTrades(BTCETrade[] bTCETrades, CurrencyPair currencyPair) {

    List<Trade> tradesList = new ArrayList<>();
    long lastTradeId = 0;
    for (BTCETrade bTCETrade : bTCETrades) {
      // Date is reversed order. Insert at index 0 instead of appending
      long tradeId = bTCETrade.getTid();
      if (tradeId > lastTradeId) {
        lastTradeId = tradeId;
      }
      tradesList.add(0, adaptTrade(bTCETrade, currencyPair));
    }
    return new Trades(tradesList, lastTradeId, TradeSortType.SortByID);
  }

  /**
   * Adapts a BTCETicker to a Ticker Object
   *
   * @param bTCETicker
   * @return
   */
  public static Ticker adaptTicker(BTCETicker bTCETicker, CurrencyPair currencyPair) {

    BigDecimal last = bTCETicker.getLast();
    BigDecimal bid = bTCETicker.getSell();
    BigDecimal ask = bTCETicker.getBuy();
    BigDecimal high = bTCETicker.getHigh();
    BigDecimal low = bTCETicker.getLow();
    BigDecimal avg = bTCETicker.getAvg();
    BigDecimal volume = bTCETicker.getVolCur();
    Date timestamp = DateUtils.fromMillisUtc(bTCETicker.getUpdated() * 1000L);

    return new Ticker.Builder().currencyPair(currencyPair).last(last).bid(bid).ask(ask).high(high).low(low).vwap(avg).volume(volume)
        .timestamp(timestamp).build();
  }

  public static Wallet adaptWallet(BTCEAccountInfo btceAccountInfo) {

    List<Balance> balances = new ArrayList<>();
    Map<String, BigDecimal> funds = btceAccountInfo.getFunds();

    for (String lcCurrency : funds.keySet()) {
      /* BTC-E signals DASH as DSH. This is a different coin. Translate in correct DASH name */
      BigDecimal fund = funds.get(lcCurrency);
      if (lcCurrency.equals("dsh")) {
        lcCurrency = "dash";
      }
      Currency currency = Currency.getInstance(lcCurrency);
      balances.add(new Balance(currency, fund));
    }
    return new Wallet(balances);
  }

  public static OpenOrders adaptOrders(Map<Long, BTCEOrder> btceOrderMap) {

    List<LimitOrder> limitOrders = new ArrayList<>();
    for (Long id : btceOrderMap.keySet()) {
      BTCEOrder bTCEOrder = btceOrderMap.get(id);
      OrderType orderType = bTCEOrder.getType() == BTCEOrder.Type.buy ? OrderType.BID : OrderType.ASK;
      BigDecimal price = bTCEOrder.getRate();
      Date timestamp = DateUtils.fromMillisUtc(bTCEOrder.getTimestampCreated() * 1000L);
      CurrencyPair currencyPair = adaptCurrencyPair(bTCEOrder.getPair());

      limitOrders.add(new LimitOrder(orderType, bTCEOrder.getAmount(), currencyPair, Long.toString(id), timestamp, price));
    }
    return new OpenOrders(limitOrders);
  }

  public static UserTrades adaptTradeHistory(Map<Long, BTCETradeHistoryResult> tradeHistory) {

    List<UserTrade> trades = new ArrayList<>(tradeHistory.size());
    for (Entry<Long, BTCETradeHistoryResult> entry : tradeHistory.entrySet()) {
      BTCETradeHistoryResult result = entry.getValue();
      OrderType type = result.getType() == BTCETradeHistoryResult.Type.buy ? OrderType.BID : OrderType.ASK;
      BigDecimal price = result.getRate();
      BigDecimal tradableAmount = result.getAmount();
      Date timeStamp = DateUtils.fromMillisUtc(result.getTimestamp() * 1000L);
      String orderId = String.valueOf(result.getOrderId());
      String tradeId = String.valueOf(entry.getKey());
      CurrencyPair currencyPair = adaptCurrencyPair(result.getPair());
      trades.add(new UserTrade(type, tradableAmount, currencyPair, price, timeStamp, tradeId, orderId, null, (Currency) null));
    }
    return new UserTrades(trades, TradeSortType.SortByTimestamp);
  }

  /**
   * Adapts a BTCEOrderInfoResult to a LimitOrder
   *
   * @param orderId Order original id
   * @param orderInfo
   * @return
   */
  public static LimitOrder adaptOrderInfo(String orderId, BTCEOrderInfoResult orderInfo) {

    OrderType orderType = orderInfo.getType() == BTCEOrderInfoResult.Type.buy ? OrderType.BID : OrderType.ASK;
    BigDecimal price = orderInfo.getRate();
    Date timestamp = DateUtils.fromMillisUtc(orderInfo.getTimestampCreated() * 1000L);
    CurrencyPair currencyPair = adaptCurrencyPair(orderInfo.getPair());
    OrderStatus orderStatus = null;
    switch (orderInfo.getStatus()) {
      case 0:
        if (orderInfo.getAmount().compareTo(orderInfo.getStartAmount()) == 0) {
          orderStatus = OrderStatus.NEW;
        } else {
          orderStatus = OrderStatus.PARTIALLY_FILLED;
        }
        break;
      case 1:
        orderStatus = OrderStatus.FILLED;
        break;
      case 2:
      case 3:
        orderStatus = OrderStatus.CANCELED;
        break;
    }

    return new LimitOrder(orderType, orderInfo.getStartAmount(), currencyPair, orderId, timestamp, price, price, orderInfo.getStartAmount().subtract(orderInfo.getAmount()), orderStatus);
  }

  public static CurrencyPair adaptCurrencyPair(String btceCurrencyPair) {

    String[] currencies = btceCurrencyPair.split("_");
    /* BTC-E signals DASH as DSH. This is a different coin. Translate in correct DASH name */
    if (currencies[0].equals("dsh")) {
      currencies[0] = "dash";
    }
    if (currencies[1].equals("dsh")) {
      currencies[1] = "dash";
    }
    return new CurrencyPair(currencies[0].toUpperCase(), currencies[1].toUpperCase());
  }

  public static List<CurrencyPair> adaptCurrencyPairs(Iterable<String> btcePairs) {

    List<CurrencyPair> pairs = new ArrayList<>();
    for (String btcePair : btcePairs) {
      pairs.add(adaptCurrencyPair(btcePair));
    }

    return pairs;
  }

  public static ExchangeMetaData toMetaData(BTCEExchangeInfo btceExchangeInfo, BTCEMetaData btceMetaData) {
    Map<CurrencyPair, CurrencyPairMetaData> currencyPairs = new HashMap<>();
    Map<Currency, CurrencyMetaData> currencies = new HashMap<>();

    if (btceExchangeInfo != null) {
      for (Entry<String, BTCEPairInfo> e : btceExchangeInfo.getPairs().entrySet()) {
        CurrencyPair pair = adaptCurrencyPair(e.getKey());
        CurrencyPairMetaData marketMetaData = toMarketMetaData(e.getValue(), btceMetaData);
        currencyPairs.put(pair, marketMetaData);

        addCurrencyMetaData(pair.base, currencies, btceMetaData);
        addCurrencyMetaData(pair.counter, currencies, btceMetaData);
      }
    }

    RateLimit[] publicRateLimits = new RateLimit[]{new RateLimit(btceMetaData.publicInfoCacheSeconds, 1, TimeUnit.SECONDS)};
    return new ExchangeMetaData(currencyPairs, currencies, publicRateLimits, null, false);
  }

  private static void addCurrencyMetaData(Currency symbol, Map<Currency, CurrencyMetaData> currencies, BTCEMetaData btceMetaData) {
    if (!currencies.containsKey(symbol)) {
      currencies.put(symbol, new CurrencyMetaData(btceMetaData.amountScale));
    }
  }

  public static CurrencyPairMetaData toMarketMetaData(BTCEPairInfo info, BTCEMetaData btceMetaData) {
    int priceScale = info.getDecimals();
    BigDecimal minimumAmount = withScale(info.getMinAmount(), btceMetaData.amountScale);
    BigDecimal feeFraction = info.getFee().movePointLeft(2);

    return new CurrencyPairMetaData(feeFraction, minimumAmount, null, priceScale);
  }

  private static BigDecimal withScale(BigDecimal value, int priceScale) {
    /*
     * Last time I checked BTC-e returned an erroneous JSON result, where the minimum price for LTC/EUR was .0001 and the price scale was 3
     */
    try {
      return value.setScale(priceScale, RoundingMode.UNNECESSARY);
    } catch (ArithmeticException e) {
      log.debug("Could not round {} to {} decimal places: {}", value, priceScale, e.getMessage());
      return value.setScale(priceScale, RoundingMode.CEILING);
    }
  }

  public static String getPair(CurrencyPair currencyPair) {
    /* BTC-E signals DASH as DSH. This is a different coin. Translate in correct DASH name */
    String base = currencyPair.base.getCurrencyCode();
    String counter = currencyPair.counter.getCurrencyCode();
    if (base.equals("DASH")) {
      base = "DSH";
    } else if (counter.equals("DASH")) {
      counter = "DSH";
    }
    return (base + "_" + counter).toLowerCase();
  }

  public static LimitOrder createLimitOrder(MarketOrder marketOrder, BTCEExchangeInfo btceExchangeInfo) {
    BTCEPairInfo btcePairInfo = btceExchangeInfo.getPairs().get(getPair(marketOrder.getCurrencyPair()));
    BigDecimal limitPrice = marketOrder.getType() == OrderType.BID ? btcePairInfo.getMaxPrice() : btcePairInfo.getMinPrice();
    return LimitOrder.Builder.from(marketOrder).limitPrice(limitPrice).build();
  }
}


text:
#region License
//
// Copyright (c) 2013, Kooboo team
//
// Licensed under the BSD License
// See the file LICENSE.txt for details.
//
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using Kooboo.Extensions;
using System.ComponentModel;
using Kooboo.CMS.Common.Persistence.Non_Relational;
using Kooboo.CMS.Common.Persistence;
namespace Kooboo.CMS.Sites.Models
{
    public enum RedirectType
    {
        Moved_Permanently_301 = 301,
        Found_Redirect_302 = 302,
        [Description("Server transfer")]
        Transfer = 200
    }
    [DataContract]
    public partial class UrlRedirect : IChangeTimeline
    {
        public UrlRedirect()
        {

        }
        public UrlRedirect(Site site)
        {
            this.Site = site;
        }
        string uuid = Kooboo.UniqueIdGenerator.GetInstance().GetBase32UniqueId(8);
        [DataMember]
        public string UUID
        {
            get
            {
                if (string.IsNullOrEmpty(uuid))
                {
                    uuid = inputUrl;
                }
                return uuid;
            }
            set
            {
                uuid = value;
            }
        }

        string inputUrl = string.Empty;
        [DataMember(Order = 1)]
        public string InputUrl
        {
            get
            {
                return this.inputUrl;
            }
            set
            {
                inputUrl = value;
            }
        }
        [DataMember(Order = 4)]
        public string OutputUrl { get; set; }
        [DataMember(Order = 8)]
        public bool Regex { get; set; }
        [DataMember(Order = 12)]
        public RedirectType RedirectType { get; set; }

        [DataMember]
        public DateTime? UtcCreationDate { get; set; }

        [DataMember]
        public DateTime? UtcLastestModificationDate { get; set; }

        [DataMember]
        public string LastestEditor { get; set; }

    }

    public partial class UrlRedirect : ISiteObject, IFilePersistable, IPersistable, IIdentifiable
    {
        public Site Site { get; set; }

        #region override object
        public static bool operator ==(UrlRedirect obj1, UrlRedirect obj2)
        {
            if (object.Equals(obj1, obj2) == true)
            {
                return true;
            }
            if (object.Equals(obj1, null) == true || object.Equals(obj2, null) == true)
            {
                return false;
            }
            return obj1.Equals(obj2);
        }
        public static bool operator !=(UrlRedirect obj1, UrlRedirect obj2)
        {
            return !(obj1 == obj2);
        }

        public override bool Equals(object obj)
        {
            if (!(obj is UrlRedirect))
            {
                return false;
            }
            if (obj != null)
            {
                var urlMap = (UrlRedirect)obj;
                if (this.UUID.EqualsOrNullEmpty(urlMap.UUID, StringComparison.CurrentCultureIgnoreCase))
                {
                    return true;
                }
            }
            return base.Equals(obj);
        }
        public override string ToString()
        {
            return InputUrl;
        }
        public override int GetHashCode()
        {
            return base.GetHashCode();
        }
        #endregion

        #region IPersistable

        private bool isDummy = true;
        public bool IsDummy
        {
            get { return isDummy; }
            set { isDummy = value; }
        }

        public void Init(IPersistable source)
        {
            isDummy = false;
            this.Site = ((UrlRedirect)source).Site;
        }

        public void OnSaved()
        {
            isDummy = false;
        }

        public void OnSaving()
        {

        }

        public string DataFile
        {
            get { return new UrlRedirectsFile(this.Site).PhysicalPath; }
        }
        #endregion
    }
}

redpajama_set_name: RedPajamaGithub


text:
import {reservedWords, keywords} from "./identifier"
import {types as tt} from "./tokentype"
import {lineBreak} from "./whitespace"
import {getOptions} from "./options"

// Registered plugins
export const plugins = {}

export class Parser {
  constructor(options, input, startPos) {
    this.options = getOptions(options)
    this.sourceFile = this.options.sourceFile
    this.isKeyword = keywords[this.options.ecmaVersion >= 6 ? 6 : 5]
    this.isReservedWord = reservedWords[this.options.ecmaVersion]
    this.input = String(input)

    // Used to signal to callers of `readWord1` whether the word
    // contained any escape sequences. This is needed because words with
    // escape sequences must not be interpreted as keywords.
    this.containsEsc = false;

    // Load plugins
    this.loadPlugins(this.options.plugins)

    // Set up token state

    // The current position of the tokenizer in the input.
    if (startPos) {
      this.pos = startPos
      this.lineStart = Math.max(0, this.input.lastIndexOf("\n", startPos))
      this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length
    } else {
      this.pos = this.lineStart = 0
      this.curLine = 1
    }

    // Properties of the current token:
    // Its type
    this.type = tt.eof
    // For tokens that include more information than their type, the value
    this.value = null
    // Its start and end offset
    this.start = this.end = this.pos
    // And, if locations are used, the {line, column} object
    // corresponding to those offsets
    this.startLoc = this.endLoc = this.curPosition()

    // Position information for the previous token
    this.lastTokEndLoc = this.lastTokStartLoc = null
    this.lastTokStart = this.lastTokEnd = this.pos

    // The context stack is used to superficially track syntactic
    // context to predict whether a regular expression is allowed in a
    // given position.
    this.context = this.initialContext()
    this.exprAllowed = true

    // Figure out if it's a module code.
    this.strict = this.inModule = this.options.sourceType === "module"

    // Used to signify the start of a potential arrow function
    this.potentialArrowAt = -1

    // Flags to track whether we are in a function, a generator.
    this.inFunction = this.inGenerator = false
    // Labels in scope.
    this.labels = []

    // If enabled, skip leading hashbang line.
    if (this.pos === 0 && this.options.allowHashBang && this.input.slice(0, 2) === '#!')
      this.skipLineComment(2)
  }

  extend(name, f) {
    this[name] = f(this[name])
  }

  loadPlugins(pluginConfigs) {
    for (let name in pluginConfigs) {
      let plugin = plugins[name]
      if (!plugin) throw new Error("Plugin '" + name + "' not found")
      plugin(this, pluginConfigs[name])
    }
  }

  parse() {
    let node = this.options.program || this.startNode()
    this.nextToken()
    return this.parseTopLevel(node)
  }
}


text:
"""
================================================
:mod:`onebot.plugins.antispam` PSA
================================================

This plugin attempts to combat spam

Config options:
    max_highlights      Maximum number of nicks before kick (default: 5)

"""

import asyncio
from collections import defaultdict
import hashlib

from irc3 import rfc, plugin
from irc3.dec import event

def _hash(string):
    h = hashlib.sha256()
    h.update(string.encode())
    return h.hexdigest()

@plugin
class PSAPlugin(object):
    """PSA Plugin"""

    requires = ["irc3.plugins.userlist", "onebot.plugins.users"]

    def __init__(self, bot):
        self.bot = bot
        self.config = bot.config.get(self.__class__.__module__, {})
        self.max_highlights = self.config.get("max_highlights", 5)
        self.max_repeats = self.config.get("max_repeats", 5)
        self.log = self.bot.log.getChild(__name__)
        self.lastlines = defaultdict(dict)

    @event(rfc.PRIVMSG)
    def nickspamfilter(self, mask, target, data, **kwargs):
        """Kicks people who highlight lots of users"""
        highlights = 0
        words = data.split()
        if target in self.bot.channels:
            for nick in self.bot.channels[target]:
                if nick in words:
                    highlights += 1
                if highlights >= self.max_highlights:
                    self.log.info("Kicking {} for highlightspam", mask.nick)
                    self.bot.kick(
                        target, mask.nick, "Don't excessively highlight people."
                    )
                    return

    @event(rfc.PRIVMSG)
    async def repeatingspam(self, mask, target, data, **kwargs):
        user = self.bot.get_user(mask.nick)
        data = _hash(target + data.strip())
        last_line = await user.get_setting("last_line")
        num = await user.get_setting("last_line_num")
        if data == last_line:
            num += 1
            if num >= self.max_repeats:
                self.log.info("Kicking {} for spamming", mask.nick)
                self.bot.kick(
                    target,
                    mask.nick,
                    "Try to come up with something more creative. "
                    "({} repeating lines)".format(num),
                )
        else:
            user.set_setting("last_line", data)
            num = 1
        user.set_setting("last_line_num", num)

    @classmethod
    def reload(cls, old):
        return cls(old.bot)


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

using SampSharp.Core.Natives.NativeObjects;

namespace SampSharp.Streamer.World
{
    public partial class DynamicWorldObject<T>
    {
        protected static readonly DynamicWorldObjectInternal WorldInternal = NativeObjectProxyFactory.CreateInstance<DynamicWorldObjectInternal>();
    }

    public class DynamicWorldObjectInternal
    {
        [NativeMethod(Function = "Streamer_IsToggleItemStatic")]
        public virtual bool IsToggleItemStatic(int type, int id)
        {
            throw new NativeNotImplementedException();
        }

        [NativeMethod(Function = "Streamer_ToggleItemStatic")]
        public virtual bool ToggleItemStatic(int type, int id, bool toggle)
        {
            throw new NativeNotImplementedException();
        }

        [NativeMethod(Function = "Streamer_IsToggleItem")]
        public virtual bool IsToggleItem(int playerid, int type, int id)
        {
            throw new NativeNotImplementedException();
        }

        [NativeMethod(Function = "Streamer_ToggleItem")]
        public virtual bool ToggleItem(int playerid, int type, int id, bool toggle)
        {
            throw new NativeNotImplementedException();
        }

        [NativeMethod(Function = "Streamer_ToggleAllItems")]
        public virtual bool ToggleAllItems(int playerid, int type, bool toggle, int[] exceptions, int maxexceptions)
        {
            throw new NativeNotImplementedException();
        }

        [NativeMethod(Function = "Streamer_ToggleItemInvAreas")]
        public virtual bool ToggleItemInvAreas(int type, int id, bool toggle)
        {
            throw new NativeNotImplementedException();
        }

        [NativeMethod(Function = "Streamer_IsToggleItemInvAreas")]
        public virtual bool IsToggleItemInvAreas(int type, int id)
        {
            throw new NativeNotImplementedException();
        }

        [NativeMethod(Function = "Streamer_ToggleItemCallbacks")]
        public virtual bool ToggleItemCallbacks(int type, int id, bool toggle)
        {
            throw new NativeNotImplementedException();
        }

        [NativeMethod(Function = "Streamer_IsToggleItemCallbacks")]
        public virtual bool IsToggleItemCallbacks(int type, int id)
        {
            throw new NativeNotImplementedException();
        }

        [NativeMethod(Function = "Streamer_GetItemOffset")]
        public virtual int GetItemOffset(int type, int id, out float x, out float y, out float z)
        {
            throw new NativeNotImplementedException();
        }

        [NativeMethod(Function = "Streamer_SetItemOffset")]
        public virtual int SetItemOffset(int type, int id, float x, float y, float z)
        {
            throw new NativeNotImplementedException();
        }
    }
}


text:
#import "NSObject.h"

@class NSString, PBXExecutable;

@interface XCRemoteExecutable : NSObject
{
    BOOL shouldLaunch;
    BOOL shouldDebug;
    long long debugPort;
    PBXExecutable *localExecutable;
    NSString *localBundlePath;
    NSString *installedPath;
    NSString *executableReferencePath;
    NSString *sdkPath;
}

@property long long debugPort; // @synthesize debugPort;
@property BOOL shouldDebug; // @synthesize shouldDebug;
@property BOOL shouldLaunch; // @synthesize shouldLaunch;
@property(retain) PBXExecutable *localExecutable; // @synthesize localExecutable;
@property(retain) NSString *executableReferencePath; // @synthesize executableReferencePath;
@property(retain) NSString *installedPath; // @synthesize installedPath;
@property(retain) NSString *localBundlePath; // @synthesize localBundlePath;
@property(retain) NSString *sdkPath; // @synthesize sdkPath;

@end


text:
local class = require 'lib/30log'
local PubSub = class('PubSub', {
	UID_CNTR = 0,
	topics = {}
})

function PubSub:subscribe( topic, callback )
	if self.topics[topic] == nil then
	  self.topics[topic] = {}
	end
	local f = self.UID_CNTR + 1
	self.UID_CNTR = self.UID_CNTR+1
	table.insert(self.topics[topic],{
	  uid = f,
	  cb = callback
	})
	--return an unsubscribe function
	return function ()
	  for i, v in ipairs(self.topics[topic]) do
	    if v.uid == f then
	      table.remove(v)
	    end
	  end
	end
end

function PubSub:publish( topic, message )
	if self.topics[topic] == nil then self.topics[topic] = {} end

	for i, v in ipairs(self.topics[topic]) do
	  v:cb(message)
	end
end

return PubSub


text:
Codename Titanium - Serious Game supplementing higher level mathematical education.

## Preliminary Research and Planning
A detailed project plan for the master thesis can be seen and read in "Detailed Project plan.pdf". This report was written for the class on "Research Project Planning" at NTNU in Gjøvik, and describes the plan of action for this project for the next 6 months or so.

To validate our design decisions and get feedback from target audience members, we ran a preliminary user test on one prototype case from the serious game. The results can be seen in "Preliminary Project Report.pdf". This report was written for the class on "Advanced Project Work" at NTNU in Gjøvik.

## Work in Progress - Research Projects
This project is intended to be used as the development part of two research & development projects at NTNU in Gjøvik, Norway.
Specifically for advanced project work, and my Master's Thesis.

Updates will come periodically. Expect major refactoring in the near future.

## External Assets used
- Unreal Starter Content
- https://docs.unrealengine.com/latest/INT/Resources/Showcases/RealisticRendering/
- https://www.unrealengine.com/marketplace/ground-and-walls-texture-pack
- https://www.unrealengine.com/marketplace/dynamic-clocks
- https://www.cgtrader.com/3d-models/electronics/phones-small-appliance/digital-room-thermometer
- Third Person starter template mannequin

As these assets are *not* pushed to the repository, to run this you will have to manually add them to the project (they are quite large).


text:
require 'spec_helper'

RSpec.describe(Bunto::GitHubMetadata) do
  let(:key_value_pair) { %w{some_key some_value} }

  before(:each) do
    described_class.reset!
  end

  it 'allows you to register values' do
    expect(described_class.register_value(*key_value_pair)).not_to be_nil
  end

  it 'knows how to turn into Liquid' do
    expect(described_class).to respond_to(:to_liquid)
    expect(described_class.to_liquid).to be_a(Hash)
  end

  it 'has a hash representation' do
    expect(described_class).to respond_to(:to_h)
    expect(described_class.to_h).to be_a(Hash)
  end

  it 'stores the key-value pairs in a values hash' do
    described_class.register_value(*key_value_pair)
    expect(described_class['some_key'].to_s).to eql('some_value')
  end

  it 'has a global GitHub API client' do
    expect(described_class.client).to be_a(Bunto::GitHubMetadata::Client)
  end

  it 'does auto_paginate' do
    expect(
      described_class.client.instance_variable_get(:"@client").auto_paginate
    ).to be(true)
  end
end


text:
<?php namespace EFrane\Transfugio\Http\Formatter;

use XMLWriter;

class XMLFormatter
{
  public static function format(array $data)
  {
    $formatter = new XMLFormatter;
    return $formatter->run($data);
  }

  private function __construct() {}

  private function run($data)
  {
    $writer = new XMLWriter;
    $writer->openMemory();

    $writer->startDocument('1.0', 'utf-8');
    $writer->startElement('result');

    $this->processItem('data', $data['data'], $writer);
    //$this->processItem($key, $value, $writer);

    $writer->endElement();

    return $writer->outputMemory();
  }

  private function processItem($key, $value, XMLWriter $writer)
  {
    if (is_array($value))
    {
      if (isset($value[0]))
      {
        $writer->startElement($key);
        foreach ($value as $key => $item)
        {
          $writer->startElement('item');
          $writer->writeAttribute('value', $item);
          $writer->endElement();
        }
        $writer->endElement();
      } else
      {
        foreach ($value as $key => $innerValue)
          $this->processItem($key, $innerValue, $writer);
      }
    } else
    {
      $writer->writeElement($key, $value);
    }
  }
}


text:
import { ITokenMessageBase } from './ITokenMessageBase';

export interface ITokenMessage extends ITokenMessageBase {
    templateName: string | null;
}


text:
package im.r_c.android.jigsaw.fragment;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import im.r_c.android.jigsaw.R;

/**
 * Jigsaw
 * Created by richard on 16/5/15.
 */
public class WinFragment extends Fragment {
    public static WinFragment newInstance(Bitmap bitmap) {
        Bundle args = new Bundle();
        args.putParcelable("image", bitmap);
        WinFragment fragment = new WinFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public WinFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_win, container, false);
        ImageView iv = (ImageView) view.findViewById(R.id.iv_image);
        iv.setImageBitmap((Bitmap) getArguments().getParcelable("image"));
        return view;
    }
}


text:
import {
    combineReducers
} from 'redux'
import counter from './counter'
import wheelchair from './wheelchair'

const app = combineReducers( {
    counter,
    wheelchair
} )

export default app


text:
using System.Collections.Generic;
using Mono.Cecil.Cil;

namespace Stratis.SmartContracts.CLR.ILRewrite
{
    public static class CecilExtensions
    {
        /// <summary>
        /// All opcodes that call to a method.
        /// </summary>
        private static readonly HashSet<OpCode> CallingOps = new HashSet<OpCode>
        {
            OpCodes.Call,
            OpCodes.Calli,
            OpCodes.Callvirt
        };

        /// <summary>
        /// All branching opcodes.
        /// </summary>
        private static readonly HashSet<OpCode> BranchingOps = new HashSet<OpCode>
        {
            OpCodes.Beq,
            OpCodes.Beq_S,
            OpCodes.Bge,
            OpCodes.Bge_S,
            OpCodes.Bge_Un,
            OpCodes.Bge_Un_S,
            OpCodes.Bgt,
            OpCodes.Bgt_S,
            OpCodes.Ble,
            OpCodes.Ble_S,
            OpCodes.Ble_Un,
            OpCodes.Blt,
            OpCodes.Bne_Un,
            OpCodes.Bne_Un_S,
            OpCodes.Br,
            OpCodes.Brfalse,
            OpCodes.Brfalse_S,
            OpCodes.Brtrue,
            OpCodes.Brtrue_S,
            OpCodes.Br_S
        };

        public static bool IsMethodCall(this Instruction instruction)
        {
            return CallingOps.Contains(instruction.OpCode);
        }

        public static bool IsBranch(this Instruction instruction)
        {
            return BranchingOps.Contains(instruction.OpCode);
        }

        /// <summary>
        /// Get the simplest instruction for popping item on stack into a variable index.
        /// </summary>
        public static Instruction CreateStlocBest(this ILProcessor il, VariableDefinition variable)
        {
            switch (variable.Index)
            {
                case 0: return il.Create(OpCodes.Stloc_0);
                case 1: return il.Create(OpCodes.Stloc_1);
                case 2: return il.Create(OpCodes.Stloc_2);
                case 3: return il.Create(OpCodes.Stloc_3);
                default:
                    if (IsSByte(variable.Index))
                        return il.Create(OpCodes.Stloc_S, variable);
                    return il.Create(OpCodes.Stloc, variable);
            }
        }

        /// <summary>
        /// Get the simplest instruction for loading an item onto the stack from a variable.
        /// </summary>
        public static Instruction CreateLdlocBest(this ILProcessor il, VariableDefinition variable)
        {
            switch (variable.Index)
            {
                case 0: return il.Create(OpCodes.Ldloc_0);
                case 1: return il.Create(OpCodes.Ldloc_1);
                case 2: return il.Create(OpCodes.Ldloc_2);
                case 3: return il.Create(OpCodes.Ldloc_3);
                default:
                    if (IsSByte(variable.Index))
                        return il.Create(OpCodes.Ldloc_S, variable);
                    return il.Create(OpCodes.Ldloc, variable);
            }
        }

        /// <summary>
        /// Helper method for inserting several instructions after a target instruction in their given order.
        /// </summary>
        public static void InsertAfter(this ILProcessor il, Instruction target, params Instruction[] instructions)
        {
            int position = 0;
            Instruction lastAdded = target;
            while (position < instructions.Length)
            {
                il.InsertAfter(lastAdded, instructions[position]);
                lastAdded = instructions[position];
                position++;
            }
        }

        /// <summary>
        /// Whether the given integer is within the boundaries of a signed byte.
        /// </summary>
        private static bool IsSByte(int value)
        {
            return value >= sbyte.MinValue && value <= sbyte.MaxValue;
        }
    }
}


text:
module Inknote.DropCanvas {

    export class DropCanvas {

        private static _instance: DropCanvas;

        static get Instance(): DropCanvas {
            if (!DropCanvas._instance) {
                DropCanvas._instance = new DropCanvas();
            }
            return DropCanvas._instance;
        }

        _canvas: HTMLCanvasElement;

        get canvas() {
            if (!this._canvas) {
                this._canvas = <HTMLCanvasElement>document.getElementById("drag-drop-canvas");
            }
            return this._canvas;
        }

        private _ctx: CanvasRenderingContext2D;

        get ctx(): CanvasRenderingContext2D {
            if (!this._ctx) {
                this._ctx = this.canvas.getContext("2d");
            }
            return this._ctx;
        }

        maxSplashTime: number = 200;

        running: boolean = false;
        dropped: boolean = false;
        splashed: boolean = false;
        splashCounter: number = 0;
        finished: boolean = false;
        springBaseSize: number;

        segmentSize = 15;

        springs: Spring[] = [];
        files: DropFile[] = [];
        droplets: Droplet[] = [];

        start() {
            if (this.running == true) {
                return;
            }

            this.running = true;
            this.dropped = false;
            this.splashed = false;
            this.splashCounter = 0;
            this.finished = false;

            if (Landing.Landing.Instance.ended === false) {
                Landing.Landing.Instance.hide();
            }

            FrontEnd.showElement(document.getElementById("drag-drop"));

            this.canvas.width = this.canvas.parentElement.clientWidth;
            this.canvas.height = this.canvas.parentElement.clientHeight;

            var segments = Math.floor(this.canvas.width / this.segmentSize);
            this.springs = [];
            this.files = [];
            this.droplets = [];

            this.springBaseSize = this.canvas.height / 6;

            for (var i = 0; i <= segments + 1; i++) {
                this.springs.push(new Spring(i * this.segmentSize, this.springBaseSize, this.canvas.height, i));
            }

            var self = this;

            this.draw(self);
        }

        splashTime: number = 0;

        draw(self: DropCanvas) {
            if (self.running == false) {
                FrontEnd.hideElement(document.getElementById("drag-drop"));
                return;
            }

            self.ctx.clearRect(0, 0, self.canvas.width, self.canvas.height);

            var splashes = updateFiles(self.files, self.springs, self.canvas.height - self.springBaseSize);

            for (var i = 0; i < splashes.length; i++) {
                self.splash(splashes[i].index, splashes[i].strength);
            }

            var newFiles = [];
            for (var i = 0; i < self.files.length; i++) {
                if (self.files[i].y < self.canvas.height) {
                    newFiles.push(self.files[i]);
                }
                else {
                    self.splashed = true;
                }
            }

            if (self.splashed == true) {
                self.splashCounter++;

                if (self.splashCounter > self.maxSplashTime) {
                    self.finished = true;
                    self.stop();
                }
            }

            self.files = newFiles;

            drawFiles(self.files, self.ctx);

            var newDroplets = [];

            for (var i = 0; i < self.droplets.length; i++) {
                self.droplets[i].update();
                self.droplets[i].draw(self.ctx);
                if (self.droplets[i].position.y < self.canvas.height) {
                    newDroplets.push(self.droplets[i]);
                }
            }

            self.droplets = newDroplets;

            if (self.splashTime == 0) {
                self.splash(Math.floor(Math.random() * self.springs.length), 2 * Math.random());
            }
            self.splashTime = (self.splashTime + 1) % 4;

            self.ctx.beginPath();
            self.ctx.moveTo(0, self.canvas.height);

            updateSprings(self.springs);

            for (var i = 0; i < self.springs.length; i++) {

                self.ctx.lineTo(self.springs[i].x, self.springs[i].bottomY - self.springs[i].baseY - self.springs[i].y);

            }

            self.ctx.lineTo(self.canvas.width, self.canvas.height);
            self.ctx.lineTo(0, self.canvas.height);

            self.ctx.fillStyle = Drawing.Colours.black;
            self.ctx.strokeStyle = Drawing.Colours.black;
            self.ctx.fill();
            self.ctx.stroke();

            if (self.running == true) {
                window.requestAnimationFrame(function () { self.draw(self) });
            }
            else {
                FrontEnd.hideElement(document.getElementById("drag-drop"));
            }
        }

        drop(x: number, y: number) {
            this.dropped = true;
            this.files.push(new DropFile(x, y));
        }

        stop() {
            if (this.dropped && !this.finished) {
                return;
            }
            this.running = false;
            FrontEnd.hideElement(document.getElementById("drag-drop"));
        }

        splash(index: number, speed: number) {
            if (index >= 0 && index < this.springs.length) {
                this.springs[index].velocity = -speed;
            }

            if (speed > 10) {
                for (var i = 0; i < Math.floor(speed / 2); i++) {
                    var pos = new Maths.Vector2(index * this.segmentSize, this.canvas.height);
                    var vel = new Maths.Vector2(10 * Math.random() - 5,  -speed * Math.random() / 4);
                    var droplet = new Droplet(pos, vel, 5 * Math.random());

                    this.droplets.push(droplet);
                }
            }
        }

    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN""http://www.w3.org/TR/REC-html40/frameset.dtd">

<TITLE>
Xerces2 Implementation: Class  SchemaDateTimeException
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  SUMMARY:  INNER | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

org.apache.xerces.impl.dv.xs

Class  SchemaDateTimeException

java.lang.Object
  |
  +--java.lang.Throwable
        |
        +--java.lang.Exception
              |
              +--java.lang.RuntimeException
                    |
                    +--org.apache.xerces.impl.dv.xs.SchemaDateTimeException

All Implemented Interfaces:
java.io.Serializable

public class SchemaDateTimeException
extends java.lang.RuntimeException

INTERNAL:

Usage of this class is not supported. It may be altered or removed at any time.

Version:
$Id: SchemaDateTimeException.java 446745 2006-09-15 21:43:58Z mrglavas $

See Also:
Serialized Form

Constructor Summary

SchemaDateTimeException()

SchemaDateTimeException(java.lang.String s)

Methods inherited from class java.lang.Throwable

fillInStackTrace, getLocalizedMessage, getMessage, printStackTrace, printStackTrace, printStackTrace, toString

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

SchemaDateTimeException

public SchemaDateTimeException()

SchemaDateTimeException

public SchemaDateTimeException(java.lang.String s)

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  SUMMARY:  INNER | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

Copyright © 1999-2007 The Apache Software Foundation. All Rights Reserved.


text:
public class House {

    private static final String SENTENCE_BEGINNING_THIS = "This";
    private static final String SENTENCE_BEGINNING_THAT = "that";
    private static final String FIRST_VERB = " is ";
    private static final String[] SENTENCE_COMPONENT = new String[]{"the house that Jack built.", "the malt", "the rat", "the cat", "the dog",
            "the cow with the crumpled horn", "the maiden all forlorn", "the man all tattered and torn", "the priest all shaven and shorn",
            "the rooster that crowed in the morn", "the farmer sowing his corn", "the horse and the hound and the horn"};
    private static final String[] SENTENCE_VERB = new String[]{" lay in ", " ate ", " killed ", " worried ", " tossed ", " milked ",
            " kissed ", " married ", " woke ", " kept ", " belonged to "};

    public String verse(int verse) {
        int initialVerseNumber = verse-1;

        StringBuilder sb = new StringBuilder(SENTENCE_BEGINNING_THIS).append(FIRST_VERB).append(SENTENCE_COMPONENT[initialVerseNumber]);
        for(int i = initialVerseNumber-1; i >= 0; i--) {
            sb.append(" ").append(SENTENCE_BEGINNING_THAT).append(SENTENCE_VERB[i]).append(SENTENCE_COMPONENT[i]);
        }
        return sb.toString();
    }

    public String verses(int startVerse, int endVerse) {
        StringBuilder sb = new StringBuilder();
        for (int i = startVerse; i <= endVerse; i++) {
            sb.append(this.verse(i));
            if(i < endVerse) {
                sb.append("\n");
            }
        }
        return sb.toString();
    }

    public String sing() {
        return verses(1,12);
    }
}


text:
$(document).ready(function() {
    $("#deleteButton").click(function () {
        $(document.body).append(new ConfirmationBox("Are you sure you want to delete floor {{ floor.name }}?",
                    [ {text: "Yes", func: function(){ window.location.href = "{% url "deleteFloor" pkFloor=floor.pk %}";} },
                    {text: "No", func: function(){ this.destroy(); } } ]).$holder);
    });
});


text:
<?php

namespace Oro\Bundle\FilterBundle\Tests\Functional\Form\Type\Filter;

use Symfony\Component\Form\FormFactoryInterface;

use Oro\Bundle\FilterBundle\Form\Type\Filter\SkipEmptyPeriodsFilterType;
use Oro\Bundle\TestFrameworkBundle\Test\WebTestCase;

class SkipEmptyPeriodsFilterTypeTest extends WebTestCase
{
    /**
     * {@inheritdoc}
     */
    public function setUp()
    {
        parent::setUp();
        $this->initClient();
    }

    /**
     * @dataProvider validDataProvider
     * @param array $submittedData
     * @param array $expectedData
     */
    public function testFormSubmitValidData(array $submittedData, array $expectedData)
    {
        $form = $this->getFormFactory()->create(
            SkipEmptyPeriodsFilterType::NAME,
            null,
            [
                'csrf_protection' => false,
            ]
        );

        $form->submit($submittedData);

        $this->assertTrue($form->isSynchronized());
        $this->assertTrue($form->isValid());
        $this->assertEquals($expectedData, $form->getData());
    }

    /**
     * @return array
     */
    public function validDataProvider()
    {
        return [
            'type_no' => [
                [
                    'value' => false,
                ],
                [
                    'value' => false,
                    'type' => null,
                ]
            ],
            'type_yes' => [
                [
                    'value' => true,
                ],
                [
                    'value' => true,
                    'type' => null,
                ],
            ],
        ];
    }

    /**
     * @return FormFactoryInterface
     */
    protected function getFormFactory()
    {
        return $this->getContainer()->get('form.factory');
    }
}


text:
# Rampage.js [![npm Version](http://img.shields.io/npm/v/rampage.svg?style=flat)](https://www.npmjs.org/package/rampage) [![Build Status](https://img.shields.io/travis/yuanqing/rampage.svg?style=flat)](https://travis-ci.org/yuanqing/rampage) [![Coverage Status](https://img.shields.io/coveralls/yuanqing/rampage.svg?style=flat)](https://coveralls.io/r/yuanqing/rampage)

> A generic way to split an array into pages, with optional callbacks to modify the structure of each page.

## Usage

```js
var arr = [
  { foo: 'bar' },
  { foo: 'baz' },
  { foo: 'qux' }
];

rampage(arr, 2);
/* [
 *   [ arr[0], arr[1] ],
 *   [ arr[2] ]
 * ]
 */
```

Note that a new array is returned; the original `arr` is unchanged.

Pass in `opts` if you want to create previous/next links or customise the structure of each page:

```js
var opts = {
  preProcess: function(pageItems, pageNum, totalPages) {
    return {
      pageItems: pageItems,
      pageNum: pageNum
    };
  },
  postProcess: function(currPage, prevPage, nextPage, pageNum, totalPages) {
    currPage.prevPage = prevPage;
    currPage.nextPage = nextPage;
    return currPage;
  }
};

var result = rampage(arr, 2, opts);
/* [
 *   {
 *     pageItems: [ arr[0], arr[1] ],
 *     pageNum: 0,
 *     prevPage: undefined,
 *     nextPage: result[1]
 *   },
 *   {
 *     pageItems: [ arr[2] ],
 *     pageNum: 1,
 *     prevPage: result[0],
 *     nextPage: undefined
 *   }
 * ]
 */
```

## API

### rampage(arr, numPerPage [, opts])

- `arr` — An array.
- `numPerPage` — A positive integer.
- `opts` — Used to define the `preProcess` and `preProcess` callbacks.

  - `opts.preProcess` [maps](http://en.wikipedia.org/wiki/Map_(higher-order_function)) over each slice of `arr`. It defaults to the identity function, and takes the following arguments:

    1. `pageItems` — The current slice of `arr`, which would have at most `numPerPage` number of items.
    2. `pageNum` — The current page number. Page numbers start from `0`.
    3. `totalPages` — The total number of pages.

  - `opts.postProcess` maps over the result of `opts.preProcess`. It takes the following arguments:

    1. `currPage` — The current page.
    2. `prevPage` — A reference to the previous page, or `undefined` if there is no previous page.
    3. `nextPage` — A reference to the next page, or `undefined` if there is no next page.
    4. `pageNum` — The current page number. Page numbers start from `0`.
    5. `totalPages` — The total number of pages.

## Installation

Install via [npm](https://www.npmjs.org/):

```bash
$ npm i --save rampage
```

## Changelog

- 0.1.0
  - Initial release

## License

[MIT license](https://github.com/yuanqing/rampage/blob/master/LICENSE)


text:
<?php

$schema['newsletters.update'] = array(
    'func' => array('fn_get_newsletter_name', '@newsletter_id'),
    'text' => 'newsletter'
);
$schema['news.update'] = array(
    'func' => array('fn_get_news_name', '@news_id'),
    'text' => 'news'
);
$schema['mailing_lists.manage'] = array(
    'text' => 'mailing_lists'
);
$schema['subscribers.manage'] = array(
    'text' => 'subscribers'
);
$schema['newsletters.campaigns'] = array(
    'text' => 'campaigns'
);

return $schema;


text:
class CacheSumAttributeWordCountJob < ApplicationJob
  queue_as :cache

  def perform(*args)
    entity_type = args.shift
    entity_id   = args.shift

    entity = entity_type.constantize.find_by(id: entity_id)
    return if entity.nil?

    sum_attribute_word_count = Attribute.where(entity_type: entity_type, entity_id: entity_id).sum(:word_count_cache)
    update = entity.word_count_updates.find_or_initialize_by(
      for_date: DateTime.current,
    )
    update.word_count = sum_attribute_word_count
    update.user_id  ||= entity.user_id

    update.save!
  end
end


text:
package org.springframework.samples.petclinic.jdbc;

import org.springframework.samples.petclinic.Pet;

/**
 * @author Juergen Hoeller
 */
public class JdbcPet extends Pet {

	private int typeId;

	private int ownerId;

	public void setTypeId(int typeId) {
		this.typeId = typeId;
	}

	public int getTypeId() {
		return this.typeId;
	}

	public void setOwnerId(int ownerId) {
		this.ownerId = ownerId;
	}

	public int getOwnerId() {
		return ownerId;
	}

}


text:
#include "memtx_bitset.h"

#include <string.h>

#include "tuple.h"

static inline struct tuple *
value_to_tuple(size_t value);

static inline size_t
tuple_to_value(struct tuple *tuple)
{
	/*
	 * @todo small_ptr_compress() is broken
	 * https://github.com/tarantool/tarantool/issues/49
	 */
	/* size_t value = small_ptr_compress(tuple); */
	size_t value = (intptr_t) tuple >> 2;
	assert(value_to_tuple(value) == tuple);
	return value;
}

static inline struct tuple *
value_to_tuple(size_t value)
{
	/* return (struct tuple *) salloc_ptr_from_index(value); */
	return (struct tuple *) (value << 2);
}
struct bitset_index_iterator {
	struct iterator base; /* Must be the first member. */
	struct bitset_iterator bitset_it;
};

static struct bitset_index_iterator *
bitset_index_iterator(struct iterator *it)
{
	return (struct bitset_index_iterator *) it;
}

void
bitset_index_iterator_free(struct iterator *iterator)
{
	assert(iterator->free == bitset_index_iterator_free);
	struct bitset_index_iterator *it = bitset_index_iterator(iterator);

	bitset_iterator_destroy(&it->bitset_it);
	free(it);
}

struct tuple *
bitset_index_iterator_next(struct iterator *iterator)
{
	assert(iterator->free == bitset_index_iterator_free);
	struct bitset_index_iterator *it = bitset_index_iterator(iterator);

	size_t value = bitset_iterator_next(&it->bitset_it);
	if (value == SIZE_MAX)
		return NULL;

	return value_to_tuple(value);
}

MemtxBitset::MemtxBitset(struct key_def *key_def)
	: Index(key_def)
{
	assert(!this->key_def->is_unique);

	if (bitset_index_create(&index, realloc) != 0)
		panic_syserror("bitset_index_create");
}

MemtxBitset::~MemtxBitset()
{
	bitset_index_destroy(&index);
}

size_t
MemtxBitset::size() const
{
	return bitset_index_size(&index);
}

size_t
MemtxBitset::memsize() const
{
	return 0;
}

struct iterator *
MemtxBitset::allocIterator() const
{
	struct bitset_index_iterator *it = (struct bitset_index_iterator *)
			malloc(sizeof(*it));
	if (!it)
		return NULL;

	memset(it, 0, sizeof(*it));
	it->base.next = bitset_index_iterator_next;
	it->base.free = bitset_index_iterator_free;

	bitset_iterator_create(&it->bitset_it, realloc);

	return (struct iterator *) it;
}

struct tuple *
MemtxBitset::findByKey(const char *key, uint32_t part_count) const
{
	(void) key;
	(void) part_count;
	tnt_raise(ClientError, ER_UNSUPPORTED, "MemtxBitset", "findByKey()");
	return NULL;
}

static inline const char *
make_key(const char *field, uint32_t *key_len)
{
	static uint64_t u64key;
	switch (mp_typeof(*field)) {
	case MP_UINT:
		u64key = mp_decode_uint(&field);
		*key_len = sizeof(uint64_t);
		return (const char *) &u64key;
		break;
	case MP_STR:
		return mp_decode_str(&field, key_len);
		break;
	default:
		*key_len = 0;
		assert(false);
		return NULL;
	}
}

struct tuple *
MemtxBitset::replace(struct tuple *old_tuple, struct tuple *new_tuple,
		     enum dup_replace_mode mode)
{
	assert(!key_def->is_unique);
	assert(old_tuple != NULL || new_tuple != NULL);
	(void) mode;

	struct tuple *ret = NULL;

	if (old_tuple != NULL) {
		size_t value = tuple_to_value(old_tuple);
		if (bitset_index_contains_value(&index, value)) {
			ret = old_tuple;

			assert(old_tuple != new_tuple);
			bitset_index_remove_value(&index, value);
		}
	}

	if (new_tuple != NULL) {
		const char *field;
		field = tuple_field(new_tuple, key_def->parts[0].fieldno);
		uint32_t key_len;
		const void *key = make_key(field, &key_len);
		size_t value = tuple_to_value(new_tuple);
		if (bitset_index_insert(&index, key, key_len, value) < 0) {
			tnt_raise(ClientError, ER_MEMORY_ISSUE, 0,
				  "MemtxBitset", "insert");
		}
	}

	return ret;
}

void
MemtxBitset::initIterator(struct iterator *iterator, enum iterator_type type,
			  const char *key, uint32_t part_count) const
{
	assert(iterator->free == bitset_index_iterator_free);
	assert(part_count == 0 || key != NULL);
	(void) part_count;

	struct bitset_index_iterator *it = bitset_index_iterator(iterator);

	const void *bitset_key = NULL;
	uint32_t bitset_key_size = 0;

	if (type != ITER_ALL) {
		assert(part_count == 1);
		bitset_key = make_key(key, &bitset_key_size);
	}

	struct bitset_expr expr;
	bitset_expr_create(&expr, realloc);
	try {
		int rc = 0;
		switch (type) {
		case ITER_ALL:
			rc = bitset_index_expr_all(&expr);
			break;
		case ITER_EQ:
			rc = bitset_index_expr_equals(&expr, bitset_key,
						      bitset_key_size);
			break;
		case ITER_BITS_ALL_SET:
			rc = bitset_index_expr_all_set(&expr, bitset_key,
						       bitset_key_size);
			break;
		case ITER_BITS_ALL_NOT_SET:
			rc = bitset_index_expr_all_not_set(&expr, bitset_key,
							   bitset_key_size);
			break;
		case ITER_BITS_ANY_SET:
			rc = bitset_index_expr_any_set(&expr, bitset_key,
						       bitset_key_size);
			break;
		default:
			tnt_raise(ClientError, ER_UNSUPPORTED,
				  "MemtxBitset", "requested iterator type");
		}

		if (rc != 0) {
			tnt_raise(ClientError, ER_MEMORY_ISSUE,
				  0, "MemtxBitset", "iterator expression");
		}

		if (bitset_index_init_iterator((bitset_index *) &index,
					       &it->bitset_it,
					       &expr) != 0) {
			tnt_raise(ClientError, ER_MEMORY_ISSUE,
				  0, "MemtxBitset", "iterator state");
		}

		bitset_expr_destroy(&expr);
	} catch (Exception *e) {
		bitset_expr_destroy(&expr);
		throw;
	}
}


text:
package edu.kit.iks.Cryptographics.DiffieHellman;

import java.awt.Color;

import org.junit.Before;
import org.junit.Test;

import edu.kit.iks.Cryptographics.DiffieHellman.Model;
import junit.framework.TestCase;

public class ModelTest extends TestCase  {
	private Model model;

	@Before
	public void setUp() throws Exception {
		this.model = new Model();
	}

	@Test
	public void testMixAlicePrivateAndPublic() {
		Color publicColor = Color.RED;
		Color privateColor = Color.BLUE;

		this.model.setPublicColor(publicColor);
		assertEquals(this.model.getPublicColor(), publicColor);
		this.model.setAlicePrivateColor(privateColor);
		assertEquals(this.model.getAlicePrivateColor(), privateColor);

		this.model.mixAlicePrivateAndPublic();
		Color expected = new Color(127, 0, 127);
		Color actual = this.model.getAliceMixedColor();
		assertEquals(expected, actual);
	}

	@Test
	public void testMixBobPrivateAndPublic() {
		Color publicColor = Color.YELLOW;
		Color privateColor = Color.PINK;

		this.model.setPublicColor(publicColor);
		assertEquals(this.model.getPublicColor(), publicColor);
		this.model.setBobPrivateColor(privateColor);
		assertEquals(this.model.getBobPrivateColor(), privateColor);

		this.model.mixBobPrivateAndPublic();
		Color expected = new Color(255, 215, 87);
		Color actual = this.model.getBobMixedColor();
		assertEquals(expected, actual);
	}
}


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

    <modelVersion>4.0.0</modelVersion>

    <groupId>org.ld4l</groupId>
    <artifactId>vitrolib-project</artifactId>
    <version>0.1</version>
    <packaging>pom</packaging>

    <name>vitrolib</name>
    <description>LD4L vitrolib project</description>
    <url>http://ld4l.org/</url>

    <licenses>
        <license>
            <name>BSD 3-Clause License</name>
            <url>https://raw.github.com/ld4l-labs/vitrolib/master/LICENSE</url>
            <distribution>repo</distribution>
        </license>
    </licenses>

    <developers>
        <developer>
            <name>Rebecca Younes</name>
            <email>rjy7@cornell.edu</email>
            <organization>Cornell University Library</organization>
            <organizationUrl>https://github.com/rjyounes</organizationUrl>
        </developer>
        <developer>
            <name>Huda Khan</name>
            <email>hjk54cornell.edu</email>
            <organization>Cornell University</organization>
            <organizationUrl>https://github.com/hudajkhan</organizationUrl>
        </developer>
        <developer>
            <name>Jim Blake</name>
            <email>jeb228@cornell.edu</email>
            <organization>Cornell University Library</organization>
            <organizationUrl>https://github.com/j2blake</organizationUrl>
        </developer>
    </developers>

    <scm>
        <connection>scm:git:git@github.com:ld4l-labs/vitrolib.git</connection>
        <developerConnection>scm:git:git@github.com:ld4l-labs/vitrolib.git</developerConnection>
        <url>git@github.com:ld4l-labs/vitrolib.git</url>
        <tag>HEAD</tag>
    </scm>

    <properties>
        <vitro-version>1.10.0-SNAPSHOT</vitro-version>
        <vitrolib-home-dir>${basedir}</vitrolib-home-dir>
        <maven.build.timestamp.format>yyyy-MM-dd HH:mm:ss</maven.build.timestamp.format>
        <build.timestamp>${maven.build.timestamp}</build.timestamp>
    </properties>

    <modules>
        <module>api</module>
        <module>webapp</module>
        <module>home</module>
    </modules>

    <profiles>
        <profile>
            <id>vitro</id>
            <activation>
                <file>
                    <exists>../Vitro/pom.xml</exists>
                </file>
            </activation>
            <modules>
                <module>../Vitro</module>
            </modules>
        </profile>
        <profile>
            <id>installer</id>
            <activation>
                <property>
                    <name>!vitrolib-installer-dir</name>
                </property>
            </activation>
            <modules>
                <module>installer</module>
            </modules>
        </profile>
        <profile>
            <id>external-installer</id>
            <activation>
                <property>
                    <name>vitrolib-installer-dir</name>
                </property>
            </activation>
            <modules>
                <module>${vitrolib-installer-dir}</module>
            </modules>
        </profile>
        <profile>
            <id>doclint-java8-disable</id>
            <activation>
                <jdk>[1.8,)</jdk>
            </activation>
            <properties>
                <javadoc.opts>-Xdoclint:none</javadoc.opts>
            </properties>
        </profile>
        <profile>
            <id>release</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-javadoc-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>attach-javadocs</id>
                                <goals>
                                    <goal>jar</goal>
                                </goals>
                            </execution>
                        </executions>
                        <configuration>
                            <quiet>true</quiet>
                            <additionalparam>${javadoc.opts}</additionalparam>
                        </configuration>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-source-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>attach-sources</id>
                                <goals>
                                    <goal>jar-no-fork</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-gpg-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>sign-artifacts</id>
                                <phase>verify</phase>
                                <goals>
                                    <goal>sign</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <groupId>org.sonatype.plugins</groupId>
                        <artifactId>nexus-staging-maven-plugin</artifactId>
                        <extensions>true</extensions>
                        <configuration>
                            <serverId>ossrh</serverId>
                            <nexusUrl>https://oss.sonatype.org/</nexusUrl>
                            <autoReleaseAfterClose>false</autoReleaseAfterClose>
                        </configuration>
                    </plugin>
                    <plugin>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>buildnumber-maven-plugin</artifactId>
                        <executions>
                            <execution>
                                <phase>validate</phase>
                                <goals>
                                    <goal>create</goal>
                                </goals>
                            </execution>
                        </executions>
                        <configuration>
                            <doCheck>false</doCheck>
                            <doUpdate>false</doUpdate>
                            <shortRevisionLength>7</shortRevisionLength>
                            <revisionOnScmFailure>true</revisionOnScmFailure>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.vivoweb</groupId>
                <artifactId>vitro-api</artifactId>
                <version>${vitro-version}</version>
            </dependency>
            <dependency>
                <groupId>org.vivoweb</groupId>
                <artifactId>vitro-api</artifactId>
                <version>${vitro-version}</version>
                <type>test-jar</type>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.vivoweb</groupId>
                <artifactId>vitro-dependencies</artifactId>
                <version>${vitro-version}</version>
                <type>pom</type>
            </dependency>
            <dependency>
                <groupId>org.vivoweb</groupId>
                <artifactId>vitro-home</artifactId>
                <version>${vitro-version}</version>
                <type>tar.gz</type>
            </dependency>
            <dependency>
                <groupId>org.vivoweb</groupId>
                <artifactId>vitro-webapp</artifactId>
                <version>${vitro-version}</version>
                <type>war</type>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
        <pluginManagement>
            <plugins>
                <plugin>
                    <artifactId>maven-assembly-plugin</artifactId>
                    <version>2.5.5</version>
                </plugin>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.0.0</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.5.1</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-gpg-plugin</artifactId>
                    <version>1.6</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-jar-plugin</artifactId>
                    <version>2.6</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-javadoc-plugin</artifactId>
                    <version>2.9.1</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-source-plugin</artifactId>
                    <version>2.2.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>2.6</version>
                </plugin>
                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>build-helper-maven-plugin</artifactId>
                    <version>1.9.1</version>
                </plugin>
                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>buildnumber-maven-plugin</artifactId>
                    <version>1.4</version>
                </plugin>
                <plugin>
                    <groupId>org.sonatype.plugins</groupId>
                    <artifactId>nexus-staging-maven-plugin</artifactId>
                    <version>1.6.3</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>


text:
package com.amazonaws.services.macie2.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * Specifies a property- or tag-based condition that defines criteria for including or excluding S3 objects from a
 * classification job. A JobScopeTerm object can contain only one simpleScopeTerm object or one tagScopeTerm object.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class JobScopeTerm implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * A property-based condition that defines a property, operator, and one or more values for including or excluding
     * objects from the job.
     *

     */
    private SimpleScopeTerm simpleScopeTerm;
    /**
     *

     * A tag-based condition that defines the operator and tag keys or tag key and value pairs for including or
     * excluding objects from the job.
     *

     */
    private TagScopeTerm tagScopeTerm;

    /**
     *

     * A property-based condition that defines a property, operator, and one or more values for including or excluding
     * objects from the job.
     *

     *
     * @param simpleScopeTerm
     *        A property-based condition that defines a property, operator, and one or more values for including or
     *        excluding objects from the job.
     */

    public void setSimpleScopeTerm(SimpleScopeTerm simpleScopeTerm) {
        this.simpleScopeTerm = simpleScopeTerm;
    }

    /**
     *

     * A property-based condition that defines a property, operator, and one or more values for including or excluding
     * objects from the job.
     *

     *
     * @return A property-based condition that defines a property, operator, and one or more values for including or
     *         excluding objects from the job.
     */

    public SimpleScopeTerm getSimpleScopeTerm() {
        return this.simpleScopeTerm;
    }

    /**
     *

     * A property-based condition that defines a property, operator, and one or more values for including or excluding
     * objects from the job.
     *

     *
     * @param simpleScopeTerm
     *        A property-based condition that defines a property, operator, and one or more values for including or
     *        excluding objects from the job.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public JobScopeTerm withSimpleScopeTerm(SimpleScopeTerm simpleScopeTerm) {
        setSimpleScopeTerm(simpleScopeTerm);
        return this;
    }

    /**
     *

     * A tag-based condition that defines the operator and tag keys or tag key and value pairs for including or
     * excluding objects from the job.
     *

     *
     * @param tagScopeTerm
     *        A tag-based condition that defines the operator and tag keys or tag key and value pairs for including or
     *        excluding objects from the job.
     */

    public void setTagScopeTerm(TagScopeTerm tagScopeTerm) {
        this.tagScopeTerm = tagScopeTerm;
    }

    /**
     *

     * A tag-based condition that defines the operator and tag keys or tag key and value pairs for including or
     * excluding objects from the job.
     *

     *
     * @return A tag-based condition that defines the operator and tag keys or tag key and value pairs for including or
     *         excluding objects from the job.
     */

    public TagScopeTerm getTagScopeTerm() {
        return this.tagScopeTerm;
    }

    /**
     *

     * A tag-based condition that defines the operator and tag keys or tag key and value pairs for including or
     * excluding objects from the job.
     *

     *
     * @param tagScopeTerm
     *        A tag-based condition that defines the operator and tag keys or tag key and value pairs for including or
     *        excluding objects from the job.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public JobScopeTerm withTagScopeTerm(TagScopeTerm tagScopeTerm) {
        setTagScopeTerm(tagScopeTerm);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getSimpleScopeTerm() != null)
            sb.append("SimpleScopeTerm: ").append(getSimpleScopeTerm()).append(",");
        if (getTagScopeTerm() != null)
            sb.append("TagScopeTerm: ").append(getTagScopeTerm());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof JobScopeTerm == false)
            return false;
        JobScopeTerm other = (JobScopeTerm) obj;
        if (other.getSimpleScopeTerm() == null ^ this.getSimpleScopeTerm() == null)
            return false;
        if (other.getSimpleScopeTerm() != null && other.getSimpleScopeTerm().equals(this.getSimpleScopeTerm()) == false)
            return false;
        if (other.getTagScopeTerm() == null ^ this.getTagScopeTerm() == null)
            return false;
        if (other.getTagScopeTerm() != null && other.getTagScopeTerm().equals(this.getTagScopeTerm()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getSimpleScopeTerm() == null) ? 0 : getSimpleScopeTerm().hashCode());
        hashCode = prime * hashCode + ((getTagScopeTerm() == null) ? 0 : getTagScopeTerm().hashCode());
        return hashCode;
    }

    @Override
    public JobScopeTerm clone() {
        try {
            return (JobScopeTerm) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.macie2.model.transform.JobScopeTermMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
package mongodb

import (
	"github.com/compose/transporter/client"
	mgo "gopkg.in/mgo.v2"
)

// Session serves as a wrapper for the underlying mgo.Session
type Session struct {
	mgoSession *mgo.Session
}

var _ client.Session = &Session{}

// Close implements necessary calls to cleanup the underlying mgo.Session
func (s *Session) Close() {
	s.mgoSession.Close()
}


text:
<?php

declare(strict_types = 1);

namespace bitExpert\Adroit;

use bitExpert\Adroit\Action\Action;
use bitExpert\Adroit\Action\Resolver\ActionResolverMiddleware;
use bitExpert\Adroit\Action\Executor\ActionExecutorMiddleware;
use bitExpert\Adroit\Responder\Resolver\ResponderResolverMiddleware;
use bitExpert\Adroit\Responder\Executor\ResponderExecutorMiddleware;
use bitExpert\Adroit\Responder\Responder;
use bitExpert\Adroit\Domain\Payload;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Stratigility\MiddlewarePipe;
use Zend\Stratigility\NoopFinalHandler;

/**
 * MiddlewarePipe implementation for an Adroit web application.
 *
 * @api
 */
class AdroitMiddleware extends MiddlewarePipe
{
    protected static $actionAttribute = Action::class;
    protected static $payloadAttribute = Payload::class;
    protected static $responderAttribute = Responder::class;

    /**
     * @var string
     */
    protected $routingResultAttribute;
    /**
     * @var \bitExpert\Adroit\Action\Resolver\ActionResolver[]
     */
    protected $actionResolvers;
    /**
     * @var \bitExpert\Adroit\Responder\Resolver\ResponderResolver[]
     */
    protected $responderResolvers;
    /**
     * @var callable[]
     */
    protected $beforeActionResolverMiddlewares;
    /**
     * @var callable[]
     */
    protected $beforeActionExecutorMiddlewares;
    /**
     * @var callable[]
     */
    protected $beforeResponderResolverMiddlewares;
    /**
     * @var callable[]
     */
    protected $beforeResponderExecutorMiddlewares;

    /**
     * AdroitMiddleware constructor.
     *
     * @param string $routingResultAttribute
     * @param \bitExpert\Adroit\Action\Resolver\ActionResolver[] $actionResolvers
     * @param \bitExpert\Adroit\Responder\Resolver\ResponderResolver[] $responderResolvers
     */
    public function __construct($routingResultAttribute, array $actionResolvers, array $responderResolvers)
    {
        parent::__construct();

        $this->routingResultAttribute = $routingResultAttribute;
        $this->actionResolvers = $actionResolvers;
        $this->responderResolvers = $responderResolvers;

        $this->beforeActionResolverMiddlewares = [];
        $this->beforeActionExecutorMiddlewares = [];
        $this->beforeResponderResolverMiddlewares = [];
        $this->beforeResponderExecutorMiddlewares = [];
    }

    /**
     * Adds the given middleware to the pipe before the action middleware
     * (chainable)
     *
     * @param callable $middleware
     * @return AdroitMiddleware
     */
    public function beforeResolveAction(callable $middleware) : self
    {
        $this->beforeActionResolverMiddlewares[] = $middleware;
        return $this;
    }

    /**
     * Adds the given middleware to the pipe before the action middleware
     * (chainable)
     *
     * @param callable $middleware
     * @return AdroitMiddleware
     */
    public function beforeExecuteAction(callable $middleware) : self
    {
        $this->beforeActionExecutorMiddlewares[] = $middleware;
        return $this;
    }

    /**
     * Adds the given middleware to the pipe after the action middleware and before the responder middleware
     * (chainable)
     *
     * @param callable $middleware
     * @return AdroitMiddleware
     */
    public function beforeResolveResponder(callable $middleware) : self
    {
        $this->beforeResponderResolverMiddlewares[] = $middleware;
        return $this;
    }

    /**
     * Adds the given middleware to the pipe after the action middleware and before the responder middleware
     * (chainable)
     *
     * @param callable $middleware
     * @return AdroitMiddleware
     */
    public function beforeExecuteResponder(callable $middleware) : self
    {
        $this->beforeResponderExecutorMiddlewares[] = $middleware;
        return $this;
    }

    /**
     * @inheritdoc
     */
    public function __invoke(
        ServerRequestInterface $request,
        ResponseInterface $response,
        callable $out = null
    ) : ResponseInterface {
        $out = $out ?: new NoopFinalHandler();
        $this->initialize();
        return parent::__invoke($request, $response, $out);
    }

    /**
     * Pipes all given middlewares.
     *
     * @param callable[] $middlewares
     */
    protected function pipeEach(array $middlewares)
    {
        foreach ($middlewares as $middleware) {
            $this->pipe($middleware);
        }
    }

    /**
     * Initializes the application by piping the fixed middlewares (routing, action, responder)
     * and the configured middlewares in the right order.
     */
    protected function initialize()
    {
        $actionResolverMiddleware = $this->getActionResolverMiddleware(
            $this->actionResolvers,
            $this->routingResultAttribute,
            self::$actionAttribute
        );

        $actionExecutorMiddleware = $this->getActionExecutorMiddleware(
            self::$actionAttribute,
            self::$payloadAttribute
        );

        $responderResolverMiddleware = $this->getResponderResolverMiddleware(
            $this->responderResolvers,
            self::$payloadAttribute,
            self::$responderAttribute
        );

        $responderExecutorMiddleware = $this->getResponderExecutorMiddleware(
            self::$responderAttribute,
            self::$payloadAttribute
        );

        $this->pipeEach($this->beforeActionResolverMiddlewares);
        $this->pipe($actionResolverMiddleware);
        $this->pipeEach($this->beforeActionExecutorMiddlewares);
        $this->pipe($actionExecutorMiddleware);
        $this->pipeEach($this->beforeResponderResolverMiddlewares);
        $this->pipe($responderResolverMiddleware);
        $this->pipeEach($this->beforeResponderExecutorMiddlewares);
        $this->pipe($responderExecutorMiddleware);
    }

    /**
     * @param \bitExpert\Adroit\Action\Resolver\ActionResolver[] $actionResolvers
     * @param string $routingResultAttribute
     * @param string $actionAttribute
     * @return ActionResolverMiddleware
     */
    protected function getActionResolverMiddleware(
        array $actionResolvers,
        string $routingResultAttribute,
        string $actionAttribute
    ) : ActionResolverMiddleware {
        return new ActionResolverMiddleware($actionResolvers, $routingResultAttribute, $actionAttribute);
    }

    /**
     * @param string $actionAttribute
     * @param string $payloadAttribute
     * @return ActionExecutorMiddleware
     */
    protected function getActionExecutorMiddleware(
        string $actionAttribute,
        string $payloadAttribute
    ) : ActionExecutorMiddleware {
        return new ActionExecutorMiddleware($actionAttribute, $payloadAttribute);
    }

    /**
     * @param \bitExpert\Adroit\Responder\Resolver\ResponderResolver[] $responderResolvers
     * @param string $payloadAttribute
     * @param string $responderAttribute
     * @return ResponderResolverMiddleware
     */
    protected function getResponderResolverMiddleware(
        array $responderResolvers,
        string $payloadAttribute,
        string $responderAttribute
    ) : ResponderResolverMiddleware {
        return new ResponderResolverMiddleware($responderResolvers, $payloadAttribute, $responderAttribute);
    }

    /**
     * @param string $responderAttribute
     * @param string $payloadAttribute
     * @return ResponderExecutorMiddleware
     */
    protected function getResponderExecutorMiddleware(
        string $responderAttribute,
        string $payloadAttribute
    ) : ResponderExecutorMiddleware {
        return new ResponderExecutorMiddleware($responderAttribute, $payloadAttribute);
    }
}


text:
@implementation NSException (L3OCUnitCompatibility)

-(NSString *)filename {
	return self.userInfo[NSStringFromSelector(_cmd)];
}

-(NSNumber *)lineNumber {
	return self.userInfo[NSStringFromSelector(_cmd)];
}

+(NSException *)failureInFile:(NSString *)filename atLine:(int)lineNumber withDescription:(NSString *)formatString, ... {
	NSString *description = nil;
	if (formatString) {
		va_list arguments;
		va_start(arguments, formatString);
		description = [[NSString alloc] initWithFormat:formatString arguments:arguments];
		va_end(arguments);
	}

	return [NSException exceptionWithName:@"L3Exception" reason:description userInfo:@{
		@"filename": filename,
		@"lineNumber": @(lineNumber),
	}];
}

@end


text:
/*global describe, it */
'use strict';
var fs = require('fs');
var path = require('path');
var assert = require('assert');
var gifsicle = require('../lib/gifsicle');
var util = require('../lib/util');
var binPath = gifsicle.path;
var srcUrl = gifsicle.src;

describe('Gifsicle rebuild', function () {
	it('it should rebuild the gifsicle binaries', function (cb) {
		// Give this test time to build
		this.timeout(false);

		var origCTime = fs.statSync(binPath).ctime;
		util.build(srcUrl, path.dirname(binPath), function (err) {
			var actualCTime = fs.statSync(binPath).ctime;
			assert(actualCTime !== origCTime);
			cb(err);
		}).path;
	});
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NBitcoin.Protocol
{
	/// <summary>
	/// Ask for known peer addresses in the network
	/// </summary>
	[Payload("sendaddrv2")]
	public class SendAddrV2Payload : Payload
	{
	}
}


text:
package com.jcwhatever.nucleus.managed.commands.exceptions;

/**
 * Thrown when a parameter is missing its argument.
 */
public class MissingArgumentException extends CommandException {

    /**
     * Constructor.
     *
     * @param message  The message to tell the command sender.
     */
    protected MissingArgumentException(CharSequence message) {
        super(message);
    }
}


text:
#ifndef HQ_JPEG_H
#define HQ_JPEG_H
#include "HQPrimitiveDataType.h"
#include "ImgByteStream.h"

struct jpeg_decompress_struct;
struct jpeg_error_mgr;

class JPEGImg
{
public:
	JPEGImg();
	~JPEGImg();

	int Load(ImgByteStream &stream, hq_ubyte8* & pixelDataOut,
			hq_uint32 &width,hq_uint32 &height,hq_short16 &bits ,
			hq_uint32 &imgSize, bool &isGreyscale);

	bool IsJPEG(ImgByteStream &stream);
	void Clear();
private:
	ImgByteStream *pStream;
	jpeg_decompress_struct * dobj;
	jpeg_error_mgr* jerr;
};

#endif


text:
package com.plnyyanks.frcnotebook.datatypes;

import android.util.Log;

import com.plnyyanks.frcnotebook.Constants;
import com.plnyyanks.frcnotebook.datafeed.USFIRSTParser;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Locale;

public class Event implements Comparable<Event>{

    private String  eventKey;
    private String eventName;

    private String shortName;
    private String eventLocation;
    private String eventStart;
    private String eventEnd;
    private int    eventYear;
    private Date   startDate,
                   endDate;
    private boolean official;

    public static final DateFormat     df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH),
                                       df2= new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH);
    public static final SimpleDateFormat weekFormatter = new SimpleDateFormat("w");

    private ArrayList<Match> quals,quarterFinals,semiFinals,finals;

    public Event(){

    }

    public Event(String eventKey, String eventName, String shortName, String eventLocation, String eventStart, String eventEnd, int eventYear,boolean official) {
        this.eventKey = eventKey;
        this.eventName = eventName;
        this.shortName = shortName;
        this.eventLocation = eventLocation;
        this.eventStart = eventStart;
        this.eventEnd = eventEnd;
        this.eventYear = eventYear;
        this.official = official;

        try {
            startDate = parseDate(eventStart);
            endDate = parseDate(eventEnd);
            endDate.setTime(endDate.getTime() + 24*60*60*1000);
        } catch (ParseException e) {
            startDate = new Date();
            endDate = new Date();
            Log.e(Constants.LOG_TAG, "Unable to parse event date. " + Arrays.toString(e.getStackTrace()));
        }
    }

    public String getEventKey() {
        return eventKey;
    }

    public void setEventKey(String eventKey) {
        this.eventKey = eventKey;
    }

    public String getEventName() {
        return eventName;
    }

    public void setEventName(String eventName) {
        this.eventName = eventName;
    }

    public String getShortName() {
        return shortName;
    }

    public void setShortName(String shortName) {
        this.shortName = shortName;
    }

    public String getEventLocation() {
        return eventLocation;
    }

    public void setEventLocation(String eventLocation) {
        this.eventLocation = eventLocation;
    }

    public String getEventStart() {
        return eventStart;
    }

    public Date getStartDate(){
        return startDate;
    }

    public void setEventStart(String eventStart) {
        this.eventStart = eventStart;
        try {
            startDate = parseDate(eventStart);
        } catch (ParseException e) {
            startDate = new Date();
            Log.e(Constants.LOG_TAG, "Unable to parse event date. " + Arrays.toString(e.getStackTrace()));
        }
    }

    public String getEventEnd() {
        return eventEnd;
    }

    public Date getEndDate(){
        return endDate;
    }

    public void setEventEnd(String eventEnd) {
        this.eventEnd = eventEnd;
        try {
            endDate = parseDate(eventEnd);
            endDate.setTime(endDate.getTime() + 24*60*60*1000);
        } catch (ParseException e) {
            endDate = new Date();
            Log.e(Constants.LOG_TAG, "Unable to parse event date. " + Arrays.toString(e.getStackTrace()));
        }
    }

    public boolean isHappeningNow(){
        Date now = new Date();
        return now.after(startDate) && now.before(endDate);
    }

    public int getEventYear() {
        return eventYear;
    }

    public void setEventYear(int eventYear) {
        this.eventYear = eventYear;
    }

    public void setOfficial(boolean official){
        this.official = official;
    }

    public boolean isOfficial(){
        return official;
    }

    public ArrayList<Match> getQuals() {
        if(quals == null)
            quals = new ArrayList<Match>();
        return quals;
    }

    public ArrayList<Match> getQuarterFinals() {
        if(quarterFinals==null)
            quarterFinals = new ArrayList<Match>();
        return quarterFinals;
    }

    public ArrayList<Match> getSemiFinals() {
        if(semiFinals==null)
            semiFinals = new ArrayList<Match>();
        return semiFinals;
    }

    public ArrayList<Match> getFinals() {
        if(finals==null)
            finals = new ArrayList<Match>();
        return finals;
    }

    public void sortMatches(ArrayList<Match> allMatches){
        quals = new ArrayList<Match>();
        quarterFinals = new ArrayList<Match>();
        semiFinals = new ArrayList<Match>();
        finals = new ArrayList<Match>();

        String matchKey;
        for(Match m:allMatches){
            matchKey = m.getMatchKey();
            if(matchKey.contains("_qm")){
                //qualification match
                quals.add(m);
            }
            if(matchKey.contains("_qf")){
                //quarter final match
                quarterFinals.add(m);
            }
            if(matchKey.contains("_sf")){
                //semifinal match
                semiFinals.add(m);
            }
            if(matchKey.contains("_f")){
                //final match
                finals.add(m);
            }
        }
        Collections.sort(quals);
        Collections.sort(quarterFinals);
        Collections.sort(semiFinals);
        Collections.sort(finals);
    }

    public int getCompetitionWeek(){
        if(startDate == null) return -1;
        int week = Integer.parseInt(weekFormatter.format(startDate))-8;
        return week<0?0:week;
    }

    public static int getCompetitionWeek(String dateString){
        try {
            Date eventDate = parseDate(dateString);
            int week = Integer.parseInt(weekFormatter.format(eventDate))-8;
            return week<0?0:week;
        } catch (ParseException e) {
            Log.e(Constants.LOG_TAG,"Unable to parse date string. "+Arrays.toString(e.getStackTrace()));
            return -1;
        }
    }

    private static Date parseDate(String dateString) throws ParseException {
        try {
            return df.parse(dateString);
        } catch (ParseException e) {
            Log.d(Constants.LOG_TAG,"TBAv1 date parse failed. Trying with v2 format...");
            return df2.parse(dateString);
        }
    }

    @Override
    public int compareTo(Event event) {
        if(startDate==null || event.getStartDate() == null)
            return 0;
        return startDate.compareTo(event.getStartDate());
    }
}


text:
#import <Foundation/Foundation.h>

/**
 @brief The JSON writer class.

 This uses SBJsonStreamWriter internally.

 @see @ref json2objc
 */

@interface MSBJsonWriter : NSObject

/**ß
 @brief The maximum recursing depth.

 Defaults to 32. If the input is nested deeper than this the input will be deemed to be
 malicious and the parser returns nil, signalling an error. ("Nested too deep".) You can
 turn off this security feature by setting the maxDepth value to 0.
 */
@property NSUInteger maxDepth;

/**
 @brief Return an error trace, or nil if there was no errors.

 Note that this method returns the trace of the last method that failed.
 You need to check the return value of the call you're making to figure out
 if the call actually failed, before you know call this method.
 */
@property (readonly, copy) NSString *error;

/**
 @brief Whether we are generating human-readable (multiline) JSON.

 Set whether or not to generate human-readable JSON. The default is NO, which produces
 JSON without any whitespace. (Except inside strings.) If set to YES, generates human-readable
 JSON with linebreaks after each array value and dictionary key/value pair, indented two
 spaces per nesting level.
 */
@property BOOL humanReadable;

/**
 @brief Whether or not to sort the dictionary keys in the output.

 If this is set to YES, the dictionary keys in the JSON output will be in sorted order.
 (This is useful if you need to compare two structures, for example.) The default is NO.
 */
@property BOOL sortKeys;

/**
 @brief An optional comparator to be used if sortKeys is YES.

 If this is nil, sorting will be done via @selector(compare:).
 */
@property (copy) NSComparator sortKeysComparator;

/**
 @brief Return JSON representation for the given object.

 Returns a string containing JSON representation of the passed in value, or nil on error.
 If nil is returned and @p error is not NULL, @p *error can be interrogated to find the cause of the error.

 @param value any instance that can be represented as JSON text.
 */
- (NSString*)stringWithObject:(id)value;

/**
 @brief Return JSON representation for the given object.

 Returns an NSData object containing JSON represented as UTF8 text, or nil on error.

 @param value any instance that can be represented as JSON text.
 */
- (NSData*)dataWithObject:(id)value;

/**
 @brief Return JSON representation (or fragment) for the given object.

 Returns a string containing JSON representation of the passed in value, or nil on error.
 If nil is returned and @p error is not NULL, @p *error can be interrogated to find the cause of the error.

 @param value any instance that can be represented as a JSON fragment
 @param error pointer to object to be populated with NSError on failure

 */- (NSString*)stringWithObject:(id)value
                           error:(NSError**)error;

@end


text:
#include "tommath_private.h"
#ifdef BN_MP_ADD_C
/* LibTomMath, multiple-precision integer library -- Tom St Denis
 *
 * LibTomMath is a library that provides multiple-precision
 * integer arithmetic as well as number theoretic functionality.
 *
 * The library was designed directly after the MPI library by
 * Michael Fromberger but has been written from scratch with
 * additional optimizations in place.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 */

/* high level addition (handles signs) */
int mp_add(const mp_int *a, const mp_int *b, mp_int *c)
{
   int     sa, sb, res;

   /* get sign of both inputs */
   sa = a->sign;
   sb = b->sign;

   /* handle two cases, not four */
   if (sa == sb) {
      /* both positive or both negative */
      /* add their magnitudes, copy the sign */
      c->sign = sa;
      res = s_mp_add(a, b, c);
   } else {
      /* one positive, the other negative */
      /* subtract the one with the greater magnitude from */
      /* the one of the lesser magnitude.  The result gets */
      /* the sign of the one with the greater magnitude. */
      if (mp_cmp_mag(a, b) == MP_LT) {
         c->sign = sb;
         res = s_mp_sub(b, a, c);
      } else {
         c->sign = sa;
         res = s_mp_sub(a, b, c);
      }
   }
   return res;
}

#endif

/* ref:         HEAD -> develop */
/* git commit:  8b9f98baa16b21e1612ac6746273febb74150a6f */
/* commit time: 2018-09-23 21:37:58 +0200 */


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html401/strict.dtd">

  <title>MudWalker Reference: Windows: Find</title>
  <meta name="Keywords" content="MudWalker,find,find window,search,search window,grep,regexp,regex,jump,goto,line,line number">

Find Window

I rather hope that most of the controls here are self-explanatory. Some that might not be:

Regexp: Specifies that the search will be performed using regular expression syntax. See #Regular Expressions

In selection only: Applies to the Replace All function.

Please inform me if this section needs more explanation.

  Table of Contents | Window Reference