text:
using System.Collections;
using System.Windows;
using System.Windows.Documents;

namespace Waf.BookLibrary.Reporting.Presentation.Controls;

public class ItemsElement : Section
{
    public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register(nameof(ItemsSource), typeof(IEnumerable), typeof(ItemsElement), new UIPropertyMetadata(null, ItemsSourceChangedHandler));

    public static readonly DependencyProperty ItemTemplateProperty = DependencyProperty.Register(nameof(ItemTemplate), typeof(DataTemplate), typeof(ItemsElement), new UIPropertyMetadata(null));

    public IEnumerable ItemsSource
    {
        get => (IEnumerable)GetValue(ItemsSourceProperty);
        set => SetValue(ItemsSourceProperty, value);
    }

    public DataTemplate ItemTemplate
    {
        get => (DataTemplate)GetValue(ItemTemplateProperty);
        set => SetValue(ItemTemplateProperty, value);
    }

    private void UpdateContent()
    {
        if (ItemsSource != null)
        {
            if (ItemTemplate == null) throw new InvalidOperationException("When ItemsSource is used then the ItemTemplate must not be null.");
            var blocks = new List<Block>();
            foreach (object? item in ItemsSource)
            {
                Block? block = null;
                if (ItemTemplate.LoadContent() is ContentElement contentElement) block = contentElement.Content as Block;
                if (block == null) throw new InvalidOperationException("The ItemTemplate must define: DataTemplate > ContentElement > Block element.");
                block.DataContext = item;
                blocks.Add(block);
            }
            Blocks.AddRange(blocks);
        }
    }

    private static void ItemsSourceChangedHandler(DependencyObject d, DependencyPropertyChangedEventArgs e) => ((ItemsElement)d).UpdateContent();
}


text:
		<button class="button" ng-click="send();cancel()" ng-if="msg != ''">

		</button>
		<button class="button" ng-click="cancel()">

		</button>

redpajama_set_name: RedPajamaGithub


text:
/*
 * File:   Surelog.h
 * Author: alain
 *
 * Created on November 21, 2019, 10:09 PM
 */

#ifndef SURELOG_SURELOG_H
#define SURELOG_SURELOG_H
#pragma once

// UHDM
#include <uhdm/sv_vpi_user.h>

namespace SURELOG {

class CommandLineParser;
class Design;
struct scompiler;
class AstListener;

// Create a compiler session based on the command line options
scompiler* start_compiler(CommandLineParser* clp);

// Surelog internal design representation and AST access
Design* get_design(scompiler* compiler);

// UHDM Database design access (use UHDM SystemVerilog Object Model schema to
// navigate) see: third_party/Verilog_Object_Model.pdf
//      third_party/UHDM/include/
//      third_party/UHDM/headers/
vpiHandle get_uhdm_design(scompiler* compiler);

// Terminate the compiler session, cleanup internal datastructures,
// Purges UHDM and VPI from memory,
// this invalidates any UHDM/VPI pointers the client application might still
// use!
void shutdown_compiler(scompiler* compiler);

void walk_ast(scompiler* compiler, AstListener* listener);

}  // namespace SURELOG

#endif  // SURELOG_SURELOG_H


text:
package com.treode.cps.buffer

import java.io.{EOFException, InputStream, OutputStream}
import java.lang.{Double => JDouble, Float => JFloat}
import java.nio.ByteBuffer
import java.nio.charset.Charset

trait ReadableStream {

  def readByte(): Byte

  def readBytes (v: Array [Byte]): Unit = {
    var i = 0
    while (i < v.length) {
      v (i) =  readByte()
      i += 1
    }}

  def readBytes (v: ByteBuffer): Unit = {
    while (v.remaining > 0) (v.put (readByte()))
  }

  def readBytes (v: ByteBuffer, off: Int, len: Int): Unit = {
    val end = off + len
    var i = off
    while (i < end) {
      v.put (readByte())
      i += 1
    }}

  private [this] def readi (shift: Int): Int =
    (readByte.toInt & 0xFF) << shift

  def readShort(): Short =
    (readi (8) | readi (0)).toShort

  def readInt(): Int =
    readi (24) | readi (16) | readi (8) | readi (0)

  private def readl (shift: Int): Long =
    (readByte.toLong & 0xFF) << shift

  def readLong(): Long =
    readl (56) | readl (48) | readl (40) | readl (32) | readl (24) | readl (16) | readl (8) | readl (0)

  def readFloat(): Float = JFloat.intBitsToFloat (readInt())

  def readDouble(): Double = JDouble.longBitsToDouble (readLong())
}

trait ReadableStreamEnvoy {

  protected val stream: ReadableStream

  def readByte() = stream.readByte()
  def readBytes (v: Array [Byte]) = stream.readBytes (v)
  def readBytes (v: ByteBuffer) = stream.readBytes (v)
  def readBytes (v: ByteBuffer, off: Int, len: Int) = stream.readBytes (v, off, len)
  def readShort() = stream.readShort()
  def readInt() = stream.readInt()
  def readLong() = stream.readLong()
  def readFloat() = stream.readFloat()
  def readDouble() = stream.readDouble()
}

private class JavaReadableStream (in: InputStream) extends ReadableStream {

  def readByte(): Byte =
    in.read() match {
      case x if x < 0 => throw new EOFException
      case x => x.toByte;
    }}

object ReadableStream {

  implicit def apply (in: InputStream): ReadableStream = new JavaReadableStream (in)
}

trait WritableStream {

  def writeByte (v: Byte): Unit

  def writeBytes (v: Array [Byte]): Unit = {
    var i = 0
    while (i < v.length) {
      writeByte (v (i))
      i += 1
    }}

  def writeBytes (v: ByteBuffer): Unit = {
    while (v.remaining > 0) (writeByte (v.get))
  }

  def writeShort (v: Short): Unit = {
    writeByte ((v >> 8).toByte)
    writeByte (v.toByte)
  }

  def writeInt (v: Int): Unit = {
    writeByte ((v >> 24).toByte)
    writeByte ((v >> 16).toByte)
    writeByte ((v >> 8).toByte)
    writeByte (v.toByte)
  }

  def writeLong (v: Long): Unit = {
    writeByte ((v >> 56).toByte)
    writeByte ((v >> 48).toByte)
    writeByte ((v >> 40).toByte)
    writeByte ((v >> 32).toByte)
    writeByte ((v >> 24).toByte)
    writeByte ((v >> 16).toByte)
    writeByte ((v >> 8).toByte)
    writeByte (v.toByte)
  }

  def writeFloat (v: Float): Unit =
    writeInt (JFloat.floatToRawIntBits (v))

  def writeDouble (v: Double): Unit =
    writeLong (JDouble.doubleToRawLongBits (v))
}

trait WritableStreamEnvoy extends WritableStream {

  protected val stream: WritableStream

  def writeByte (v: Byte) = stream.writeByte (v)
  override def writeBytes (v: Array [Byte]) = stream.writeBytes (v)
  override def writeBytes (v: ByteBuffer) = stream.writeBytes (v)
  override def writeShort (v: Short) = stream.writeShort (v)
  override def writeInt (v: Int) = stream.writeInt (v)
  override def writeLong (v: Long) = stream.writeLong (v)
  override def writeFloat (v: Float) = stream.writeFloat (v)
  override def writeDouble (v: Double) = stream.writeDouble (v)
}

private class JavaWritableStream (out: OutputStream) extends WritableStream {

  def writeByte (value : Byte) = out.write (value)
}

object WritableStream {

  implicit def apply (out: OutputStream): WritableStream = new JavaWritableStream (out)
}


text:
<?php

namespace yiiunit\framework\log;

use Yii;
use yii\helpers\FileHelper;
use yii\log\Dispatcher;
use yii\log\FileTarget;
use yii\log\Logger;
use yiiunit\TestCase;

/**
 * @group log
 */
class FileTargetTest extends TestCase
{
    protected function setUp()
    {
        parent::setUp();
        $this->mockApplication();
    }

    /**
     * Tests that log directory isn't created during init process
     * @see https://github.com/yiisoft/yii2/issues/15662
     */
    public function testInit()
    {
        $logFile = Yii::getAlias('@yiiunit/runtime/log/filetargettest.log');
        FileHelper::removeDirectory(dirname($logFile));
        new FileTarget([
            'logFile' => Yii::getAlias('@yiiunit/runtime/log/filetargettest.log'),
        ]);
        $this->assertFileNotExists(
            dirname($logFile),
            'Log directory should not be created during init process'
        );
    }

    public function testRotate()
    {
        $logFile = Yii::getAlias('@yiiunit/runtime/log/filetargettest.log');
        FileHelper::removeDirectory(dirname($logFile));
        mkdir(dirname($logFile), 0777, true);

        $logger = new Logger();
        $dispatcher = new Dispatcher([
            'logger' => $logger,
            'targets' => [
                'file' => [
                    'class' => 'yii\log\FileTarget',
                    'logFile' => $logFile,
                    'levels' => ['warning'],
                    'maxFileSize' => 1024, // 1 MB
                    'maxLogFiles' => 1, // one file for rotation and one normal log file
                    'logVars' => [],
                ],
            ],
        ]);

        // one file

        $logger->log(str_repeat('x', 1024), Logger::LEVEL_WARNING);
        $logger->flush(true);

        clearstatcache();

        $this->assertFileExists($logFile);
        $this->assertFileNotExists($logFile . '.1');
        $this->assertFileNotExists($logFile . '.2');
        $this->assertFileNotExists($logFile . '.3');
        $this->assertFileNotExists($logFile . '.4');

        // exceed max size
        for ($i = 0; $i < 1024; $i++) {
            $logger->log(str_repeat('x', 1024), Logger::LEVEL_WARNING);
        }
        $logger->flush(true);

        // first rotate

        $logger->log(str_repeat('x', 1024), Logger::LEVEL_WARNING);
        $logger->flush(true);

        clearstatcache();

        $this->assertFileExists($logFile);
        $this->assertFileExists($logFile . '.1');
        $this->assertFileNotExists($logFile . '.2');
        $this->assertFileNotExists($logFile . '.3');
        $this->assertFileNotExists($logFile . '.4');

        // second rotate

        for ($i = 0; $i < 1024; $i++) {
            $logger->log(str_repeat('x', 1024), Logger::LEVEL_WARNING);
        }
        $logger->flush(true);

        clearstatcache();

        $this->assertFileExists($logFile);
        $this->assertFileExists($logFile . '.1');
        $this->assertFileNotExists($logFile . '.2');
        $this->assertFileNotExists($logFile . '.3');
        $this->assertFileNotExists($logFile . '.4');
    }
}


text:
package com.spryrocks.android.modules.ui.mvvm.connectedServices;

import com.spryrocks.android.modules.ui.lifecycle.LifecycleListener;

import java.util.Set;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class ConnectedServicesRegistration extends LifecycleListener implements IConnectedServices, IConnectedServicesManager {
    private IConnectedServicesManager connectedServicesManager;

    private IConnectedServiceReceiver connectedServiceReceiver;
    private IConnectedServiceCallbacksReceiver connectedServicesCallbacksReceiver;

    public void setConnectedServicesOwner(IConnectedServicesOwner connectedServicesOwner) {
        IConnectedServices connectedServices = connectedServicesOwner.getConnectedServices();
        connectedServicesManager = (IConnectedServicesManager) connectedServices;
        connectedServiceReceiver = connectedServices;
        connectedServicesCallbacksReceiver = connectedServices;
    }

    @Override
    public <TService extends IConnectedService, TServiceImpl extends TService> TServiceImpl connectService(Class<TService> serviceClass, TServiceImpl service) {
        connectedServicesManager.connectService(serviceClass, service);

        return service;
    }

    @Override
    public <TService extends IConnectedService> void disconnectService(Class<TService> serviceClass) {
        connectedServicesManager.disconnectService(serviceClass);
    }

    @Override
    public void clearServices() {
        connectedServicesManager.clearServices();
    }

    @Nullable
    @Override
    public <TService extends IConnectedService> TService getService(@NonNull Class<TService> serviceClass) {
        return connectedServiceReceiver.getService(serviceClass);
    }

    @Override
    public void onDestroy() {
        clearServices();
    }

    @NonNull
    @Override
    public <TCallbacks extends IConnectedServiceCallbacks> Set<TCallbacks> getCallbacks(@NonNull Class<TCallbacks> tCallbacksClass) {
        return connectedServicesCallbacksReceiver.getCallbacks(tCallbacksClass);
    }
}


text:
#ifndef ENTITY_H
#define ENTITY_H

#include "aoe_object.h"

class State;

/** Entity is the main interface for every tangible object.
 */
class Entity : virtual public AOEObject {
protected:
	State* attachedState;

public:
	Entity() : attachedState(NULL) {}

	Entity(State* newAttachedState) : attachedState(newAttachedState) {
		xassert(attachedState, "Object %p is not attached to any state.", (AOEObject*)this);
	}

	/** Gets the container state of this object.
	 * Under normal operation, it is always valid, never NULL and does not need to be checked.
	 * Remember that update() checks for nullity before calling updateObject and other update passes, so checking the state pointer is never useful.
	 */
	State* state() {
		return attachedState;
	}

	void setAttachedState(State* newState);

	/* AOEObject */

	AuroraEngine* engine();
	VFS::File* source();
	virtual ~Entity() { }
};
#endif


text:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Muscularity.Core.Shared;

namespace Muscularity.Web.Infrastructure.ExceptionHandling
{
    /// <summary>
    /// A filter factory that will create the <see cref="ResourceNotFoundException"/>.
    /// </summary>
    public class ResourceNotFoundExceptionFilterFactory : IFilterFactory
    {
        public bool IsReusable => true;

        public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
        {
            var hostingEnvironment = (IWebHostEnvironment)serviceProvider.GetService(typeof(IWebHostEnvironment));
            var logger = (ILogger<ResourceNotFoundExceptionFilter>)serviceProvider.GetService(typeof(ILogger<ResourceNotFoundExceptionFilter>));

            return new ResourceNotFoundExceptionFilter(hostingEnvironment, logger);
        }
    }
}


text:
package video

import (
	"context"
	"time"

	"go-common/app/interface/main/favorite/conf"
	xredis "go-common/library/cache/redis"
)

// Dao defeine fav Dao
type Dao struct {
	redisPool        *xredis.Pool
	expireRedis      int
	coverExpireRedis int
}

// New return fav dao
func New(c *conf.Config) (d *Dao) {
	d = &Dao{
		redisPool:        xredis.NewPool(c.Redis.Config),
		expireRedis:      int(time.Duration(c.Redis.Expire) / time.Second),
		coverExpireRedis: int(time.Duration(c.Redis.CoverExpire) / time.Second),
	}
	return
}

// Close close all connection
func (d *Dao) Close() {
	if d.redisPool != nil {
		d.redisPool.Close()
	}
}

// Ping check connection used in dao
func (d *Dao) Ping(c context.Context) (err error) {
	return d.pingRedis(c)
}


text:
'use strict';
module.exports = (markRepository, firmRepository, countryRepository, errors) => {
    const BaseService = require('./base');
    const config = require('../config.json');
    const Promise = require("bluebird");
    Object.setPrototypeOf(MarkService.prototype, BaseService.prototype);

    function MarkService(markRepository, errors) {
        BaseService.call(this, markRepository, errors);

        let self = this;

        self.create = create;
        self.update = update;
        self.readChunk = readChunk;
        self.read = read;
        function read(id) {
            return new Promise((resolve, reject) => {
                markRepository.find({
                    where: {
                        id: id
                    },
                    include: [
                        {
                            model: countryRepository,
                            attributes: ["COUNTRY_NAME"]
                        }, {
                            model: firmRepository,
                            attributes: ["FIRM_NAME"]
                        }
                    ]
                }).then((result) => {
                    result["COUNTRY"] = result["country.COUNTRY_NAME"];
                    result["FIRM"] = result["firm.FIRM_NAME"];
                    delete  result["country.COUNTRY_NAME"];
                    delete  result["firm.FIRM_NAME"];
                    resolve({"data": result})
                }).catch(reject);
            });
        }

        function readChunk(options) {
            return new Promise((resolve, reject) => {
                options = Object.assign({}, config.defaults.readChunk, options);

                var limit = Number(options.length);
                var offset = Number(options.start);
                var searchKey = '%' + options.search.value + '%';
                var orderColumnNumber = Number(options.order[0].column);
                var orderColumn;
                if (options.columns)
                    orderColumn = options.columns[orderColumnNumber].data;
                else
                    orderColumn = "MARK_NAME";
                markRepository.findAndCountAll({
                        limit: limit,
                        offset: offset,
                        order: [[orderColumn, options.order[0].dir.toUpperCase()]],
                        raw: true,

                        where: {
                            $or: [
                                {
                                    MARK_NAME: {
                                        $like: searchKey
                                    }
                                }

                            ]
                        },
                        include: [
                            {
                                model: countryRepository,
                                attributes: ["COUNTRY_NAME"]
                            }, {
                                model: firmRepository,
                                attributes: ["FIRM_NAME"]
                            }
                        ]
                    }
                ).then((result) => {
                    for (var i = 0; i < result.rows.length; i++) {
                        result.rows[i]["COUNTRY"] = result.rows[i]["country.COUNTRY_NAME"];
                        result.rows[i]["FIRM"] = result.rows[i]["firm.FIRM_NAME"];
                        delete  result.rows[i]["country.COUNTRY_NAME"];
                        delete  result.rows[i]["firm.FIRM_NAME"];
                    }
                    let records = options.search.value.length ? result.rows.length : result.count;

                    resolve({
                        "data": result.rows,
                        "options": [],
                        "files": [],
                        "draw": options.draw,
                        "recordsTotal": result.count,
                        "recordsFiltered": records
                    });
                }).catch(reject);
            });
        }

        function create(req) {
            let data = req.data[0];
               return Promise.all([
                    self.baseCreate(data),
                    firmRepository.findById(data.firm),
                    countryRepository.findById(data.country)
                ]).spread((mark, firm, country) => {
                   if (!mark || !firm) {
                       throw `Error while creating object. ${mark ? 'Firm' : 'Mark'} id doesen\'t not exist`;
                   }
                    return new Promise.all([
                        firm.addMark(mark),
                        country.addMark(mark),
                        mark
                    ]);
                }).spread((firm, country, mark) =>  self.read(mark.id));
        }

        function grant(firmId, countryId) {

        }

        function update(req) {
            let keys = Object.keys(req.body.data);
            let key = Number.parseInt(keys[0]);
            let data = req.body.data[key];

               return Promise.all([
                    self.baseUpdate(req.params.id || data.id, data),
                    firmRepository.findById(data.firm),
                    countryRepository.findById(data.country)
                ]).spread((mark, firm, country) => {
                    if (mark && firm && country)
                        return new Promise.all([
                            mark.data,
                            firm.addMark(mark.data),
                            country.addMark(mark.data)
                        ]);
                    else return [mark.data]
                }).spread((mark, firm, country) => self.read(mark.id))
        }

    }

    return new MarkService(markRepository, errors);
};


text:
{% extends 'base.html' %}

{% block content %}
{% load staticfiles %}
{% load crispy_forms_tags %}
<link href="/static/index.css" rel="stylesheet" type="text/css"/>

Crike -- 试题管理

<button class="btn btn-success" onclick="showExamform();"></button>

<form id='newexamform' style="display: none" method="post" enctype="multipart/form-data" action="/admin/exams/">
  {% csrf_token %}

新增:Click to input a name&nbsp&nbsp*
    <button onclick="saveExam(event,this);" class="btn btn-success" style="float:right;display=none">
      </button>

词汇测验

    <input type="checkbox" name="withtrans" checked>加入句子翻译题

新增

点击选择课本

选择题

阅读理解

</form>

{% for exam in exams %}
<form id='examform' method="post" enctype="multipart/form-data" action="/admin/exams/">
  {% csrf_token %}
  <input name='id' value="{{exam.id}}" hidden="true">

    {{exam.name}}
    &nbsp&nbsp*
    <button class="btn btn-danger" style="float:right;" onclick="deleteExam(event,this);">
      </button>
    <button onclick="saveExam(event, this);" class="btn btn-success" style="float:right;display:none">
      </button>

词汇测验

      {% if exam.withtrans %}
      <input type="checkbox" onclick="checkWithTrans(this)" name="withtrans" checked>加入句子翻译题
      {% else %}
      <input type="checkbox" onclick="checkWithTrans(this)" name="withtrans">加入句子翻译题
      {% endif %}

      {% for lesson in exam.lessons|dictsort:"name" %}

<input name="addlessons" value='{{lesson.id}}' hidden="true">{{lesson.book.name}}

{{lesson.name}}

sum:{{lesson.words|length}}

      {% endfor %}

新增

点击选择课本

选择题

    {% for question in exam.choices %}
    {{forloop.counter}}.

{{question.question|linebreaksbr}}

        <input type="radio" name="answer{{forloop.counter}}" value=1 {% if question.rightindex == 1 %}checked=true{% endif %}>

A
{{question.answers.0|linebreaksbr}}

        <input type="radio" name="answer{{forloop.counter}}" value=2 {% if question.rightindex == 2 %}checked=true{% endif %}>

B
{{question.answers.1|linebreaksbr}}

        <input type="radio" name="answer{{forloop.counter}}" value=3 {% if question.rightindex == 3 %}checked=true{% endif %}>

C
{{question.answers.2|linebreaksbr}}

        <input type="radio" name="answer{{forloop.counter}}" value=4 {% if question.rightindex == 4 %}checked=true{% endif %}>

D
{{question.answers.3|linebreaksbr}}

    {% endfor %}

阅读理解

    {% for reading in exam.readings %}
    {{forloop.counter}}.

Article:

{{reading.name}}

{{reading.article|linebreaksbr}}

Questions:

      {% for question in reading.questions %}

{{question.question|linebreaksbr}}

          <input type="radio" name="answer{{forloop.parentloop.counter}}{{forloop.counter}}" value=1 {% if question.rightindex == 1 %}checked=true{% endif %}>

A
{{question.answers.0|linebreaksbr}}

          <input type="radio" name="answer{{forloop.parentloop.counter}}{{forloop.counter}}" value=2 {% if question.rightindex == 2 %}checked=true{% endif %}>

B
{{question.answers.1|linebreaksbr}}

          <input type="radio" name="answer{{forloop.parentloop.counter}}{{forloop.counter}}" value=3 {% if question.rightindex == 3 %}checked=true{% endif %}>

C
{{question.answers.2|linebreaksbr}}

          <input type="radio" name="answer{{forloop.parentloop.counter}}{{forloop.counter}}" value=4 {% if question.rightindex == 4 %}checked=true{% endif %}>

D
{{question.answers.3|linebreaksbr}}

      {% endfor %}

    {% endfor %}

</form>
{% endfor %}

{% endblock %}

{% block body_footer %}

{% endblock %}


text:
<TITLE>Chapter 12</TITLE>

<FORM METHOD=POST NAME="spreadsheet">

</FORM>

<FORM METHOD=POST>

Field Name

Expression

<INPUT TYPE=text SIZE=10 NAME="expField"
   onChange="var exp = GetCookie(this.value); this.form.expression.value =
(exp == null) ? '' : exp;">

<INPUT TYPE=text SIZE=50 NAME="expression">

<INPUT TYPE=button VALUE="Apply"
onClick="saveExp(this.form);">

<INPUT TYPE=button VALUE="Delete"
onClick="deleteExp(this.form);">

</FORM>


text:
@layout('admin.qrcode.template')

	 {{ __('content.qrcode') }} · {{ __('content.add_new_word') }}

@section('qrcode')

		@foreach($fields as $column => $value)

			{{ Utilites::html_form_build($fields[$column]['type'], $fields[$column]['data'], View::make('admin.assets.form_pattern'), __('forms.'.$column.'_word'), $fields[$column]['attributes']) }}

		@endforeach

			{{ __('qrcode.annotation') }}

					<button
						id="ajax_save_button"
						class="btn"
						type="button"
						disabled="disabled"
						data-post="{{ e($json_save) }}"
						data-link="{{ action('admin.qrcode.action@save') }}"
						data-prevent-follow="true"
						data-out-popup="true"
						data-out="status"
					>
						 {{ __('forms.save_word') }}
					</button>

@endsection


text:
using System;
using System.Collections.Generic;
using TripleTexDotNet.Classes;
using TripleTexDotNet.Interfaces;

namespace TripleTexDotNet.Services
{
    public class ProductService : IProductService
    {
        private readonly IJsonService _service;

        public ProductService(IJsonService service)
        {
            _service = service;
        }

        public IEnumerable<Product> SearchForProducts(string searchString)
        {
            return _service.Call<IEnumerable<Product>>("Product.searchForProducts", -1, searchString);
        }

        public void SaveProduct()
        {
            throw new NotImplementedException();
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using XenAdmin.Controls;
using XenAdmin.Core;
using XenAdmin.Diagnostics.Checks;
using XenAdmin.Diagnostics.Hotfixing;
using XenAdmin.Wizards.PatchingWizard;
using XenAPI;
using System.Linq;

namespace XenAdmin.Wizards.RollingUpgradeWizard
{
    public partial class RollingUpgradeWizardPrecheckPage : PatchingWizard_PrecheckPage
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public RollingUpgradeWizardPrecheckPage()
        {
            InitializeComponent();
            this.Dock = DockStyle.Fill;
        }

        private void AddEventHandlersToMasters()
        {
            foreach (Host master in SelectedMasters)
            {
                master.Connection.ConnectionStateChanged += connection_ConnectionChanged;
                master.Connection.CachePopulated += connection_ConnectionChanged;
            }
        }

        private void RemoveEventHandlersToMasters()
        {
            foreach (Host master in SelectedMasters)
            {
                master.Connection.ConnectionStateChanged -= connection_ConnectionChanged;
                master.Connection.CachePopulated -= connection_ConnectionChanged;
            }
        }

        private void connection_ConnectionChanged(object sender, EventArgs eventArgs)
        {
            Program.Invoke(Program.MainWindow, RefreshRechecks);
        }

        public override void PageLoaded(PageLoadedDirection direction)
        {
            if (direction == PageLoadedDirection.Back)
            {
                RefreshRechecks();
                return;
            }
            var selectedMasters = new List<Host>(SelectedMasters);
            ManualUpgrade = ManualModeSelected;
            RemoveEventHandlersToMasters();
            SelectedServers.Clear();
            foreach (Host selectedMaster in selectedMasters)
            {
                Host master = selectedMaster;
                if (master != null)
                {
                    Pool pool = Helpers.GetPoolOfOne(master.Connection);
                    if (pool != null)
                        SelectedServers.AddRange(pool.HostsToUpgrade);
                    else
                        SelectedServers.Add(master);
                }
            }
            AddEventHandlersToMasters();
            labelPrechecksFirstLine.Text = Messages.ROLLINGUPGRADE_PRECHECKS;
            RefreshRechecks();
            return;
        }

        public override void PageLeave(PageLoadedDirection direction, ref bool cancel)
        {
            RemoveEventHandlersToMasters();
            base.PageLeave(direction, ref cancel);
        }

        public override void PageCancelled()
        {
            RemoveEventHandlersToMasters();
            base.PageCancelled();
        }

        public override string PageTitle
        {
            get
            {
                return Messages.UPGRADE_PRECHECKS_TITLE;
            }
        }

        public override string Text
        {
            get
            {
                return Messages.UPGRADE_PRECHECKS_TEXT;
            }
        }

        public override string HelpID
        {
            get { return "Upgradeprechecks"; }
        }

        protected override List<KeyValuePair<string, List<Check>>> GenerateChecks(Pool_patch patch)
        {
            List<KeyValuePair<string, List<Check>>> checks = new List<KeyValuePair<string, List<Check>>>();

            //HostMaintenanceModeCheck checks
            checks.Add(new KeyValuePair<string, List<Check>>(Messages.CHECKING_HOST_LIVENESS_STATUS, new List<Check>()));
            List<Check> checkGroup = checks[checks.Count - 1].Value;
            foreach (Host host in SelectedServers)
            {
                checkGroup.Add(new HostMaintenanceModeCheck(host));
            }

            //HA checks
            checks.Add(new KeyValuePair<string, List<Check>>(Messages.CHECKING_HA_STATUS, new List<Check>()));
            checkGroup = checks[checks.Count - 1].Value;
            foreach (Pool pool in SelectedPools)
            {
                Host host = pool.Connection.Resolve(pool.master);

                if(host == null)
                    continue;

                checkGroup.Add(new HAOffCheck(host));
            }

            //Checking can evacuate host
            checks.Add(new KeyValuePair<string, List<Check>>(Messages.CHECKING_CANEVACUATE_STATUS, new List<Check>()));
            checkGroup = checks[checks.Count - 1].Value;
            foreach (Host host in SelectedServers)
            {
                checkGroup.Add(new AssertCanEvacuateUpgradeCheck(host));
            }

            //PBDsPluggedCheck
            checks.Add(new KeyValuePair<string, List<Check>>(Messages.CHECKING_STORAGE_CONNECTIONS_STATUS, new List<Check>()));
            checkGroup = checks[checks.Count - 1].Value;
            foreach (Host host in SelectedServers)
            {
                checkGroup.Add(new PBDsPluggedCheck(host));
            }

            //HotfixesCheck required for MNR, Cowley, Boston and Sanibel
            bool titleAdded = false;
            foreach (var host in SelectedServers)
            {
                if (new HotfixFactory().IsHotfixRequired(host) && !ManualUpgrade)
                {
                    if (!titleAdded)
                    {
                        checks.Add(new KeyValuePair<string, List<Check>>(Messages.CHECKING_UPGRADE_HOTFIX_STATUS,
                                                                         new List<Check>()));
                        checkGroup = checks[checks.Count - 1].Value;
                        titleAdded = true;
                    }
                    checkGroup.Add(new HostHasHotfixCheck(host));
                }
            }

            //iSL (StorageLink) check - CA-223486: only for pre-Creedence
            var preCreedenceServers = SelectedServers.Where(h => !Helpers.CreedenceOrGreater(h)).ToList();
            if (preCreedenceServers.Any())
            {
                checks.Add(new KeyValuePair<string, List<Check>>(Messages.CHECKING_STORAGELINK_STATUS, new List<Check>()));
                checkGroup = checks[checks.Count - 1].Value;
                foreach (Host host in preCreedenceServers)
                {
                    checkGroup.Add(new HostHasUnsupportedStorageLinkSRCheck(host));
                }
            }

            //SafeToUpgradeCheck - in automatic mode only
            if (!ManualUpgrade)
            {
                checks.Add(new KeyValuePair<string, List<Check>>(Messages.CHECKING_SAFE_TO_UPGRADE, new List<Check>()));
                checkGroup = checks[checks.Count - 1].Value;

                foreach (Host host in SelectedServers)
                {
                    checkGroup.Add(new SafeToUpgradeCheck(host));
                }
            }

            return checks;

        }

        public IEnumerable<Host> SelectedMasters { private get; set; }
        public bool ManualModeSelected { private get; set; }
    }
}


text:
namespace SwedbankSharp.JsonSchemas
{
    public class QuickBalanceSubscriptionObject
    {
        public string SubscriptionId { get; set; }
    }
}


text:
package play.utils.meta.form;

import play.api.i18n.Lang;
import play.twirl.api.Html;
import play.data.Form.Field;
import play.utils.meta.FieldMetadata;
import scala.Symbol;
import scala.Tuple2;
import views.html.helper.FieldConstructor;

public class NumberWidget extends FormFieldWidget {

	public NumberWidget(FieldMetadata fieldMetadata) {
		super(fieldMetadata);
	}

	@Override
	protected Html render(Field formField, Tuple2<Symbol, Object>[] args, FieldConstructor fieldConstructor, Lang lang) {
		return play.utils.meta.form.html.numberWidget.render(formField, args, fieldConstructor, lang);
	}

}


text:
package org.assertj.core.internal.longarrays;

import static org.assertj.core.error.ShouldNotBeEmpty.shouldNotBeEmpty;
import static org.assertj.core.test.LongArrays.*;
import static org.assertj.core.test.TestData.someInfo;
import static org.assertj.core.test.TestFailures.failBecauseExpectedAssertionErrorWasNotThrown;
import static org.assertj.core.util.FailureMessages.actualIsNull;

import static org.mockito.Mockito.verify;

import org.assertj.core.api.AssertionInfo;
import org.assertj.core.internal.LongArrays;
import org.assertj.core.internal.LongArraysBaseTest;
import org.junit.Test;

/**
 * Tests for <code>{@link LongArrays#assertNotEmpty(AssertionInfo, long[])}</code>.
 *
 * @author Alex Ruiz
 * @author Joel Costigliola
 */
public class LongArrays_assertNotEmpty_Test extends LongArraysBaseTest {

  @Test
  public void should_fail_if_actual_is_null() {
    thrown.expectAssertionError(actualIsNull());
    arrays.assertNotEmpty(someInfo(), null);
  }

  @Test
  public void should_fail_if_actual_is_empty() {
    AssertionInfo info = someInfo();
    try {
      arrays.assertNotEmpty(info, emptyArray());
    } catch (AssertionError e) {
      verify(failures).failure(info, shouldNotBeEmpty());
      return;
    }
    failBecauseExpectedAssertionErrorWasNotThrown();
  }

  @Test
  public void should_pass_if_actual_is_not_empty() {
    arrays.assertNotEmpty(someInfo(), arrayOf(8L));
  }
}


text:
import os
from datetime import timedelta

# starterbot's ID as an environment variable
BOT_ID = os.environ.get("BOT_ID")
SLACK_BOT_TOKEN = os.environ.get('SLACK_BOT_TOKEN')

# constants
AT_BOT = "<@" + BOT_ID + ">"
BOT_NAME = 'antibot'
DEFAULT_DELETE_DELAY = 20.0 # Default is 180 seconds
DB_NAME = "counter.db"

# Skirmish Constants
CHECKIN_FREQ_DAYS = 7 # Number of days between check-ins
RELAPSE_POINTS = -5
PER_DAY_POINTS = 1
BUFFER_DAYS_TEAM = timedelta(days=7)
SKIRMISH_NOADMIN_FUNCTIONS = ["players", "details"]


text:
REST framework includes an abstraction for dealing with `ViewSets`, that allows the developer to concentrate on modeling the state and interactions of the API, and leave the URL construction to be handled automatically, based on common conventions.

`ViewSet` classes are almost the same thing as `View` classes, except that they provide operations such as `read`, or `update`, and not method handlers such as `get` or `put`.

A `ViewSet` class is only bound to a set of method handlers at the last moment, when it is instantiated into a set of views, typically by using a `Router` class which handles the complexities of defining the URL conf for you.

## Refactoring to use ViewSets

Let's take our current set of views, and refactor them into view sets.

First of all let's refactor our `UserList` and `UserDetail` views into a single `UserViewSet`.  We can remove the two views, and replace them with a single class:

    from rest_framework import viewsets

    class UserViewSet(viewsets.ReadOnlyModelViewSet):
        """
        This viewset automatically provides `list` and `detail` actions.
        """
        queryset = User.objects.all()
        serializer_class = UserSerializer

Here we've used the `ReadOnlyModelViewSet` class to automatically provide the default 'read-only' operations.  We're still setting the `queryset` and `serializer_class` attributes exactly as we did when we were using regular views, but we no longer need to provide the same information to two separate classes.

Next we're going to replace the `SnippetList`, `SnippetDetail` and `SnippetHighlight` view classes.  We can remove the three views, and again replace them with a single class.

    from rest_framework.decorators import detail_route
    from rest_framework.response import Response

    class SnippetViewSet(viewsets.ModelViewSet):
        """
        This viewset automatically provides `list`, `create`, `retrieve`,
        `update` and `destroy` actions.

        Additionally we also provide an extra `highlight` action.
        """
        queryset = Snippet.objects.all()
        serializer_class = SnippetSerializer
        permission_classes = (permissions.IsAuthenticatedOrReadOnly,
                              IsOwnerOrReadOnly,)

        @detail_route(renderer_classes=[renderers.StaticHTMLRenderer])
        def highlight(self, request, *args, **kwargs):
            snippet = self.get_object()
            return Response(snippet.highlighted)

        def perform_create(self, serializer):
            serializer.save(owner=self.request.user)

This time we've used the `ModelViewSet` class in order to get the complete set of default read and write operations.

Notice that we've also used the `@detail_route` decorator to create a custom action, named `highlight`.  This decorator can be used to add any custom endpoints that don't fit into the standard `create`/`update`/`delete` style.

Custom actions which use the `@detail_route` decorator will respond to `GET` requests by default.  We can use the `methods` argument if we wanted an action that responded to `POST` requests.

The URLs for custom actions by default depend on the method name itself. If you want to change the way url should be constructed, you can include url_path as a decorator keyword argument.

## Binding ViewSets to URLs explicitly

The handler methods only get bound to the actions when we define the URLConf.
To see what's going on under the hood let's first explicitly create a set of views from our ViewSets.

In the `snippets/urls.py` file we bind our `ViewSet` classes into a set of concrete views.

    from snippets.views import SnippetViewSet, UserViewSet, api_root
    from rest_framework import renderers

    snippet_list = SnippetViewSet.as_view({
        'get': 'list',
        'post': 'create'
    })
    snippet_detail = SnippetViewSet.as_view({
        'get': 'retrieve',
        'put': 'update',
        'patch': 'partial_update',
        'delete': 'destroy'
    })
    snippet_highlight = SnippetViewSet.as_view({
        'get': 'highlight'
    }, renderer_classes=[renderers.StaticHTMLRenderer])
    user_list = UserViewSet.as_view({
        'get': 'list'
    })
    user_detail = UserViewSet.as_view({
        'get': 'retrieve'
    })

Notice how we're creating multiple views from each `ViewSet` class, by binding the http methods to the required action for each view.

Now that we've bound our resources into concrete views, we can register the views with the URL conf as usual.

    urlpatterns = format_suffix_patterns([
        url(r'^$', api_root),
        url(r'^snippets/$', snippet_list, name='snippet-list'),
        url(r'^snippets/(?P<pk>[0-9]+)/$', snippet_detail, name='snippet-detail'),
        url(r'^snippets/(?P<pk>[0-9]+)/highlight/$', snippet_highlight, name='snippet-highlight'),
        url(r'^users/$', user_list, name='user-list'),
        url(r'^users/(?P<pk>[0-9]+)/$', user_detail, name='user-detail')
    ])

## Using Routers

Because we're using `ViewSet` classes rather than `View` classes, we actually don't need to design the URL conf ourselves.  The conventions for wiring up resources into views and urls can be handled automatically, using a `Router` class.  All we need to do is register the appropriate view sets with a router, and let it do the rest.

Here's our re-wired `snippets/urls.py` file.

    from django.conf.urls import url, include
    from rest_framework.routers import DefaultRouter
    from snippets import views

    # Create a router and register our viewsets with it.
    router = DefaultRouter()
    router.register(r'snippets', views.SnippetViewSet)
    router.register(r'users', views.UserViewSet)

    # The API URLs are now determined automatically by the router.
    urlpatterns = [
        url(r'^', include(router.urls))
    ]

Registering the viewsets with the router is similar to providing a urlpattern.  We include two arguments - the URL prefix for the views, and the viewset itself.

The `DefaultRouter` class we're using also automatically creates the API root view for us, so we can now delete the `api_root` method from our `views` module.

## Trade-offs between views vs viewsets

Using viewsets can be a really useful abstraction.  It helps ensure that URL conventions will be consistent across your API, minimizes the amount of code you need to write, and allows you to concentrate on the interactions and representations your API provides rather than the specifics of the URL conf.

That doesn't mean it's always the right approach to take.  There's a similar set of trade-offs to consider as when using class-based views instead of function based views.  Using viewsets is less explicit than building your views individually.

In [part 7][tut-7] of the tutorial we'll look at how we can add an API schema,
and interact with our API using a client library or command line tool.

[tut-7]: 7-schemas-and-client-libraries.md


text:
from django.conf.urls import url
from . import views

handler404 = 'dev.views.page_not_found_view'
handler500 = 'dev.views.error_view'
handler403 = 'dev.views.permission_denied_view'
handler400 = 'dev.views.bad_request_view'

urlpatterns = [
    url(r'^(?i)quickstart/', views.quick_start, name='quick_start'),
    url(r'^$', views.introduction, name='introduction'),
]


text:
<?php

namespace Slick\Filter;

/**
 * Url filter
 *
 * @package Slick\Filter
 * @author  Filipe Silva <silvam.filipe@gmail.com>
 */
class Url implements FilterInterface
{

    /**
     * Returns the result of filtering $value
     *
     * @param mixed $value
     *
     * @throws Exception\CannotFilterValueException
     *      If filtering $value is impossible.
     *
     * @return mixed
     */
    public function filter($value)
    {
        return filter_var($value, FILTER_SANITIZE_URL);
    }
}


text:
package com.carlosbecker.github;

import javax.inject.Inject;

import org.eclipse.egit.github.core.client.GitHubClient;

import com.carlosbecker.integration.IntegratorConfig;
import com.google.inject.Provider;

public class GitHubClientProvider implements Provider<GitHubClient> {
    @Inject
    private IntegratorConfig config;

    @Override
    public GitHubClient get() {
        GitHubClient client = new GitHubClient();
        client.setOAuth2Token(config.oauth());
        return client;
    }
}


text:
using NUnit.Framework;
using RampUp.Actors;
using RampUp.Actors.Impl;
using RampUp.Buffers;
using AHandler = RampUp.Tests.Actors.Impl.ActorRegistryTestsBase.AHandler;
using ABHandler = RampUp.Tests.Actors.Impl.ActorRegistryTestsBase.ABHandler;
using A = RampUp.Tests.Actors.Impl.ActorRegistryTestsBase.A;
using B = RampUp.Tests.Actors.Impl.ActorRegistryTestsBase.B;

namespace RampUp.Tests.Actors.Impl
{
    public class CompositeActorTests
    {
        [Test]
        public void DesribesAndDispatchesProperly()
        {
            var a = new AHandler();
            var ab = new ABHandler();
            var actor = new CompositeActor(new IActor[] {a, ab}, new StructSizeCounter(),
                FakeMessageIdGenerator.GetMessageId);
            CollectionAssert.AreEquivalent(new[] {typeof (A), typeof (B)}, actor.Descriptor.HandledMessageTypes);
            var aid = FakeMessageIdGenerator.GetMessageId(typeof (A));
            var bid = FakeMessageIdGenerator.GetMessageId(typeof (B));

            // Ensure counters
            Assert.AreEqual(0, a.ACount);
            Assert.AreEqual(0, ab.ACount);
            Assert.AreEqual(0, ab.BCount);

            // A
            actor.MessageHandler(aid, ByteChunk.Empty);
            Assert.AreEqual(1, a.ACount);
            Assert.AreEqual(1, ab.ACount);
            Assert.AreEqual(0, ab.BCount);

            // B
            actor.MessageHandler(bid, ByteChunk.Empty);
            Assert.AreEqual(1, a.ACount);
            Assert.AreEqual(1, ab.ACount);
            Assert.AreEqual(1, ab.BCount);
        }
    }
}


text:
from __future__ import division

import libtcodpy as libtcod
import xp_loader
import gzip
from vec2d import Vec2d

from ui.strings.command_responses import command_response_table
from ui.frame import Frame
from ui.ui_event import UIEvent, UIEventType

# pseudoterminal frame - sits on the left and displays current input and input history to the player - primary interface to the actual game
# also manages keyboard input and generates events to the game state to signal commands
class FramePseudoTerminal(Frame):

	def __init__(self, root_console_width, root_console_height, terminal_width, terminal_height, frame_manager):
		# constants and initialization
		self.prompt_string = "X:\\>"
		self.input_command = ""
		self.blinking_cursor = "_"
		self.cursor_blink_delay = 500
		self.cursor_timer = 0
		self.console_command_history = []
		self.console_max_history_length = terminal_height - 2
		self.input_enabled = True

		Frame.__init__(self, root_console_width, root_console_height, terminal_width, terminal_height, frame_manager)
		#-1 to account for border tile
		self.max_command_size = self.width - len(self.prompt_string) - 1

		libtcod.console_set_key_color(self.console, libtcod.Color(255, 0, 255))

	def update(self, delta):
		key = libtcod.console_check_for_keypress(True)

		self.update_blinky_cursor(delta)

		if self.input_enabled:

			if len(self.input_command) < self.max_command_size:
				if key.vk == libtcod.KEY_CHAR:
					self.input_command += chr(key.c)
				#add numbers, because these are separate keycodes for some godforsaken reason
				#really, libtcod?
				elif key.vk == libtcod.KEY_0:
					self.input_command += '0'
				elif key.vk == libtcod.KEY_1:
					self.input_command += '1'
				elif key.vk == libtcod.KEY_2:
					self.input_command += '2'
				elif key.vk == libtcod.KEY_3:
					self.input_command += '3'
				elif key.vk == libtcod.KEY_4:
					self.input_command += '4'
				elif key.vk == libtcod.KEY_5:
					self.input_command += '5'
				elif key.vk == libtcod.KEY_6:
					self.input_command += '6'
				elif key.vk == libtcod.KEY_7:
					self.input_command += '7'
				elif key.vk == libtcod.KEY_8:
					self.input_command += '8'
				elif key.vk == libtcod.KEY_9:
					self.input_command += '9'
				elif key.vk == libtcod.KEY_UP:
					self.input_command += chr(24)
				elif key.vk == libtcod.KEY_DOWN:
					self.input_command += chr(25)
				elif key.vk == libtcod.KEY_LEFT:
					self.input_command += chr(27)
				elif key.vk == libtcod.KEY_RIGHT:
					self.input_command += chr(26)
			#send command
				elif key.vk == libtcod.KEY_ENTER and self.input_command != "":
					self.add_line_to_history(self.prompt_string + self.input_command)
					self.frame_manager.parent_menu.handle_input_command(self.input_command)
					self.input_command = ""
				elif key.vk == libtcod.KEY_BACKSPACE:
					self.input_command = self.input_command[:-1]

	def update_blinky_cursor(self, delta):
		self.cursor_timer += delta
		if self.cursor_timer > self.cursor_blink_delay:
			self.cursor_timer = 0
			if self.blinking_cursor == "_":
				self.blinking_cursor = " "
			else:
				self.blinking_cursor = "_"

	def handle_ui_event(self, event):
		if event.type == UIEventType.InputDisabled:
			self.input_enabled = False
		elif event.type == UIEventType.InputEnabled:
			#add a blank line
			self.add_line_to_history('')
			self.input_enabled = True
		elif event.type == UIEventType.InvalidCommand and len(event.data['command']) > 1:
			#if it was a non single character command and the result was not found, try splitting the command out into characters and trying each one
			#TODO move this into command strings file
			self.add_line_to_history('Event sequence:')
			for char in list(event.data['command']):
				self.frame_manager.parent_menu.handle_input_command(char)
		elif event.type in command_response_table:
			if 'command' in event.data:
				self.add_line_to_history(command_response_table[event.type].format(event.data['command']))
			else:
				self.add_line_to_history(command_response_table[event.type])

	def add_line_to_history(self, line):
		#remove the oldest history line - the best way I can think of to do it right now
		if len(self.console_command_history) >= self.console_max_history_length:
			self.console_command_history.reverse()
			self.console_command_history.pop()
			self.console_command_history.reverse()

		self.console_command_history.append(line)

	def draw(self):
		libtcod.console_clear(self.console)

		libtcod.console_set_default_background(self.console, libtcod.Color(255,0,255))
		libtcod.console_rect(self.console, 0, 0, self.width, self.height, libtcod.BKGND_SET)
		libtcod.console_set_default_background(self.console, libtcod.black)

		libtcod.console_set_alignment(self.console, libtcod.LEFT)

		current_height = 0
		for line in self.console_command_history:
			libtcod.console_print(self.console, 0, current_height, line)
			current_height += 1
		if self.input_enabled:
			libtcod.console_print(self.console, 0, current_height, self.prompt_string + self.input_command + self.blinking_cursor)

		libtcod.console_vline(self.console, self.width - 1, 0, self.height)

		libtcod.console_blit(self.console, 0, 0, self.width, self.height, 0, 0, self.root_console_height - self.height)


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/DigitalTabletop.iml" filepath="$PROJECT_DIR$/DigitalTabletop.iml" />
      <module fileurl="file://$PROJECT_DIR$/DigitalTabletop/DigitalTabletop-DigitalTabletop.iml" filepath="$PROJECT_DIR$/DigitalTabletop/DigitalTabletop-DigitalTabletop.iml" />
    </modules>
  </component>
</project>


text:
/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package net.java.sip.communicator.plugin.addrbook.msoutlook;

import java.awt.event.*;

import javax.swing.*;

import org.jitsi.service.resources.*;

import net.java.sip.communicator.plugin.addrbook.*;
import net.java.sip.communicator.plugin.desktoputil.*;

/**
 * A dialog with warning message that Outlook is not the default mail client
 * shown when the contact source is started.
 *
 * @author Hristo Terezov
 */
public class DefaultMailClientMessageDialog
    extends MessageDialog
{

    /**
     * Serial ID.
     */
    private static final long serialVersionUID = -6321186451307613417L;

    /**
     * The <tt>ResourceManagementService</tt>
     */
    private static ResourceManagementService resources
        = AddrBookActivator.getResources();

    /**
     * Make Outlook default mail client check box.
     */
    private JCheckBox defaultMailClientCheckBox = new SIPCommCheckBox(
        resources
            .getI18NString("plugin.addrbook.MAKE_OUTLOOK_DEFAULT_MAIL_CLIENT"));

    public static int DONT_ASK_SELECTED_MASK = 1;

    public static int DEFAULT_MAIL_CLIENT_SELECTED_MASK = 2;

    /**
     * Creates an instance of <tt>DefaultMailClientMessageDialog</tt>.
     */
    public DefaultMailClientMessageDialog()
    {
        super(null,
            AddrBookActivator.getResources().getI18NString(
            "plugin.addrbook.OUTLOOK_IS_NOT_DEFAULT_MAIL_CLIENT_TITLE"),
            resources.getI18NString(
                "plugin.addrbook.OUTLOOK_IS_NOT_DEFAULT_MAIL_CLIENT",
                new String[]{
                    resources.getSettingsString(
                        "service.gui.APPLICATION_NAME")}), false);
        checkBoxPanel.setLayout(new BoxLayout(checkBoxPanel, BoxLayout.Y_AXIS));
        checkBoxPanel.add(defaultMailClientCheckBox);
    }

    /**
     * Handles the <tt>ActionEvent</tt>. Depending on the user choice sets
     * the return code to the appropriate value.
     *
     * @param e the <tt>ActionEvent</tt> that notified us
     */
    public void actionPerformed(ActionEvent e)
    {
        JButton button = (JButton)e.getSource();

        if(!button.equals(okButton))
            return;

        this.returnCode = 0;

        if (doNotAskAgain.isSelected())
        {
            this.returnCode = this.returnCode | DONT_ASK_SELECTED_MASK;
        }

        if (defaultMailClientCheckBox.isSelected())
        {
            this.returnCode
                = this.returnCode | DEFAULT_MAIL_CLIENT_SELECTED_MASK;
        }

        this.dispose();
    }

}


text:
package edu.harvard.canvas_data.client.tables;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.csv.CSVRecord;

public class ExternalToolActivationFact extends CanvasDataTable {
  private Long externalToolActivationId;
  private Long courseId;
  private Long accountId;
  private Long rootAccountId;
  private Long enrollmentTermId;
  private Long courseAccountId;

  public ExternalToolActivationFact(final CSVRecord record) {
    String $externalToolActivationId = record.get(0);
    if ($externalToolActivationId != null && $externalToolActivationId.length() > 0) {
      this.externalToolActivationId = Long.valueOf($externalToolActivationId);
    }
    String $courseId = record.get(1);
    if ($courseId != null && $courseId.length() > 0) {
      this.courseId = Long.valueOf($courseId);
    }
    String $accountId = record.get(2);
    if ($accountId != null && $accountId.length() > 0) {
      this.accountId = Long.valueOf($accountId);
    }
    String $rootAccountId = record.get(3);
    if ($rootAccountId != null && $rootAccountId.length() > 0) {
      this.rootAccountId = Long.valueOf($rootAccountId);
    }
    String $enrollmentTermId = record.get(4);
    if ($enrollmentTermId != null && $enrollmentTermId.length() > 0) {
      this.enrollmentTermId = Long.valueOf($enrollmentTermId);
    }
    String $courseAccountId = record.get(5);
    if ($courseAccountId != null && $courseAccountId.length() > 0) {
      this.courseAccountId = Long.valueOf($courseAccountId);
    }
  }

  public Long getExternalToolActivationId() {
    return this.externalToolActivationId;
  }

  public Long getCourseId() {
    return this.courseId;
  }

  public Long getAccountId() {
    return this.accountId;
  }

  public Long getRootAccountId() {
    return this.rootAccountId;
  }

  public Long getEnrollmentTermId() {
    return this.enrollmentTermId;
  }

  public Long getCourseAccountId() {
    return this.courseAccountId;
  }

  @Override
    public List<Object> getCsvFields() {
    final List<Object> fields = new ArrayList<Object>();
    fields.add(externalToolActivationId);
    fields.add(courseId);
    fields.add(accountId);
    fields.add(rootAccountId);
    fields.add(enrollmentTermId);
    fields.add(courseAccountId);
    return fields;
  }

  @Override
  public List<String> getCsvHeaders() {
    final List<String> fields = new ArrayList<String>();
      fields.add("external_tool_activation_id");
      fields.add("course_id");
      fields.add("account_id");
      fields.add("root_account_id");
      fields.add("enrollment_term_id");
      fields.add("course_account_id");
    return fields;
  }
}


text:
//   Copyright 2015 Patrick Putnam
//
//   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.
#ifndef GENERATE_MUTATION_KERNEL_IMPL_HPP_
#define GENERATE_MUTATION_KERNEL_IMPL_HPP_

#include "clotho/cuda/data_spaces/allele_space/device_allele_space.hpp"
#include "clotho/cuda/data_spaces/event_space/device_event_space.hpp"
#include "clotho/cuda/data_spaces/free_space/device_free_space.hpp"

template < class StateType, class AlleleSpaceType, class IntType, class OrderTag >
__global__ void _generate_mutation_kernel( StateType * states
                                        , device_free_space< IntType, OrderTag > * fspace
                                        , device_event_space< IntType, OrderTag > * events
                                        , AlleleSpaceType * alleles ) {
    typedef StateType                               state_type;

    typedef device_free_space< IntType, OrderTag >  free_space_type;
    typedef device_event_space< IntType, OrderTag > event_space_type;

    unsigned int tid = threadIdx.y * blockDim.x + threadIdx.x;

    unsigned int N = events->total;
    unsigned int i = tid;
    unsigned int * fmap = fspace->free_map;

    state_type local_state = states[tid];

    OrderTag * otag = NULL;

    while( i < N ) {
        unsigned int idx = fmap[ i ];

        _generate_random_allele( &local_state, alleles, idx, otag );

        i += (blockDim.x * blockDim.y);
    }

    states[tid] = local_state;
}

/*
template < class StateType, class RealType, class IntType, class OrderTag >
__global__ void _generate_mutation_kernel( StateType * states
                                        , device_free_space< IntType, OrderTag > * fspace
                                        , device_event_space< IntType, OrderTag > * events
                                        , device_weighted_allele_space< RealType > * alleles ) {
    typedef StateType                               state_type;

    typedef device_free_space< IntType, OrderTag >  free_space_type;

    typedef device_event_space< IntType, OrderTag > event_space_type;

    typedef device_weighted_allele_space< RealType >  allele_space_type;
    typedef typename allele_space_type::real_type     real_type;

    unsigned int tid = threadIdx.y * blockDim.x + threadIdx.x;

    unsigned int N = events->total;

    unsigned int i = tid;

//    allele_space_type local_space = * alleles;

    real_type * locs = alleles->locations;
    real_type * wghts = alleles->weights;

    unsigned int * fmap = fspace->free_map;

    state_type local_state = states[tid];

    while( i < N ) {
        unsigned int idx = fmap[ i ];

        real_type x = curand_uniform( &local_state );
        real_type y = curand_normal( &local_state );

        locs[idx] = x;
        wghts[idx] = y;

        i += (blockDim.x * blockDim.y);
    }

    states[tid] = local_state;
}*/

#endif  // GENERATE_MUTATION_KERNEL_IMPL_HPP_


text:
package org.insightech.er.editor.model.diagram_contents.not_element.dictionary;

import org.insightech.er.db.sqltype.SqlType;

public class RealWord extends Word {

    private static final long serialVersionUID = -1983348253197344183L;

	private String physicalName;

	private String logicalName;

	private SqlType type;

	private TypeData typeData;

	private String description;

	public RealWord(String physicalName, String logicalName, SqlType type,
			TypeData typeData, String description, String database) {
		this.physicalName = physicalName;
		this.logicalName = logicalName;
		this.setType(type, typeData, database);
		this.description = description;
	}

	public RealWord(Word word) {
		this.physicalName = word.getPhysicalName();
		this.logicalName = word.getLogicalName();
		this.type = word.getType();
		this.typeData = new TypeData(word.getTypeData());
		this.description = word.getDescription();
	}

	@Override
	public String getLogicalName() {
		return logicalName;
	}

	@Override
	public String getPhysicalName() {
		return physicalName;
	}

	@Override
	public SqlType getType() {
		return type;
	}

	@Override
	public void setLogicalName(String logicalName) {
		this.logicalName = logicalName;
	}

	@Override
	public void setPhysicalName(String physicalName) {
		this.physicalName = physicalName;
	}

	@Override
	public void setType(SqlType type, TypeData typeData, String database) {
		this.type = type;
		this.typeData = new TypeData(typeData);;

		if (type != null && type.isNeedLength(database)) {
			if (this.typeData.getLength() == null) {
				this.typeData.setLength(0);
			}
		} else {
			this.typeData.setLength(null);
		}

		if (type != null && type.isNeedDecimal(database)) {
			if (this.typeData.getDecimal() == null) {
				this.typeData.setDecimal(0);
			}
		} else {
			this.typeData.setDecimal(null);
		}

	}

	@Override
	protected void setType(SqlType type) {
		this.type = type;
	}

	@Override
	public TypeData getTypeData() {
		return typeData;
	}

	@Override
	protected void setTypeData(TypeData typeData) {
		this.typeData = typeData;
	}

	public String getDescription() {
		return this.description;
	}

	@Override
	public void setDescription(String description) {
		this.description = description;
	}

	@Override
	public final int hashCode() {
		return super.hashCode();
	}

	@Override
	public final boolean equals(Object obj) {
		return super.equals(obj);
	}
}


text:
#ifndef _BSD_SYS_UCONTEXT_H_
#define	_BSD_SYS_UCONTEXT_H_

#include <sys/bsd_signal.h>
#include <machine/bsd_ucontext.h>

typedef struct __ucontext {
	/*
	 * Keep the order of the first two fields. Also,
	 * keep them the first two fields in the structure.
	 * This way we can have a union with struct
	 * sigcontext and ucontext_t. This allows us to
	 * support them both at the same time.
	 * note: the union is not defined, though.
	 */
	sigset_t	uc_sigmask;
	mcontext_t	uc_mcontext;

	struct __ucontext *uc_link;
	stack_t		uc_stack;
	int		uc_flags;
#define	UCF_SWAPPED	0x00000001	/* Used by swapcontext(3). */
	int		__spare__[4];
} ucontext_t;

#if defined(_FREEBSD_KERNEL) && defined(COMPAT_FREEBSD4)
#if defined(__i386__)
struct ucontext4 {
	sigset_t	uc_sigmask;
	struct mcontext4 uc_mcontext;
	struct ucontext4 *uc_link;
	stack_t		uc_stack;
	int		__spare__[8];
};
#else	/* __i386__ */
#define ucontext4 ucontext
#endif	/* __i386__ */
#endif	/* _FREEBSD_KERNEL */

#ifndef _FREEBSD_KERNEL

__BEGIN_DECLS

int	getcontext(ucontext_t *);
int	setcontext(const ucontext_t *);
void	makecontext(ucontext_t *, void (*)(void), int, ...);
int	signalcontext(ucontext_t *, int, __sighandler_t *);
int	swapcontext(ucontext_t *, const ucontext_t *);

__END_DECLS

#else /* _FREEBSD_KERNEL */

struct thread;

/*
 * Flags for get_mcontext().  The low order 4 bits (i.e a mask of 0x0f) are
 * reserved for use by machine independent code.  All other bits are for use
 * by machine dependent code.
 */
#define	GET_MC_CLEAR_RET	1

/* Machine-dependent functions: */
int	get_mcontext(struct thread *, mcontext_t *, int);
int	set_mcontext(struct thread *, const mcontext_t *);

#endif /* !_FREEBSD_KERNEL */

#endif /* !_BSD_SYS_UCONTEXT_H_ */


text: <ng-include src="'partials/comcenter-content.html'"></ng-include>


text: Symfony2 Bundle for the breakfast-serializer


text:
package me.towdium.jecharacters.utils;

import me.towdium.jecharacters.JechConfig;
import me.towdium.jecharacters.JustEnoughCharacters;
import me.towdium.pinin.DictLoader;
import me.towdium.pinin.PinIn;
import me.towdium.pinin.searchers.TreeSearcher;
import mezz.jei.core.search.suffixtree.GeneralizedSuffixTree;
import net.minecraft.MethodsReturnNonnullByDefault;
import net.minecraft.client.searchtree.SuffixArray;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.config.ModConfigEvent;

import javax.annotation.ParametersAreNonnullByDefault;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.function.BiConsumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static me.towdium.pinin.searchers.Searcher.Logic.CONTAIN;
import static net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus.MOD;

@Mod.EventBusSubscriber(bus = MOD)
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
public class Match {
    public static final PinIn context = new PinIn(new Loader()).config().accelerate(true).commit();
    static final Pattern p = Pattern.compile("a");
    static Set<TreeSearcher<?>> searchers = Collections.newSetFromMap(new WeakHashMap<>());

    private static <T> TreeSearcher<T> searcher() {
        TreeSearcher<T> ret = new TreeSearcher<>(CONTAIN, context);
        searchers.add(ret);
        return ret;
    }

    // Psi
    public static int rank(Object o, String s1, String s2) {
        return contains(s1, s2) ? 1 : 0;
    }

    public static String wrap(String s) {
        return JechConfig.enableQuote.get() ? '"' + s + '"' : s;
    }

    public static boolean contains(String s, CharSequence cs) {
        boolean b = context.contains(s, cs.toString());
        if (JechConfig.enableVerbose.get())
            JustEnoughCharacters.logger.info("contains(" + s + ',' + cs + ")->" + b);
        return b;
    }

    public static boolean contains(CharSequence a, CharSequence b, boolean c) {
        if (c) return contains(a.toString().toLowerCase(), b.toString().toLowerCase());
        else return contains(a, b);
    }

    public static boolean equals(String s, Object o) {
        boolean b = o instanceof String && context.matches(s, (String) o);
        if (JechConfig.enableVerbose.get())
            JustEnoughCharacters.logger.info("contains(" + s + ',' + o + ")->" + b);
        return b;
    }

    public static boolean contains(CharSequence a, CharSequence b) {
        return contains(a.toString(), b);
    }

    public static Matcher matcher(Pattern test, CharSequence name) {
        boolean result;
        if ((test.flags() & Pattern.CASE_INSENSITIVE) != 0 || (test.flags() & Pattern.UNICODE_CASE) != 0) {
            result = matches(name.toString().toLowerCase(), test.toString().toLowerCase());
        } else {
            result = matches(name.toString(), test.toString());
        }
        return result ? p.matcher("a") : p.matcher("");
    }

    public static boolean matches(String s1, String s2) {
        boolean start = s2.startsWith(".*");
        boolean end = s2.endsWith(".*");
        if (start && end && s2.length() < 4) end = false;
        if (start || end) s2 = s2.substring(start ? 2 : 0, s2.length() - (end ? 2 : 0));
        return contains(s1, s2);
    }

    @SubscribeEvent
    public static void onConfigChange(ModConfigEvent e) {
        onConfigChange();
    }

    public static void onConfigChange() {
        context.config().keyboard(JechConfig.enumKeyboard.get().keyboard)
                .fAng2An(JechConfig.enableFAng2an.get()).fEng2En(JechConfig.enableFEng2en.get())
                .fIng2In(JechConfig.enableFIng2in.get()).fZh2Z(JechConfig.enableFZh2z.get())
                .fCh2C(JechConfig.enableFCh2c.get()).fSh2S(JechConfig.enableFSh2s.get())
                .fU2V(JechConfig.enableFU2v.get()).commit();
        searchers.forEach(TreeSearcher::refresh);
    }

    public static class FakeTree<T> extends GeneralizedSuffixTree<T> {

        TreeSearcher<T> tree = searcher();

        @Override
        public void getSearchResults(String word, Set<T> results) {
            if (JechConfig.enableVerbose.get()) {
                JustEnoughCharacters.logger.info("FakeTree:search(" + word + ')');
            }
            results.addAll(tree.search(word));
        }

        @Override
        public void put(String key, T value) {
            if (JechConfig.enableVerbose.get()) {
                JustEnoughCharacters.logger.info("FakeTree:put(" + key + ',' + value + ')');
            }
            tree.put(key, value);
        }

        @Override
        public void getAllElements(Set<T> results) {
            results.addAll(tree.search(""));
        }

    }

    public static class FakeArray<T> extends SuffixArray<T> {
        TreeSearcher<T> tree = searcher();

        @Override
        public void add(T v, String k) {
            if (JechConfig.enableVerbose.get())
                JustEnoughCharacters.logger.info("FakeArray:put(" + v + ',' + k + ')');
            tree.put(k, v);
        }

        @Override
        public void generate() {
        }

        @Override
        public List<T> search(String k) {
            if (JechConfig.enableVerbose.get())
                JustEnoughCharacters.logger.info("FakeArray:search(" + k + ')');
            return tree.search(k);
        }
    }

    static class Loader extends DictLoader.Default {
        @Override
        public void load(BiConsumer<Character, String[]> feed) {
            super.load(feed);
            feed.accept('\u9FCF', new String[]{"mai4"});   // 钅麦
            feed.accept('\u9FD4', new String[]{"ge1"});    // 钅哥
            feed.accept('\u9FED', new String[]{"ni3"});    // 钅尔
            feed.accept('\u9FEC', new String[]{"tian2"});  // 石田
            feed.accept('\u9FEB', new String[]{"ao4"});    // 奥气
            feed.accept('\uE900', new String[]{"lu2"});    // 钅卢
            feed.accept('\uE901', new String[]{"du4"});    // 钅杜
            feed.accept('\uE902', new String[]{"xi3"});    // 钅喜
            feed.accept('\uE903', new String[]{"bo1"});    // 钅波
            feed.accept('\uE904', new String[]{"hei1"});   // 钅黑
            feed.accept('\uE906', new String[]{"da2"});    // 钅达
            feed.accept('\uE907', new String[]{"lun2"});   // 钅仑
            feed.accept('\uE910', new String[]{"fu1"});    // 钅夫
            feed.accept('\uE912', new String[]{"li4"});    // 钅立
        }
    }
}


text:
<?xml version="1.0"?>
<doc>
  <assembly>
    <name>c:\!\nemerle\bin\Release\net-4.0\PowerPack\\Nemerle.Peg.xml</name>
  </assembly>
  <members>
    <member name="T:Nemerle.Peg.ExtensionRuleBase`1" />
    <member name="M:Nemerle.Peg.ExtensionRuleBase`1.#ctor" />
    <member name="M:Nemerle.Peg.ExtensionRuleBase`1.Parse(System.Int32,System.String)" />
    <member name="M:Nemerle.Peg.ExtensionRuleBase`1.Parse(System.Int32,System.String,`0@)" />
    <member name="M:Nemerle.Peg.ExtensionRuleBase`1.get_PrecedenceLesserThan" />
    <member name="P:Nemerle.Peg.ExtensionRuleBase`1.PrecedenceLesserThan" />
    <member name="M:Nemerle.Peg.ExtensionRuleBase`1.get_PrecedenceEqualsTo" />
    <member name="P:Nemerle.Peg.ExtensionRuleBase`1.PrecedenceEqualsTo" />
    <member name="M:Nemerle.Peg.ExtensionRuleBase`1.get_PrecedenceGreaterThan" />
    <member name="P:Nemerle.Peg.ExtensionRuleBase`1.PrecedenceGreaterThan" />
    <member name="M:Nemerle.Peg.ExtensionRuleBase`1.get_Name" />
    <member name="P:Nemerle.Peg.ExtensionRuleBase`1.Name" />
    <member name="T:Nemerle.Peg.IGrammar" />
    <member name="M:Nemerle.Peg.IGrammar.PushGrammarState" />
    <member name="M:Nemerle.Peg.IGrammar.PopGrammarState" />
    <member name="T:Nemerle.Peg.IToken" />
    <member name="M:Nemerle.Peg.IToken.get_StartPos" />
    <member name="P:Nemerle.Peg.IToken.StartPos" />
    <member name="M:Nemerle.Peg.IToken.get_EndPos" />
    <member name="P:Nemerle.Peg.IToken.EndPos" />
    <member name="T:Nemerle.Peg.Located" />
    <member name="M:Nemerle.Peg.Located.#cctor" />
    <member name="F:Nemerle.Peg.Located.location" />
    <member name="M:Nemerle.Peg.Located.get_StartPos" />
    <member name="P:Nemerle.Peg.Located.StartPos" />
    <member name="M:Nemerle.Peg.Located.get_EndPos" />
    <member name="P:Nemerle.Peg.Located.EndPos" />
    <member name="M:Nemerle.Peg.Located.#ctor" />
    <member name="M:Nemerle.Peg.Located.#ctor(Nemerle.Peg.Location)" />
    <member name="F:Nemerle.Peg.Located._posAndLenRx" />
    <member name="M:Nemerle.Peg.Located.ExtractPosAndLen(System.String)" />
    <member name="M:Nemerle.Peg.Located.BuildMessage(System.String)" />
    <member name="M:Nemerle.Peg.Located.get_Location" />
    <member name="M:Nemerle.Peg.Located.set_Location(Nemerle.Peg.Location)" />
    <member name="P:Nemerle.Peg.Located.Location" />
    <member name="T:Nemerle.Peg.Location" />
    <member name="F:Nemerle.Peg.Location._source" />
    <member name="F:Nemerle.Peg.Location._startPos" />
    <member name="F:Nemerle.Peg.Location._endPos" />
    <member name="M:Nemerle.Peg.Location.get_IsEmpty" />
    <member name="P:Nemerle.Peg.Location.IsEmpty" />
    <member name="M:Nemerle.Peg.Location.GetText" />
    <member name="M:Nemerle.Peg.Location.get_StartLineColumn" />
    <member name="P:Nemerle.Peg.Location.StartLineColumn" />
    <member name="M:Nemerle.Peg.Location.get_EndLineColumn" />
    <member name="P:Nemerle.Peg.Location.EndLineColumn" />
    <member name="M:Nemerle.Peg.Location.ToString" />
    <member name="M:Nemerle.Peg.Location.Combine(Nemerle.Peg.Location)" />
    <member name="M:Nemerle.Peg.Location.op_Addition(Nemerle.Peg.Location,Nemerle.Peg.Location)" />
    <member name="M:Nemerle.Peg.Location.FromToken(Nemerle.Peg.SourceSnapshot,Nemerle.Peg.NToken)" />
    <member name="M:Nemerle.Peg.Location.FromToken(Nemerle.Peg.SourceSnapshot,Nemerle.Peg.IToken)" />
    <member name="M:Nemerle.Peg.Location.FromToken(Nemerle.Peg.SourceSnapshot,Nemerle.Peg.NToken,Nemerle.Peg.NToken)" />
    <member name="M:Nemerle.Peg.Location.FromToken(Nemerle.Peg.SourceSnapshot,Nemerle.Peg.IToken,Nemerle.Peg.IToken)" />
    <member name="M:Nemerle.Peg.Location.get_Source" />
    <member name="P:Nemerle.Peg.Location.Source" />
    <member name="M:Nemerle.Peg.Location.get_StartPos" />
    <member name="P:Nemerle.Peg.Location.StartPos" />
    <member name="M:Nemerle.Peg.Location.get_EndPos" />
    <member name="P:Nemerle.Peg.Location.EndPos" />
    <member name="M:Nemerle.Peg.Location.#ctor(Nemerle.Peg.SourceSnapshot,System.Int32,System.Int32)" />
    <member name="T:Nemerle.Peg.NToken" />
    <member name="M:Nemerle.Peg.NToken.GetHashCode(System.Collections.IEqualityComparer)" />
    <member name="M:Nemerle.Peg.NToken.Equals(System.Object,System.Collections.IEqualityComparer)" />
    <member name="M:Nemerle.Peg.NToken.op_Inequality(Nemerle.Peg.NToken,Nemerle.Peg.NToken)" />
    <member name="M:Nemerle.Peg.NToken.op_Equality(Nemerle.Peg.NToken,Nemerle.Peg.NToken)" />
    <member name="M:Nemerle.Peg.NToken.GetHashCode" />
    <member name="M:Nemerle.Peg.NToken.Equals(System.Object)" />
    <member name="M:Nemerle.Peg.NToken.Equals(Nemerle.Peg.NToken)" />
    <member name="F:Nemerle.Peg.NToken._startPos" />
    <member name="F:Nemerle.Peg.NToken._endPos" />
    <member name="M:Nemerle.Peg.NToken.get_IsEmpty" />
    <member name="P:Nemerle.Peg.NToken.IsEmpty" />
    <member name="M:Nemerle.Peg.NToken.ToString" />
    <member name="M:Nemerle.Peg.NToken.EqualsImpl(Nemerle.Peg.NToken)" />
    <member name="M:Nemerle.Peg.NToken.get_StartPos" />
    <member name="P:Nemerle.Peg.NToken.StartPos" />
    <member name="M:Nemerle.Peg.NToken.get_EndPos" />
    <member name="P:Nemerle.Peg.NToken.EndPos" />
    <member name="M:Nemerle.Peg.NToken.#ctor(System.Int32,System.Int32)" />
    <member name="T:Nemerle.Peg.PegParser" />
    <member name="M:Nemerle.Peg.PegParser.#ctor" />
    <member name="F:Nemerle.Peg.PegParser._grammars" />
    <member name="F:Nemerle.Peg.PegParser._grammarList" />
    <member name="F:Nemerle.Peg.PegParser._stateStack" />
    <member name="M:Nemerle.Peg.PegParser.AddGrammar``1(Nemerle.Builtins.Function{Nemerle.Peg.PegParser,``0})" />
    <member name="M:Nemerle.Peg.PegParser.PushState" />
    <member name="M:Nemerle.Peg.PegParser.PopState" />
    <member name="T:Nemerle.Peg.SingleLineSourceSnapshot" />
    <member name="M:Nemerle.Peg.SingleLineSourceSnapshot.#ctor(System.String,System.Int32,System.String)" />
    <member name="T:Nemerle.Peg.SourceSnapshot" />
    <member name="F:Nemerle.Peg.SourceSnapshot._N_cache_3776" />
    <member name="F:Nemerle.Peg.SourceSnapshot.originalText" />
    <member name="F:Nemerle.Peg.SourceSnapshot.text" />
    <member name="F:Nemerle.Peg.SourceSnapshot.fileIndex" />
    <member name="F:Nemerle.Peg.SourceSnapshot.fileName" />
    <member name="F:Nemerle.Peg.SourceSnapshot.lineIndexes" />
    <member name="M:Nemerle.Peg.SourceSnapshot.#ctor(System.String,System.String,System.Int32,System.String,System.Int32[])" />
    <member name="M:Nemerle.Peg.SourceSnapshot.#ctor(System.String,System.Int32,System.String)" />
    <member name="M:Nemerle.Peg.SourceSnapshot.GetLinesRelocationTable" />
    <member name="M:Nemerle.Peg.SourceSnapshot.PositionToLineColumn(System.Int32)" />
    <member name="M:Nemerle.Peg.SourceSnapshot.GetSourceLine(System.Int32)" />
    <member name="M:Nemerle.Peg.SourceSnapshot.WithText(System.String)" />
    <member name="M:Nemerle.Peg.SourceSnapshot.ToString" />
    <member name="M:Nemerle.Peg.SourceSnapshot.MakeLineIndexes(System.String)" />
    <member name="M:Nemerle.Peg.SourceSnapshot.get_OriginalText" />
    <member name="P:Nemerle.Peg.SourceSnapshot.OriginalText" />
    <member name="M:Nemerle.Peg.SourceSnapshot.get_Text" />
    <member name="P:Nemerle.Peg.SourceSnapshot.Text" />
    <member name="M:Nemerle.Peg.SourceSnapshot.get_FileIndex" />
    <member name="P:Nemerle.Peg.SourceSnapshot.FileIndex" />
    <member name="M:Nemerle.Peg.SourceSnapshot.get_FileName" />
    <member name="P:Nemerle.Peg.SourceSnapshot.FileName" />
    <member name="T:Nemerle.Peg.VList`1" />
    <member name="T:Nemerle.Peg.VToken`1" />
    <member name="F:Nemerle.Peg.VToken`1.value" />
    <member name="M:Nemerle.Peg.VToken`1.op_Implicit(Nemerle.Peg.VToken{`0})~`0" />
    <member name="M:Nemerle.Peg.VToken`1.get_Value" />
    <member name="P:Nemerle.Peg.VToken`1.Value" />
    <member name="M:Nemerle.Peg.VToken`1.#ctor(`0)" />
    <member name="M:Nemerle.Peg.VToken`1.#ctor(Nemerle.Peg.Location,`0)" />
  </members>
</doc>


text:
import Observable from '../Observable';
export default function takeUntil<T>(notifier: Observable<any>): any;


text:
/**
 * WEBLAB Global Abatement
 */

var WEBLAB = WEBLAB || {};

/** @define {boolean} */
var ENABLE_DEBUG = true;

//to avoid 'console' is undefined Error in IE
if (!window.console || !ENABLE_DEBUG) console = {
    log: function() {}
};
/*alert("WINDOWS MODE!");

var alertFallback = true;
   if (typeof console === "undefined" || typeof console.log === "undefined") {
     console = {};
     if (alertFallback) {
         console.log = function(msg) {
              alert(msg);
         };
     } else {
         console.log = function() {};
     }
   }*/

console.log("ENABLE_DEBUG: ", ENABLE_DEBUG);

//safari bind fix
if (typeof Function.prototype.bind != 'function') {
    console.log("WEBLAB adding bind function...");
    Function.prototype.bind = function(bind) {
        var self = this;
        return function() {
            var args = Array.prototype.slice.call(arguments);
            return self.apply(bind || null, args);
        };
    };
}

WEBLAB.namespace = function(aNamespace) {
    var parts = aNamespace.split('.'),
        parent = WEBLAB,
        i;
    if (parts[0] === "WEBLAB") {
        parts = parts.slice(1);
    }

    for (i = 0; i < parts.length; i += 1) {
        if (typeof parent[parts[i]] === "undefined") {
            parent[parts[i]] = {};
        }
        parent = parent[parts[i]];
    }

    return parent;
};


text:
B-tree storage of sets with configurable I/O.

This implements B-trees of any order >= 2 in Erlang.

I/O is handled by user-provided callbacks.

Only sets (keys without data) are supported.

## Implementation notes

- Initially based on [Wirth76].
- Converted from Pascal to C, and then to Erlang.  The Erlang
  version uses tuples in lieu of arrays.  Pages are of variable
  not fixed size.
- I/O of pages is made explicit.
- Search is separated from insertion.  Search returns a stack of
  pages and indices recording the path from the root to the key.
  Insertion uses that stack to navigate the tree when rewriting it.
- Deletion is tricky enough that the recursive structure of the
  original code is kept as-is.  A local cache is used to avoid
  redundant I/O.
- Our use cases only want sets, so this does not associate
  attributes with the keys.
- Bulk-loading into an empty tree has been added.

## References

[BM72] R. Bayer and E. McCreight, "Organization and Maintenance of
Large Ordered Indexes", Acta Informatica, Vol. 1, Fasc. 3, pp. 173--189,
1972.

[Wirth76] Niklaus Wirth, "Algorithms + Data Structures = Programs",
Program 4.7, pp 252--257, Prentice-Hall, 1976.

[Comer79] Douglas Comer, "The Ubiquitous B-Tree", Computing Surveys,
Vol. 11, No. 2, pp 121--137, ACM, June 1979.


text:
using Knightware.Diagnostics;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;

namespace Spyder.Client.Net.DrawingData.Deserializers
{
    /// <summary>
    /// Manages a collection of network packets and deserializes them to drawing data objects when available
    /// </summary>
    public class DrawingDataDeserializer
    {
        private const int HEADER_SIZE = 7;

        private int rxSequence = -1;
        private int rxPacketCount = -1;
        private readonly SortedDictionary<int, byte[]> rxCache = new();

        public string ServerIP { get; private set; }
        public string ServerVersion { get; private set; }

        public DrawingDataDeserializer(string serverIP, string serverVersion)
        {
            this.ServerIP = serverIP;
            this.ServerVersion = serverVersion;
        }

        /// <summary>
        /// Event raised when a new DrawingData object has been deserialized
        /// </summary>
        public event DrawingDataDeserializedEventHandler DrawingDataDeserialized;
        protected void OnDrawingDataDeserialized(DrawingDataDeserializedEventArgs args)
        {
            DrawingDataDeserialized?.Invoke(this, args);
        }

        public void Read(byte[] Stream, int offset)
        {
            int readIndex = offset;

            if (Stream == null || Stream.Length < HEADER_SIZE)
                return;

            byte version = Stream[readIndex++];
            byte compression = Stream[readIndex++];
            byte sequence = Stream[readIndex++];
            byte packetID = Stream[readIndex++];
            byte totalPackets = Stream[readIndex++];
            int streamLength = Stream[readIndex++];
            streamLength |= (Stream[readIndex++] << 8);
            bool compressed = (compression == (byte)'C');

            var deserializer = GetDeserializer(version, ServerVersion);
            if (deserializer == null)
            {
                //Ignore drawing data that we don't have a deserializer for
                return;
            }

            if (streamLength > Stream.Length - offset)
            {
                TraceQueue.Trace(this, TracingLevel.Information, "DrawingData: Invalid packet size specified in header: {0}", streamLength);
                return;
            }

            //New Sequence?
            if (sequence != rxSequence)
            {
                rxCache.Clear();
                rxSequence = sequence;
                rxPacketCount = totalPackets;
            }

            //Validate packet total size
            if (totalPackets != this.rxPacketCount)
            {
                TraceQueue.Trace(this, TracingLevel.Information, "DrawingData: Invalid packet count in current sequence");
                return;
            }

            //Computers with multiple network cards may give us the same drawing data packet more than once
            if (rxCache.ContainsKey(packetID))
            {
                return;
            }

            //Copy data from packet
            byte[] packetData = new byte[streamLength];
            Array.Copy(Stream, readIndex, packetData, 0, streamLength);
            rxCache.Add(packetID, packetData);

            //Last Packet
            if (rxCache.Count == totalPackets)
            {
                //Create full packet
                byte[] fullRxPacket = new byte[rxCache.Values.Sum(array => (array == null ? 0 : array.Length))];
                int index = 0;
                for (int i = 0; i < totalPackets; i++)
                {
                    byte[] current = rxCache[i];
                    if (current == null)
                        return;

                    int currentLength = current.Length;
                    Array.ConstrainedCopy(current, 0, fullRxPacket, index, currentLength);
                    index += currentLength;
                }

                //Decompress packet if needed
                if (compressed)
                {
                    fullRxPacket = Decompress(fullRxPacket, 0, fullRxPacket.Length);
                    if (fullRxPacket == null)
                    {
                        TraceQueue.Trace(this, TracingLevel.Warning, "Failed to decompress drawing data");
                        return;
                    }
                }

                //Deserialize data
                DrawingData drawingData;
                drawingData = deserializer.Deserialize(fullRxPacket);
                if (drawingData == null)
                {
                    TraceQueue.Trace(this, TracingLevel.Warning, "Failed to deserialize drawing data");
                    return;
                }

                //Raise drawing data update event
                OnDrawingDataDeserialized(new DrawingDataDeserializedEventArgs()
                {
                    DrawingData = drawingData,
                    RawMessage = fullRxPacket
                });

                rxCache.Clear();
            }
        }

        private IDrawingDataDeserializer GetDeserializer(int drawingDataVersion, string serverVersion)
        {
            switch (drawingDataVersion)
            {
                case 8: return new DrawingDataDeserializer_Version8();
                case 19: return new DrawingDataDeserializer_Version19();
                case 20: return new DrawingDataDeserializer_Version20(serverVersion);
                case 50: return new DrawingDataDeserializer_Version50(serverVersion);
                case 51: return new DrawingDataDeserializer_Version51(serverVersion);
                case 52: return new DrawingDataDeserializer_Version52(serverVersion);
                case 53: return new DrawingDataDeserializer_Version53(serverVersion);
                case 54: return new DrawingDataDeserializer_Version54(serverVersion);
                default: return null;
            }
        }

        private byte[] Decompress(byte[] compressedData, int offset, int count)
        {
            if (compressedData == null)
            {
                return null;
            }

            try
            {
                //Read the uncompressed size of the stream from the first 4 bytes of the source array
                int uncompressedSize = 0;
                uncompressedSize |= (compressedData[offset]);
                uncompressedSize |= (compressedData[offset + 1] << 8);
                uncompressedSize |= (compressedData[offset + 2] << 16);
                uncompressedSize |= (compressedData[offset + 3] << 24);

                return Decompress(compressedData, offset + 4, count - 4, uncompressedSize);
            }
            catch (Exception ex)
            {
                TraceQueue.Trace(this, TracingLevel.Warning, "{0} occurred while decompressing DrawingData: {1}", ex.GetType().Name, ex.Message);
                return null;
            }
        }

        public byte[] Decompress(byte[] zipCompressedData, int offset, int count, int uncompressedDataLength)
        {
            using (MemoryStream compressedStream = new MemoryStream(zipCompressedData, offset, count, false))
            {
                using (var decompressor = new GZipStream(compressedStream, CompressionMode.Decompress))
                {
                    byte[] decompressedBytes = new byte[uncompressedDataLength];
                    int read = decompressor.Read(decompressedBytes, 0, uncompressedDataLength);
                    return (read == uncompressedDataLength ? decompressedBytes : null);
                }
            }
        }
    }
}


text:
<?php

namespace Oro\Bundle\EmailBundle\Provider;

use Oro\Bundle\EmailBundle\Entity\EmailBody;
use Oro\Bundle\EntityBundle\Provider\EntityNameProviderInterface;

class EmailBodyEntityNameProvider implements EntityNameProviderInterface
{
    /**
     * {@inheritdoc}
     */
    public function getName($format, $locale, $entity)
    {
        if (!$entity instanceof EmailBody) {
            return false;
        }

        return $entity->getBodyIsText() ? $entity->getTextBody() : $entity->getBodyContent();
    }

    /**
     * {@inheritdoc}
     */
    public function getNameDQL($format, $locale, $className, $alias)
    {
        if ($className !== EmailBody::class) {
            return false;
        }

        return sprintf('CASE WHEN %1$s.bodyIsText = true THEN %1$s.textBody ELSE %1$s.bodyContent END', $alias);
    }
}


text:
"""
This module holds models related to the process to generate contracts
"""
import uuid
from itertools import chain
from pathlib import Path

from django.db import models
from django.urls import reverse
from django.utils import timezone
from markupfield.fields import MarkupField
from ordered_model.models import OrderedModel

from sponsors.exceptions import InvalidStatusException
from sponsors.utils import file_from_storage
from sponsors.models.sponsorship import Sponsorship

class LegalClause(OrderedModel):
    """
    Legal clauses applied to benefits
    """

    internal_name = models.CharField(
        max_length=1024,
        verbose_name="Internal Name",
        help_text="Friendly name used internally by PSF to reference this clause",
        blank=False,
    )
    clause = models.TextField(
        verbose_name="Clause",
        help_text="Legal clause text to be added to contract",
        blank=False,
    )
    notes = models.TextField(
        verbose_name="Notes", help_text="PSF staff notes", blank=True, default=""
    )

    def __str__(self):
        return f"Clause: {self.internal_name}"

    class Meta(OrderedModel.Meta):
        pass

def signed_contract_random_path(instance, filename):
    """
    Use random UUID to name signed contracts
    """
    directory = instance.SIGNED_PDF_DIR
    ext = "".join(Path(filename).suffixes)
    name = uuid.uuid4()
    return f"{directory}{name}{ext}"

class Contract(models.Model):
    """
    Contract model to oficialize a Sponsorship
    """

    DRAFT = "draft"
    OUTDATED = "outdated"
    AWAITING_SIGNATURE = "awaiting signature"
    EXECUTED = "executed"
    NULLIFIED = "nullified"

    STATUS_CHOICES = [
        (DRAFT, "Draft"),
        (OUTDATED, "Outdated"),
        (AWAITING_SIGNATURE, "Awaiting signature"),
        (EXECUTED, "Executed"),
        (NULLIFIED, "Nullified"),
    ]

    FINAL_VERSION_PDF_DIR = "sponsors/contracts/"
    FINAL_VERSION_DOCX_DIR = FINAL_VERSION_PDF_DIR + "docx/"
    SIGNED_PDF_DIR = FINAL_VERSION_PDF_DIR + "signed/"

    status = models.CharField(
        max_length=20, choices=STATUS_CHOICES, default=DRAFT, db_index=True
    )
    revision = models.PositiveIntegerField(default=0, verbose_name="Revision nº")
    document = models.FileField(
        upload_to=FINAL_VERSION_PDF_DIR,
        blank=True,
        verbose_name="Unsigned PDF",
    )
    document_docx = models.FileField(
        upload_to=FINAL_VERSION_DOCX_DIR,
        blank=True,
        verbose_name="Unsigned Docx",
    )
    signed_document = models.FileField(
        upload_to=signed_contract_random_path,
        blank=True,
        verbose_name="Signed PDF",
    )

    # Contract information gets populated during object's creation.
    # The sponsorship FK ís just a reference to keep track of related objects.
    # It shouldn't be used to fetch for any of the sponsorship's data.
    sponsorship = models.OneToOneField(
        "sponsors.Sponsorship",
        null=True,
        on_delete=models.SET_NULL,
        related_name="contract",
    )
    sponsor_info = models.TextField(verbose_name="Sponsor information")
    sponsor_contact = models.TextField(verbose_name="Sponsor contact")

    # benefits_list = """
    #   - Foundation - Promotion of Python case study [^1]
    #   - PyCon - PyCon website Listing [^1][^2]
    #   - PyPI - Social media promotion of your sponsorship
    # """
    benefits_list = MarkupField(markup_type="markdown")
    # legal_clauses = """
    # [^1]: Here's one with multiple paragraphs and code.
    #    Indent paragraphs to include them in the footnote.
    #    `{ my code }`
    #    Add as many paragraphs as you like.
    # [^2]: Here's one with multiple paragraphs and code.
    #    Indent paragraphs to include them in the footnote.
    #    `{ my code }`
    #    Add as many paragraphs as you like.
    # """
    legal_clauses = MarkupField(markup_type="markdown", default="", blank=True)

    # Activity control fields
    created_on = models.DateField(auto_now_add=True)
    last_update = models.DateField(auto_now=True)
    sent_on = models.DateField(null=True)

    class Meta:
        verbose_name = "Contract"
        verbose_name_plural = "Contracts"

    def __str__(self):
        return f"Contract: {self.sponsorship}"

    @classmethod
    def new(cls, sponsorship):
        """
        Factory method to create a new Contract from a Sponsorship
        """
        sponsor = sponsorship.sponsor
        primary_contact = sponsor.primary_contact

        sponsor_info = f"{sponsor.name}, {sponsor.description}"
        sponsor_contact = ""
        if primary_contact:
            sponsor_contact = f"{primary_contact.name} - {primary_contact.phone} | {primary_contact.email}"

        benefits = sponsorship.benefits.all()
        # must query for Legal Clauses again to respect model's ordering
        clauses_ids = [c.id for c in chain(*(b.legal_clauses for b in benefits))]
        legal_clauses = list(LegalClause.objects.filter(id__in=clauses_ids))

        benefits_list = []
        for benefit in benefits:
            item = f"- {benefit.program_name} - {benefit.name_for_display}"
            index_str = ""
            for legal_clause in benefit.legal_clauses:
                index = legal_clauses.index(legal_clause) + 1
                index_str += f"[^{index}]"
            if index_str:
                item += f" {index_str}"
            benefits_list.append(item)

        legal_clauses_text = "\n".join(
            [f"[^{i}]: {c.clause}" for i, c in enumerate(legal_clauses, start=1)]
        )
        return cls.objects.create(
            sponsorship=sponsorship,
            sponsor_info=sponsor_info,
            sponsor_contact=sponsor_contact,
            benefits_list="\n".join([b for b in benefits_list]),
            legal_clauses=legal_clauses_text,
        )

    @property
    def is_draft(self):
        return self.status == self.DRAFT

    @property
    def preview_url(self):
        return reverse("admin:sponsors_contract_preview", args=[self.pk])

    @property
    def awaiting_signature(self):
        return self.status == self.AWAITING_SIGNATURE

    @property
    def next_status(self):
        states_map = {
            self.DRAFT: [self.AWAITING_SIGNATURE, self.EXECUTED],
            self.OUTDATED: [],
            self.AWAITING_SIGNATURE: [self.EXECUTED, self.NULLIFIED],
            self.EXECUTED: [],
            self.NULLIFIED: [self.DRAFT],
        }
        return states_map[self.status]

    def save(self, **kwargs):
        if all([self.pk, self.is_draft]):
            self.revision += 1
        return super().save(**kwargs)

    def set_final_version(self, pdf_file, docx_file=None):
        if self.AWAITING_SIGNATURE not in self.next_status:
            msg = f"Can't send a {self.get_status_display()} contract."
            raise InvalidStatusException(msg)

        sponsor = self.sponsorship.sponsor.name.upper()

        # save contract as PDF file
        path = f"{self.FINAL_VERSION_PDF_DIR}"
        pdf_filename = f"{path}SoW: {sponsor}.pdf"
        file = file_from_storage(pdf_filename, mode="wb")
        file.write(pdf_file)
        file.close()
        self.document = pdf_filename

        # save contract as docx file
        if docx_file:
            path = f"{self.FINAL_VERSION_DOCX_DIR}"
            docx_filename = f"{path}SoW: {sponsor}.docx"
            file = file_from_storage(docx_filename, mode="wb")
            file.write(docx_file)
            file.close()
            self.document_docx = docx_filename

        self.status = self.AWAITING_SIGNATURE
        self.save()

    def execute(self, commit=True, force=False):
        if not force and self.EXECUTED not in self.next_status:
            msg = f"Can't execute a {self.get_status_display()} contract."
            raise InvalidStatusException(msg)

        self.status = self.EXECUTED
        self.sponsorship.status = Sponsorship.FINALIZED
        self.sponsorship.finalized_on = timezone.now().date()
        if commit:
            self.sponsorship.save()
            self.save()

    def nullify(self, commit=True):
        if self.NULLIFIED not in self.next_status:
            msg = f"Can't nullify a {self.get_status_display()} contract."
            raise InvalidStatusException(msg)

        self.status = self.NULLIFIED
        if commit:
            self.sponsorship.save()
            self.save()