text:
<?php

namespace Brother\CommonBundle\Mailer;
use Brother\CommonBundle\Event\Events;
use Brother\CommonBundle\Event\MailEvent;
use Symfony\Component\Templating\EngineInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

/**
 * Base class for the Mailer.
 */
abstract class BaseMailer implements MailerInterface
{
    /**
     * @var array
     */
    protected $config;

    /**
     * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
     */
    protected $dispatcher;

    protected $mailer;

    /**
     * Constructor
     *
     * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher
     * @param \Symfony\Component\Templating\EngineInterface $templating
     * @param array $config
     */
    public function __construct(EventDispatcherInterface $dispatcher, \Swift_Mailer $mailer, EngineInterface $templating, $config)
    {
        $this->config = $config;
        $this->dispatcher = $dispatcher;
        $this->templating = $templating;
        $this->mailer = $mailer;
    }

    /**
     * @param MailerEntryInterface $entry
     *
     * @return mixed
     */
    public function sendAdminNotification(MailerEntryInterface $entry)
    {
        $emailTitle = str_replace(
            ['{name}', '{email}'],
            array($entry->getName(), $entry->getEmail()),
            $this->config['notification']['title']
        );

        $mailOptions = [];
        $mailOptions['subject'] = $emailTitle;
        $mailOptions['from'] = $this->config['notification']['from'];
        $mailOptions['to'] = $this->config['notification']['to'];
        $mailOptions['body'] = $this->templating->render(
            $this->config['notification']['view'],
            ['entry' => $entry]
        );

        $event = new MailEvent($entry, $mailOptions);
        $this->dispatcher->dispatch(Events::ENTRY_PRE_NOTIFY, $event);

        if ($event->isPropagationStopped()) {
            return false;
        }

        $this->sendEmail($mailOptions);
        $this->dispatcher->dispatch(Events::ENTRY_POST_NOTIFY, $event);

        return true;
    }

    /**
     * @param array $options
     */
    public function sendEmail(array $options)
    {
        if (null !== $this->mailer) {
            $message = \Swift_Message::newInstance()
                ->setSubject($options['subject'])
                ->setFrom($options['from'])
                ->setTo($options['to'])
                ->setBody($options['body']);

            if (isset($options['cc'])) {
                $message->setCc($options['body']);
            }

            $this->mailer->send($message);
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
package com.lottery.activity;

import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.lottery.R;
import com.lottery.base.BaseActivity;
import com.lottery.base.RequestResult;
import com.lottery.bean.BusinessBean;
import com.lottery.finals.RequestCode;
import com.lottery.utils.GsonUtil;
import com.lottery.utils.HttpUtils;
import com.lottery.utils.SPUtil;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class BusinessRecordActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener
        , View.OnClickListener, RequestResult {
    @BindView(R.id.tv_all)
    TextView tv_all;  //全部
    @BindView(R.id.tv_recharge)
    TextView tv_recharge;  //充值
    @BindView(R.id.tv_bunko)
    TextView tv_bunko;  //输赢
    @BindView(R.id.tv_withdraw_cash)
    TextView tv_withdraw_cash;  //提现
    @BindView(R.id.tv_poundage)
    TextView tv_poundage;  //手续费
    @BindView(R.id.tv_lead_up)
    TextView tv_lead_up;  //抢庄
    @BindView(R.id.srl_refurbish)
    SwipeRefreshLayout srl_refurbish;//下拉刷新
    @BindView(R.id.lv_business)
    ListView lv_business;//显示记录
    private List<BusinessBean.ResultBean> data = new ArrayList<>();//数据
    private Map<String, String> map = new HashMap<>();//参数集合
    private boolean isChecked1 = true;//全部按钮是否选中
    private boolean isChecked2;//充值按钮是否选中
    private boolean isChecked3;//输赢按钮是否选中
    private boolean isChecked4;//提现按钮是否选中
    private boolean isChecked5;//手续费按钮是否选中
    private boolean isChecked6;//抢庄按钮是否选中
    private CommonAdapter<BusinessBean.ResultBean> adapter;
    private HttpUtils httpUtils;
    private String code;
    private String kind = "";

    public BusinessRecordActivity() {
        super(R.layout.activity_business_record);
    }

    @Override
    protected void getBundleExtras(Bundle extras) {

    }

    @Override
    protected void initContentView(Bundle bundle) {

    }

    @Override
    protected void initView() {
        code = SPUtil.getString("alias");
        map.clear();
        httpUtils = new HttpUtils(BusinessRecordActivity.this, BusinessRecordActivity.this, "正在获取", true);
        map.put("m", "score");
        map.put("act", "detail");
        map.put("code", "001");
        map.put("kind", kind);
        httpUtils.async(RequestCode.BUSINESS_DETAIL_ALL, map);
        ButterKnife.bind(this); //绑定注解
        setTitle("交易记录"); //标题
        //返回按钮
        setLeftIcon(R.mipmap.ic_back, "返回", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        //注册点击监听事件
        tv_all.setOnClickListener(this);
        tv_recharge.setOnClickListener(this);
        tv_bunko.setOnClickListener(this);
        tv_withdraw_cash.setOnClickListener(this);
        tv_poundage.setOnClickListener(this);
        tv_lead_up.setOnClickListener(this);

        srl_refurbish.setColorSchemeColors(ContextCompat.getColor(this, R.color.colorAccent));//下拉刷新时控件的颜色
        srl_refurbish.setOnRefreshListener(this);//注册下拉刷新
        adapter = new CommonAdapter<BusinessBean.ResultBean>(this, R.layout.item_lv_act_business, data) {
            @Override
            protected void convert(ViewHolder viewHolder, BusinessBean.ResultBean item, int position) {
                viewHolder.setText(R.id.tv_name, SPUtil.getString("alias"))
                        .setText(R.id.tv_style, item.getKind())
                        .setText(R.id.tv_time, item.getOpertime())
                        .setText(R.id.tv_money, item.getScore());
            }
        };
        lv_business.setAdapter(adapter);
    }

    /**
     * 下拉刷新
     */
    @Override
    public void onRefresh() {
//        map.put("m", "score");
//        map.put("act", "detail");
//        map.put("code", "001");
        map.put("kind", kind);
        httpUtils.async(RequestCode.BUSINESS_DETAIL_RECHARGE, map);
//        srl_refurbish.setRefreshing(false);//刷新结束 下拉框消失
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_all://全部
                isChecked1 = true;
                isChecked2 = false;
                isChecked3 = false;
                isChecked4 = false;
                isChecked5 = false;
                isChecked6 = false;
                srl_refurbish.setRefreshing(true);
                break;
            case R.id.tv_recharge://下注
                isChecked2 = true;
                isChecked1 = false;
                isChecked3 = false;
                isChecked4 = false;
                isChecked5 = false;
                isChecked6 = false;
                srl_refurbish.setRefreshing(true);
                break;
            case R.id.tv_bunko://充值
                isChecked3 = true;
                isChecked1 = false;
                isChecked2 = false;
                isChecked4 = false;
                isChecked5 = false;
                isChecked6 = false;
                srl_refurbish.setRefreshing(true);
                break;
            case R.id.tv_withdraw_cash://提现
                isChecked4 = true;
                isChecked1 = false;
                isChecked2 = false;
                isChecked3 = false;
                isChecked5 = false;
                isChecked6 = false;
                srl_refurbish.setRefreshing(true);
                break;
            case R.id.tv_poundage://手续费
                isChecked5 = true;
                isChecked1 = false;
                isChecked2 = false;
                isChecked3 = false;
                isChecked4 = false;
                isChecked6 = false;
                srl_refurbish.setRefreshing(true);
                break;
            case R.id.tv_lead_up://手续费
                isChecked6 = true;
                isChecked5 = false;
                isChecked1 = false;
                isChecked2 = false;
                isChecked3 = false;
                isChecked4 = false;
                srl_refurbish.setRefreshing(true);
                break;
        }
        isSelected();
    }

    private void isSelected() {
        if (isChecked1) { //全部
            tv_all.setClickable(false);
            kind = "";
//            map.put("m", "score");
//            map.put("act", "detail");
//            map.put("code", "001");
            map.put("kind", kind);
            httpUtils.async(RequestCode.BUSINESS_DETAIL_ALL, map);
            tv_all.setTextColor(ContextCompat.getColor(BusinessRecordActivity.this, R.color.red));
        } else {
            tv_all.setClickable(true);
            tv_all.setTextColor(ContextCompat.getColor(BusinessRecordActivity.this, R.color.black));
        }
        if (isChecked2) { //充值
            tv_recharge.setClickable(false);
            kind = "充值";
//            map.put("m", "score");
//            map.put("act", "detail");
//            map.put("code", "001");
            map.put("kind", kind);
            httpUtils.async(RequestCode.BUSINESS_DETAIL_RECHARGE, map);
            tv_recharge.setTextColor(ContextCompat.getColor(BusinessRecordActivity.this, R.color.red));
        } else {
            tv_recharge.setClickable(true);
            tv_recharge.setTextColor(ContextCompat.getColor(BusinessRecordActivity.this, R.color.black));
        }
        if (isChecked3) {  //输赢
            tv_bunko.setClickable(false);
            kind = "输赢";
//            map.put("m", "score");
//            map.put("act", "detail");
//            map.put("code", "001");
            map.put("kind", kind);
            httpUtils.async(RequestCode.BUSINESS_DETAIL_BUNKO, map);
            tv_bunko.setTextColor(ContextCompat.getColor(BusinessRecordActivity.this, R.color.red));
        } else {
            tv_bunko.setClickable(true);
            tv_bunko.setTextColor(ContextCompat.getColor(BusinessRecordActivity.this, R.color.black));
        }
        if (isChecked4) { //提现
            tv_withdraw_cash.setClickable(false);
            kind = "提现";
//            map.put("m", "score");
//            map.put("act", "detail");
//            map.put("code", "001");
            map.put("kind", kind);
            httpUtils.async(RequestCode.BUSINESS_DETAIL_WITHDRAW_CASH, map);
            tv_withdraw_cash.setTextColor(ContextCompat.getColor(BusinessRecordActivity.this, R.color.red));
        } else {
            tv_withdraw_cash.setClickable(true);
            tv_withdraw_cash.setTextColor(ContextCompat.getColor(BusinessRecordActivity.this, R.color.black));
        }
        if (isChecked5) { //手续费
            tv_poundage.setClickable(false);
            kind = "手续费";
//            map.put("m", "score");
//            map.put("act", "detail");
//            map.put("code", "001");
            map.put("kind", kind);
            httpUtils.async(RequestCode.BUSINESS_DETAIL_POUNDAGE, map);
            tv_poundage.setTextColor(ContextCompat.getColor(BusinessRecordActivity.this, R.color.red));
        } else {
            tv_poundage.setClickable(true);
            tv_poundage.setTextColor(ContextCompat.getColor(BusinessRecordActivity.this, R.color.black));
        }
        if (isChecked6) { //抢庄
            tv_lead_up.setClickable(false);
            kind = "抢庄";
//            map.put("m", "score");
//            map.put("act", "detail");
//            map.put("code", "001");
            map.put("kind", kind);
            httpUtils.async(RequestCode.BUSINESS_DETAIL_LEAD_UP, map);
            tv_lead_up.setTextColor(ContextCompat.getColor(BusinessRecordActivity.this, R.color.red));
        } else {
            tv_lead_up.setClickable(true);
            tv_lead_up.setTextColor(ContextCompat.getColor(BusinessRecordActivity.this, R.color.black));
        }
    }

    @Override
    public void onSuccess(String result, String requestCode) {
        BusinessBean bean = GsonUtil.GsonToBean(result, BusinessBean.class);
        srl_refurbish.setRefreshing(false);
        data.clear();
        if (bean.getCode() == 0) {
            if (RequestCode.BUSINESS_DETAIL_ALL.equals(requestCode)) { //全部
                data.addAll(bean.getResult());
                adapter.notifyDataSetChanged();
            } else if (RequestCode.BUSINESS_DETAIL_RECHARGE.equals(requestCode)) { //充值
                data.addAll(bean.getResult());
                adapter.notifyDataSetChanged();
            } else if (RequestCode.BUSINESS_DETAIL_BUNKO.equals(requestCode)) { //输赢
                data.addAll(bean.getResult());
                adapter.notifyDataSetChanged();
            } else if (RequestCode.BUSINESS_DETAIL_WITHDRAW_CASH.equals(requestCode)) { //提现
                data.addAll(bean.getResult());
                adapter.notifyDataSetChanged();
            } else if (RequestCode.BUSINESS_DETAIL_POUNDAGE.equals(requestCode)) { //手续费
                data.addAll(bean.getResult());
                adapter.notifyDataSetChanged();
            } else if (RequestCode.BUSINESS_DETAIL_LEAD_UP.equals(requestCode)) { //抢庄
                data.addAll(bean.getResult());
                adapter.notifyDataSetChanged();
            }
        } else
            showShortToast(bean.getMessage());
    }

    @Override
    public void onFailure(String result, String requestCode) {
        showShortToast(result);
    }
}


text:
@class CLSWebRequest, CLSWebResponse, NSString, NSURLConnection;

@interface CLSWebClientTransaction : NSObject <NSURLConnectionDelegate>
{
    CLSWebRequest *_request;
    CLSWebResponse *_response;
    NSString *_contentType;
    NSURLConnection *_connection;
    struct dispatch_queue_s *_queue;
    CDUnknownBlockType _completionHandler;
}

+ (id)transactionWithRequest:(id)arg1;
- (void)complete;
@property(copy, nonatomic) CDUnknownBlockType completionHandler; // @synthesize completionHandler=_completionHandler;
- (BOOL)connection:(id)arg1 canAuthenticateAgainstProtectionSpace:(id)arg2;
- (void)connection:(id)arg1 didFailWithError:(id)arg2;
- (void)connection:(id)arg1 didReceiveData:(id)arg2;
- (void)connection:(id)arg1 didReceiveResponse:(id)arg2;
- (void)connectionDidFinishLoading:(id)arg1;
- (void)dealloc;
- (id)initWithRequest:(id)arg1;
- (id)objectFromReceivedData;
- (void)startConnection;
- (void)startWithCompletionHandler:(CDUnknownBlockType)arg1;
- (void)syncStartConnection;
- (void)syncStartWithCompletionHandler:(CDUnknownBlockType)arg1;

@end


text:
<?php

namespace Bluz\Tests\Controller;

use Bluz\Common\Exception\ComponentException;
use Bluz\Controller\Meta;
use Bluz\Tests\FrameworkTestCase;

/**
 * ApplicationTest
 *
 * @author   Anton Shevchuk
 * @created  21.05.13 10:24
 */
class MetaTest extends FrameworkTestCase
{
    /**
     * Test all reflection options
     *  - methods
     *  - cache
     *  - cache to html
     *  - params with type cast
     *  - privilege
     *  - routes
     */
    public function testReflectionWithData()
    {
        $controllerFile = __DIR__ . '/Fixtures/ConcreteWithData.php';

        $meta = new Meta($controllerFile);
        $meta->process();

        self::assertEqualsArray(['CLI', 'GET'], $meta->getMethod());
        self::assertEquals(300, $meta->getCache());
        self::assertEqualsArray(['a' => 'int', 'b' => 'float', 'c' => 'string'], $meta->getParams());
        self::assertEquals('Test', $meta->getPrivilege());
        self::assertEqualsArray(['Read', 'Write'], $meta->getAcl());
        self::assertArrayHasSize($meta->getRoute(), 2);
    }

    /**
     * Test all reflection options and export it
     */
    public function testExportReflectionWithData()
    {
        $controllerFile = __DIR__ . '/Fixtures/ConcreteWithData.php';

        $meta = new Meta($controllerFile);
        $meta->process();

        $data = var_export($meta, true);

        self::assertStringStartsWith('Bluz\Controller\Meta::__set_state', $data);
    }

    /**
     * Test reflection:
     *  - get params without description
     */
    public function testReflectionWithoutData()
    {
        $controllerFile = __DIR__ . '/Fixtures/ConcreteWithoutData.php';

        $meta = new Meta($controllerFile);
        $meta->process();

        self::assertEqualsArray(['a' => null, 'b' => null, 'c' => null], $meta->getParams());
    }

    /**
     * Test reflection without return structure
     */
    public function testReflectionWithoutReturn()
    {
        $this->expectException(ComponentException::class);
        $controllerFile = __DIR__ . '/Fixtures/ConcreteWithoutReturn.php';

        $meta = new Meta($controllerFile);
        $meta->process();
    }
}


text:
title: Entity Framework - Binding and CRUD Operations
page_title: Entity Framework - Binding and CRUD Operations | RadGrid for ASP.NET AJAX Documentation
description: Entity Framework - Binding and CRUD Operations
slug: grid/asp.net-3.5-features/entity-framework---binding-and-crud-operations
tags: entity,framework,-,binding,and,crud,operations
published: True
position: 1
---

# Entity Framework - Binding and CRUD Operations

##

The ASP.NET 3.5 framework introduces the ADO.NET Entity Framework which exposes a brand new way to supply data and structure a data access layer (DAL) to your ASP.NET web sites/web application projects.

The ADO.NET Entity Framework is designed to support data-centric applications and services, and provides a platform for programming against data that raises the level of abstraction from the logical relational level to the conceptual level. By enabling developers to work with data at a greater level of abstraction, the Entity Framework supports code that is independent of any particular data storage engine or relational schema. For more information, see [Introducing the Entity Framework](http://msdn.microsoft.com/en-us/library/bb399567.aspx).

The Entity Framework supports an [Entity Data Model](http://msdn.microsoft.com/en-us/library/bb387122.aspx) (EDM) for defining data at both the storage and conceptual level and a mapping between the two. It also enables developers to program directly against the data types defined at the conceptual level as common language runtime (CLR) objects. The Entity Framework provides tools to generate an EDM and the related CLR objects based on an existing database. This reduces much of the data access code that used to be required to create object-based data application and services, and makes it faster to create object-oriented data applications and services from an existing database.

Below is an MSDN tutorial which include step by step directions how to use the ADO.NET Entity Framework:

[ Entity Framework getting started tutorial ](http://msdn.microsoft.com/en-us/library/bb386876.aspx)

RadGrid for ASP.NET AJAX exposes declarative way to binding itself to EntityDataSource (similar to other ASP.NET 2.x/3.x data source controls) which is presented in the [following online demo](http://demos.telerik.com/aspnet-ajax/grid/examples/automaticoperations/efdatabinding/defaultcs.aspx)of the product. Additionally, the grid from the example supports automatic data editing operations as well as paging and sorting. The main points are to configure the EntityDatraSource properties accordingly.

To enable automatic editing at data source level, set the *AllowAutomaticUpdates/AllowAutomaticInserts/AllowAutomaticDeletes* properties of the grid instance and the corresponding *EnableUpdate/EnableInsert/EnableDelete* properties of the EntityDataSource to true.

Here are the code snippets from the example referenced in the previous paragraph:

````ASP.NET
<%@ register assembly="System.Web.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
  namespace="System.Web.UI.WebControls" tagprefix="asp" %>
<telerik:RadScriptManager ID="RadScriptManager1" runat="server">
</telerik:RadScriptManager>
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
  <AjaxSettings>
    <telerik:AjaxSetting AjaxControlID="RadGrid1">
      <UpdatedControls>
        <telerik:AjaxUpdatedControl ControlID="RadGrid1" LoadingPanelID="RadAjaxLoadingPanel1" />
      </UpdatedControls>
    </telerik:AjaxSetting>
  </AjaxSettings>
</telerik:RadAjaxManager>
<telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" />
<telerik:RadGrid ID="RadGrid1" runat="server" DataSourceID="EntityDataSourceCustomers"
  GridLines="None" AllowPaging="True" AllowAutomaticUpdates="True" AllowAutomaticInserts="True"
  AllowSorting="true" Width="750px" OnItemCreated="RadGrid1_ItemCreated">
  <PagerStyle Mode="NextPrevAndNumeric" />
  <MasterTableView DataSourceID="EntityDataSourceCustomers" AutoGenerateColumns="False"
    DataKeyNames="CustomerID" CommandItemDisplay="Top">
    <Columns>
      <telerik:GridEditCommandColumn ButtonType="ImageButton" UniqueName="EditCommandColumn">
      </telerik:GridEditCommandColumn>
      <telerik:GridBoundColumn DataField="CustomerID" HeaderText="CustomerID" SortExpression="CustomerID"
        UniqueName="CustomerID" Visible="false" MaxLength="5">
      </telerik:GridBoundColumn>
      <telerik:GridBoundColumn DataField="ContactName" HeaderText="ContactName" SortExpression="ContactName"
        UniqueName="ContactName">
      </telerik:GridBoundColumn>
      <telerik:GridBoundColumn DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName"
        UniqueName="CompanyName">
      </telerik:GridBoundColumn>
      <telerik:GridBoundColumn DataField="ContactTitle" HeaderText="ContactTitle" SortExpression="ContactTitle"
        UniqueName="ContactTitle">
      </telerik:GridBoundColumn>
      <telerik:GridBoundColumn DataField="Phone" HeaderText="Phone" SortExpression="Phone"
        UniqueName="Phone">
      </telerik:GridBoundColumn>
    </Columns>
    <EditFormSettings>
      <EditColumn ButtonType="ImageButton" />
    </EditFormSettings>
  </MasterTableView>
</telerik:RadGrid>
<asp:EntityDataSource ID="EntityDataSourceCustomers" runat="server" ConnectionString="name=NorthwindEntities"
  DefaultContainerName="NorthwindEntities" EntitySetName="Customers" OrderBy="it.[ContactName]"
  EntityTypeFilter="Customers" EnableUpdate="True" EnableDelete="True" EnableInsert="True">
</asp:EntityDataSource>
````
````C#
protected void RadGrid1_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
    if (e.Item is GridEditableItem && e.Item.IsInEditMode)
    {
        if (!e.Item.OwnerTableView.IsItemInserted)
        {
            GridEditableItem item = e.Item as GridEditableItem;
            GridEditManager manager = item.EditManager;
            GridTextBoxColumnEditor editor = manager.GetColumnEditor("CustomerID") as GridTextBoxColumnEditor;
            editor.TextBoxControl.Enabled = false;            }
    }
}
````
````VB
Protected Sub RadGrid1_ItemCreated(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridItemEventArgs)
    If TypeOf e.Item Is GridEditableItem AndAlso e.Item.IsInEditMode Then
        If Not e.Item.OwnerTableView.IsItemInserted Then
            Dim item As GridEditableItem = TryCast(e.Item, GridEditableItem)
            Dim manager As GridEditManager = item.EditManager
            Dim editor As GridTextBoxColumnEditor = TryCast(manager.GetColumnEditor("CustomerID"), GridTextBoxColumnEditor)
            editor.TextBoxControl.Enabled = False
        End If
    End If
End Sub
````


text:
{% load static %}
<!DOCTYPE html>

		<title>
			Erik Osmond's Portfolio
		</title>
		<meta name="viewport" content="width=device-width, initial-scale=1.0">

		<link href="{% static "css/bootstrap.min.css" %}" rel="stylesheet" media="screen">

          <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">

          </button>
          Next Everest

Home

Anagreat

Knights Tour

Welcome to ErikOsmond.com

Knight's Tour

Including dynamic board size and knight placement

Anagreat

Anagram generator plus automation

Headline for Image 3

description of image 3

		‹
		›

		Hello

		I'm Erik.  In 2010, I found a MIT course on iTunesU which taught me how to build algorithms.
		Although creating most algorithms was difficult initially, and challenges continue to present themselves,
		I find the practice of using computers to solve problems fascinating.  This site contains projects
		that fully engaged my mind in the most enjoyable way.  I'm publishing these works hoping
		that other people who might be interested in computer science can learn something new and
		see a side of computation not always available.  Many people see computers as a black box
		that does magic and if everything goes well, you get the desired results.  With these projects
		I'm aiming to make that black box a slightly lighter shade of grey which might help others understand
		how computers can be instructed to solve hard problems quickly.

		Learning is usually easiest when the student already has an understanding of the context of the challenge.
		Here you have a few contexts from which to choose. Like chess? Check out the
		Knight's Tour.  More of a Scrabble® fan?  Use my algorithm
		Anagreat to see how a computer can take a sequence of letters and create
		every possible combination of those letters in under a second

		This site is currently under construction.  It's not pretty, but it does cool stuff!


text:
using System;

namespace Shared.Core.Utils.Exceptions
{
    ///
    /// Helper class for guard statements, which allow prettier
    /// code for guard clauses
    ///
    /// All credits to Ayende Rahien
    ///
    public class Guard
    {
        ///
        /// Will throw a <see cref="InvalidOperationException"/> if the assertion
        /// is true, with the specificied message.
        ///
        /// <param name="assertion">if set to <c>true</c> [assertion].</param>
        /// <param name="message">The message.</param>
        /// <example>
        /// Sample usage:
        ///
        /// Guard.Against(string.IsNullOrEmpty(name), "Name must have a value");
        ///
        /// </example>
        public static void Against(bool assertion, string message)
        {
            if (assertion == false)
                return;
            throw new InvalidOperationException(message);
        }

        ///
        /// Will throw exception of type <typeparamref name="TException"/>
        /// with the specified message if the assertion is true
        ///
        /// <typeparam name="TException"></typeparam>
        /// <param name="assertion">if set to <c>true</c> [assertion].</param>
        /// <param name="message">The message.</param>
        /// <example>
        /// Sample usage:
        ///
        /// <![CDATA[
        /// Guard.Against<ArgumentException>(string.IsNullOrEmpty(name), "Name must have a value");
        /// ]]>
        ///
        /// </example>
        public static void Against<TException>(bool assertion, string message) where TException : Exception
        {
            if (assertion == false)
                return;
            throw (TException)Activator.CreateInstance(typeof(TException), message);
        }
    }
}


text:
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using System.Buffers;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;

namespace Apache.Arrow
{
    internal static class ArrayPoolExtensions
    {
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static void RentReturn(this ArrayPool<byte> pool, int length, Action<Memory<byte>> action)
        {
            byte[] array = null;

            try
            {
                array = pool.Rent(length);
                action(array.AsMemory(0, length));
            }
            finally
            {
                if (array != null)
                {
                    pool.Return(array);
                }
            }
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static ValueTask RentReturnAsync(this ArrayPool<byte> pool, int length, Func<Memory<byte>, ValueTask> action)
        {
            byte[] array = null;

            try
            {
                array = pool.Rent(length);
                return action(array.AsMemory(0, length));
            }
            finally
            {
                if (array != null)
                {
                    pool.Return(array);
                }
            }
        }
    }
}


text:
// Copyright 2011-2016 Google LLC
//
// 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.

package com.google.security.zynamics.binnavi.debug.connection.packets.replyparsers;

import com.google.security.zynamics.binnavi.debug.connection.DebugCommandType;
import com.google.security.zynamics.binnavi.debug.connection.interfaces.ClientReader;
import com.google.security.zynamics.binnavi.debug.connection.packets.replies.MemoryMapReply;
import com.google.security.zynamics.binnavi.debug.models.processmanager.MemoryMap;
import com.google.security.zynamics.binnavi.debug.models.processmanager.MemorySection;
import com.google.security.zynamics.zylib.disassembly.IAddress;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Parser responsible for parsing replies to Map Memory requests.
 */
public final class MemoryMapParser extends AbstractReplyParser<MemoryMapReply> {
  /**
   * Creates a new Map Memory reply parser.
   *
   * @param clientReader Used to read messages sent by the debug client.
   */
  public MemoryMapParser(final ClientReader clientReader) {
    super(clientReader, DebugCommandType.RESP_MEMMAP_SUCCESS);
  }

  @Override
  protected MemoryMapReply parseError(final int packetId) throws IOException {
    final int errorCode = parseInteger();
    return new MemoryMapReply(packetId, errorCode, null);
  }

  @Override
  public MemoryMapReply parseSuccess(final int packetId, final int argumentCount)
      throws IOException {
    final IAddress addresses[] = new IAddress[argumentCount];
    for (int i = 0; i < argumentCount; i++) {
      addresses[i] = parseAddress();
    }
    final List<MemorySection> map = new ArrayList<>();
    for (int i = 0; i < addresses.length / 2; i++) {
      final IAddress startAddress = addresses[2 * i];
      final IAddress endAddress = addresses[2 * i + 1];
      map.add(new MemorySection(startAddress, endAddress));
    }
    return new MemoryMapReply(packetId, 0, new MemoryMap(map));
  }
}


text:
package kpa

import (
	"context"
	"fmt"
	"net/http"
	"time"

	"knative.dev/pkg/apis/duck"
	"knative.dev/pkg/injection/clients/dynamicclient"
	"knative.dev/pkg/logging"

	netapis "knative.dev/networking/pkg/apis/networking"
	netv1alpha1 "knative.dev/networking/pkg/apis/networking/v1alpha1"
	nethttp "knative.dev/networking/pkg/http"
	netheader "knative.dev/networking/pkg/http/header"
	netprober "knative.dev/networking/pkg/prober"
	pkgnet "knative.dev/pkg/network"
	"knative.dev/serving/pkg/activator"
	autoscalingv1alpha1 "knative.dev/serving/pkg/apis/autoscaling/v1alpha1"
	"knative.dev/serving/pkg/autoscaler/config/autoscalerconfig"
	"knative.dev/serving/pkg/reconciler/autoscaling/config"
	kparesources "knative.dev/serving/pkg/reconciler/autoscaling/kpa/resources"
	aresources "knative.dev/serving/pkg/reconciler/autoscaling/resources"
	"knative.dev/serving/pkg/resources"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/client-go/dynamic"
	"k8s.io/client-go/tools/cache"
)

const (
	scaleUnknown = -1
	probePeriod  = 1 * time.Second
	probeTimeout = 45 * time.Second

	// The time after which the PA will be re-enqueued.
	// This number is small, since `handleScaleToZero` below will
	// re-enqueue for the configured grace period.
	reenqeuePeriod = 1 * time.Second

	// TODO(#3456): Remove this buffer once KPA does pod failure diagnostics.
	//
	// KPA will scale the Deployment down to zero if it fails to activate after ProgressDeadlineSeconds,
	// however, after ProgressDeadlineSeconds, the Deployment itself updates its status, which causes
	// the Revision to re-reconcile and diagnose pod failures. If we use the same timeout here, we will
	// race the Revision reconciler and scale down the pods before it can actually surface the pod errors.
	// We should instead do pod failure diagnostics here immediately before scaling down the Deployment.
	activationTimeoutBuffer = 30 * time.Second
)

var probeOptions = []interface{}{
	netprober.WithHeader(netheader.UserAgentKey, netheader.AutoscalingUserAgent),
	netprober.WithHeader(netheader.ProbeKey, activator.Name),
	netprober.ExpectsBody(activator.Name),
	netprober.ExpectsStatusCodes([]int{http.StatusOK}),
}

// for mocking in tests
type asyncProber interface {
	Offer(context.Context, string, interface{}, time.Duration, time.Duration, ...interface{}) bool
}

// scaler scales the target of a kpa-class PA up or down including scaling to zero.
type scaler struct {
	listerFactory func(gvr schema.GroupVersionResource) (cache.GenericLister, error)
	dynamicClient dynamic.Interface
	transport     http.RoundTripper

	// For sync probes.
	activatorProbe func(pa *autoscalingv1alpha1.PodAutoscaler, transport http.RoundTripper) (bool, error)

	// For async probes.
	probeManager asyncProber
	enqueueCB    func(interface{}, time.Duration)
}

// newScaler creates a scaler.
func newScaler(ctx context.Context, psInformerFactory duck.InformerFactory, enqueueCB func(interface{}, time.Duration)) *scaler {
	logger := logging.FromContext(ctx)
	transport := pkgnet.NewProberTransport()
	ks := &scaler{
		dynamicClient: dynamicclient.Get(ctx),
		transport:     transport,

		// We wrap the PodScalable Informer Factory here so Get() uses the outer context.
		// As the returned Informer is shared across reconciles, passing the context from
		// an individual reconcile to Get() could lead to problems.
		listerFactory: func(gvr schema.GroupVersionResource) (cache.GenericLister, error) {
			_, l, err := psInformerFactory.Get(ctx, gvr)
			return l, err
		},

		// Production setup uses the default probe implementation.
		activatorProbe: activatorProbe,
		probeManager: netprober.New(func(arg interface{}, success bool, err error) {
			logger.Infof("Async prober is done for %v: success?: %v error: %v", arg, success, err)
			// Re-enqueue the PA in any case. If the probe timed out to retry again, if succeeded to scale to 0.
			enqueueCB(arg, reenqeuePeriod)
		}, transport),
		enqueueCB: enqueueCB,
	}
	return ks
}

// Resolves the pa to the probing endpoint Eg. http://hostname:port/healthz
func paToProbeTarget(pa *autoscalingv1alpha1.PodAutoscaler) string {
	svc := pkgnet.GetServiceHostname(pa.Status.ServiceName, pa.Namespace)
	port := netapis.ServicePort(pa.Spec.ProtocolType)

	return fmt.Sprintf("http://%s:%d/%s", svc, port, nethttp.HealthCheckPath)
}

// activatorProbe returns true if via probe it determines that the
// PA is backed by the Activator.
func activatorProbe(pa *autoscalingv1alpha1.PodAutoscaler, transport http.RoundTripper) (bool, error) {
	// No service name -- no probe.
	if pa.Status.ServiceName == "" {
		return false, nil
	}
	return netprober.Do(context.Background(), transport, paToProbeTarget(pa), probeOptions...)
}

func lastPodRetention(pa *autoscalingv1alpha1.PodAutoscaler, cfg *autoscalerconfig.Config) time.Duration {
	d, ok := pa.ScaleToZeroPodRetention()
	if ok {
		return d
	}
	return cfg.ScaleToZeroPodRetentionPeriod
}

// pre: 0 <= min <= max && 0 <= x
func applyBounds(min, max, x int32) int32 {
	if x < min {
		return min
	}
	if max != 0 && x > max {
		return max
	}
	return x
}

func durationMax(d1, d2 time.Duration) time.Duration {
	if d1 < d2 {
		return d2
	}
	return d1
}

func (ks *scaler) handleScaleToZero(ctx context.Context, pa *autoscalingv1alpha1.PodAutoscaler,
	sks *netv1alpha1.ServerlessService, desiredScale int32) (int32, bool) {
	if desiredScale != 0 {
		return desiredScale, true
	}

	// We should only scale to zero when three of the following conditions are true:
	//   a) enable-scale-to-zero from configmap is true
	//   b) The PA has been active for at least the stable window, after which it
	//			gets marked inactive, and
	//   c) the PA has been backed by the Activator for at least the grace period
	//      of time.
	//  Alternatively, if (a) and the revision did not succeed to activate in
	//  `activationTimeout` time -- also scale it to 0.
	cfgs := config.FromContext(ctx)
	cfgAS := cfgs.Autoscaler

	if !cfgAS.EnableScaleToZero {
		return 1, true
	}
	cfgD := cfgs.Deployment
	var activationTimeout time.Duration
	if progressDeadline, ok := pa.ProgressDeadline(); ok {
		activationTimeout = progressDeadline + activationTimeoutBuffer
	} else {
		activationTimeout = cfgD.ProgressDeadline + activationTimeoutBuffer
	}

	now := time.Now()
	logger := logging.FromContext(ctx)
	switch {
	case pa.Status.IsActivating(): // Active=Unknown
		// If we are stuck activating for longer than our progress deadline, presume we cannot succeed and scale to 0.
		if pa.Status.CanFailActivation(now, activationTimeout) {
			logger.Info("Activation has timed out after ", activationTimeout)
			return desiredScale, true
		}
		ks.enqueueCB(pa, activationTimeout)
		return scaleUnknown, false
	case pa.Status.IsActive(): // Active=True
		// Don't scale-to-zero if the PA is active
		// but return `(0, false)` to mark PA inactive, instead.
		sw := aresources.StableWindow(pa, cfgAS)
		af := pa.Status.ActiveFor(now)
		if af >= sw {
			// If SKS is in proxy mode, then there is high probability
			// of SKS not changing its spec/status and thus not triggering
			// a new reconciliation of PA.
			if sks.Spec.Mode == netv1alpha1.SKSOperationModeProxy {
				logger.Debug("SKS is already in proxy mode, auto-re-enqueue PA")
				// Long enough to ensure current iteration is finished.
				ks.enqueueCB(pa, 3*time.Second)
			}
			logger.Info("Can deactivate PA, was active for ", af)
			return desiredScale, false
		}
		// Otherwise, scale down to at most 1 for the remainder of the idle period and then
		// reconcile PA again.
		logger.Infof("Sleeping additionally for %v before can scale to 0", sw-af)
		ks.enqueueCB(pa, sw-af)
		return 1, true
	default: // Active=False
		var (
			err error
			r   = true
		)

		if resolveTBC(ctx, pa) != -1 {
			// if TBC is -1 activator is guaranteed to already be in the path.
			// Otherwise, probe to make sure Activator is in path.
			r, err = ks.activatorProbe(pa, ks.transport)
			logger.Infof("Probing activator = %v, err = %v", r, err)
		}

		if r {
			// This enforces that the revision has been backed by the Activator for at least
			// ScaleToZeroGracePeriod time.
			// And at least ScaleToZeroPodRetentionPeriod since PA became inactive.

			// Most conservative check, if it passes we're good.
			lastPodTimeout := lastPodRetention(pa, cfgAS)
			lastPodMaxTimeout := durationMax(cfgAS.ScaleToZeroGracePeriod, lastPodTimeout)
			// If we have been inactive for this long, we can scale to 0!
			if pa.Status.InactiveFor(now) >= lastPodMaxTimeout {
				return desiredScale, true
			}

			// Now check last pod retention timeout. Since it's a hard deadline, regardless
			// of network programming state we should circle back after that time period.
			if lastPodTimeout > 0 {
				if inactiveTime := pa.Status.InactiveFor(now); inactiveTime < lastPodTimeout {
					logger.Infof("Can't scale to 0; InactiveFor %v < ScaleToZeroPodRetentionPeriod = %v",
						inactiveTime, lastPodTimeout)
					ks.enqueueCB(pa, lastPodTimeout-inactiveTime)
					return desiredScale, false
				}
				logger.Debug("Last pod timeout satisfied")
			}

			// Otherwise check how long SKS was in proxy mode.
			// Compute the difference between time we've been proxying with the timeout.
			// If it's positive, that's the time we need to sleep, if negative -- we
			// can scale to zero.
			pf := sks.Status.ProxyFor()
			to := cfgAS.ScaleToZeroGracePeriod - pf
			if to <= 0 {
				logger.Info("Fast path scaling to 0, in proxy mode for: ", pf)
				return desiredScale, true
			}

			// Re-enqueue the PA for reconciliation with timeout of `to` to make sure we wait
			// long enough.
			logger.Info("Enqueueing PA after ", to)
			ks.enqueueCB(pa, to)
			return desiredScale, false
		}

		// Otherwise (any prober failure) start the async probe.
		logger.Info("PA is not yet backed by activator, cannot scale to zero")
		if !ks.probeManager.Offer(context.Background(), paToProbeTarget(pa), pa, probePeriod, probeTimeout, probeOptions...) {
			logger.Info("Probe for revision is already in flight")
		}
		return desiredScale, false
	}
}

func (ks *scaler) applyScale(ctx context.Context, pa *autoscalingv1alpha1.PodAutoscaler, desiredScale int32,
	ps *autoscalingv1alpha1.PodScalable) error {
	logger := logging.FromContext(ctx)

	gvr, name, err := resources.ScaleResourceArguments(pa.Spec.ScaleTargetRef)
	if err != nil {
		return err
	}

	psNew := ps.DeepCopy()
	psNew.Spec.Replicas = &desiredScale
	patch, err := duck.CreatePatch(ps, psNew)
	if err != nil {
		return err
	}
	patchBytes, err := patch.MarshalJSON()
	if err != nil {
		return err
	}

	_, err = ks.dynamicClient.Resource(*gvr).Namespace(pa.Namespace).Patch(ctx, ps.Name, types.JSONPatchType,
		patchBytes, metav1.PatchOptions{})
	if err != nil {
		return fmt.Errorf("failed to apply scale %d to scale target %s: %w", desiredScale, name, err)
	}

	logger.Debug("Successfully scaled to ", desiredScale)
	return nil
}

// scale attempts to scale the given PA's target reference to the desired scale.
func (ks *scaler) scale(ctx context.Context, pa *autoscalingv1alpha1.PodAutoscaler, sks *netv1alpha1.ServerlessService, desiredScale int32) (int32, error) {
	asConfig := config.FromContext(ctx).Autoscaler
	logger := logging.FromContext(ctx)

	if desiredScale < 0 && !pa.Status.IsActivating() {
		logger.Debug("Metrics are not yet being collected.")
		return desiredScale, nil
	}

	min, max := pa.ScaleBounds(asConfig)
	initialScale := kparesources.GetInitialScale(asConfig, pa)
	// Log reachability as quoted string, since default value is "".
	logger.Debugf("MinScale = %d, MaxScale = %d, InitialScale = %d, DesiredScale = %d Reachable = %q",
		min, max, initialScale, desiredScale, pa.Spec.Reachability)
	// If initial scale has been attained, ignore the initialScale altogether.
	if initialScale > 1 && !pa.Status.IsScaleTargetInitialized() {
		// Ignore initial scale if minScale >= initialScale.
		if min < initialScale {
			logger.Debugf("Adjusting min to meet the initial scale: %d -> %d", min, initialScale)
		}
		min = intMax(initialScale, min)
	}
	if newScale := applyBounds(min, max, desiredScale); newScale != desiredScale {
		logger.Debugf("Adjusting desiredScale to meet the min and max bounds before applying: %d -> %d", desiredScale, newScale)
		desiredScale = newScale
	}

	desiredScale, shouldApplyScale := ks.handleScaleToZero(ctx, pa, sks, desiredScale)
	if !shouldApplyScale {
		return desiredScale, nil
	}

	ps, err := resources.GetScaleResource(pa.Namespace, pa.Spec.ScaleTargetRef, ks.listerFactory)
	if err != nil {
		return desiredScale, fmt.Errorf("failed to get scale target %v: %w", pa.Spec.ScaleTargetRef, err)
	}

	currentScale := int32(1)
	if ps.Spec.Replicas != nil {
		currentScale = *ps.Spec.Replicas
	}
	if desiredScale == currentScale {
		return desiredScale, nil
	}

	logger.Infof("Scaling from %d to %d", currentScale, desiredScale)
	return desiredScale, ks.applyScale(ctx, pa, desiredScale, ps)
}


text:
package com.InfinityRaider.AgriCraft.compatibility.minetweaker;

import com.InfinityRaider.AgriCraft.blocks.BlockModPlant;
import com.InfinityRaider.AgriCraft.farming.CropProduce;
import com.InfinityRaider.AgriCraft.handler.ConfigurationHandler;
import com.InfinityRaider.AgriCraft.items.ItemModSeed;
import com.InfinityRaider.AgriCraft.utility.LogHelper;
import com.InfinityRaider.AgriCraft.utility.OreDictHelper;
import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IItemStack;
import minetweaker.api.minecraft.MineTweakerMC;
import minetweaker.mc1710.item.MCItemStack;
import minetweaker.mc1710.oredict.MCOreDictEntry;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import stanhebben.zenscript.annotations.ZenClass;
import stanhebben.zenscript.annotations.ZenMethod;

@ZenClass("mods.agricraft.CropProduct")
public class CropProduct {

    @ZenMethod
    public static void add(IItemStack seed, IItemStack fruit, int weight) {
        ItemStack seedToChange = MineTweakerMC.getItemStack(seed);
        ItemStack fruitToAdd = MineTweakerMC.getItemStack(fruit);
        String error = "Invalid Seed";
        boolean success = seedToChange!=null && seedToChange.getItem()!=null && seedToChange.getItem() instanceof ItemModSeed;
        if(success) {
            BlockModPlant crop = ((ItemModSeed) seedToChange.getItem()).getPlant();
            MineTweakerAPI.apply(new AddAction(crop, fruitToAdd, weight));
        }
        if(!success) {
            MineTweakerAPI.logError("Adding fruit: '"+fruitToAdd.getDisplayName()+"' to '"+seedToChange.getDisplayName()+"' failed: "+error);
        }
    }

    @ZenMethod
    public static void remove(IItemStack seed, IItemStack fruit) {
        ItemStack seedToChange = MineTweakerMC.getItemStack(seed);
        ItemStack fruitToRemove = MineTweakerMC.getItemStack(fruit);
        String error = "Invalid Seed";
        boolean success = seedToChange!=null && seedToChange.getItem()!=null && seedToChange.getItem() instanceof ItemModSeed;
        if(success) {
            BlockModPlant crop = ((ItemModSeed) seedToChange.getItem()).getPlant();
            MineTweakerAPI.apply((new RemoveAction(crop, fruitToRemove)));
        }
        if(!success) {
            MineTweakerAPI.logError("Removing fruit: '"+fruitToRemove.getDisplayName()+"' from '"+seedToChange.getDisplayName()+"' failed: "+error);
        }
    }

    private static class AddAction implements IUndoableAction {
        private BlockModPlant crop;
        private ItemStack fruit;
        private int weight;
        public AddAction(BlockModPlant crop, ItemStack fruitToAdd, int weight) {
            this.crop = crop;
            this.fruit = fruitToAdd.copy();
            this.fruit.stackSize = 1;
            this.weight=weight>0?weight: CropProduce.DEFAULT_WEIGHT;
        }

        @Override
        public void apply() {
            crop.products.addProduce(fruit, weight);
            String oreDictTag = this.fruitTag();
            LogHelper.debug("Registering "+fruit.getDisplayName()+" to the ore dictionary as "+oreDictTag);
            if(ConfigurationHandler.registerCropProductsToOreDict && !OreDictHelper.hasOreId(fruit, oreDictTag)) {
                OreDictionary.registerOre(oreDictTag, fruit);
            }
        }

        @Override
        public boolean canUndo() {
            return true;
        }

        @Override
        public void undo() {
            crop.products.removeProduce(fruit);
            if(ConfigurationHandler.registerCropProductsToOreDict) {
                MCOreDictEntry ore = new MCOreDictEntry(this.fruitTag());
                ore.remove(new MCItemStack(this.fruit));
            }
        }

        @Override
        public String describe() {
            return "Adding fruit: '"+fruit.getDisplayName()+"' to '"+crop.getUnlocalizedName()+"' with weight "+weight;
        }

        @Override
        public String describeUndo() {
            return "Removing previously added fruit'"+fruit.getDisplayName()+"' from '"+crop.getUnlocalizedName()+"'";
        }

        @Override
        public Object getOverrideKey() {
            return null;
        }

        private String fruitTag() {
            return crop.getUnlocalizedName().substring(crop.getUnlocalizedName().indexOf(':')+1);
        }
    }

    private static class RemoveAction implements IUndoableAction {
        private BlockModPlant crop;
        private ItemStack fruit;
        private int weight;
        public RemoveAction(BlockModPlant crop, ItemStack fruit) {
            this.crop = crop;
            this.fruit = fruit.copy();
            this.fruit.stackSize = 1;
            this.weight = crop.products.getWeight(this.fruit);
        }

        @Override
        public void apply() {
            crop.products.removeProduce(fruit);
            if(ConfigurationHandler.registerCropProductsToOreDict) {
                MCOreDictEntry ore = new MCOreDictEntry(this.fruitTag());
                ore.remove(new MCItemStack(this.fruit));
            }
        }

        @Override
        public boolean canUndo() {
            return true;
        }

        @Override
        public void undo() {
            crop.products.addProduce(fruit, weight);
            String oreDictTag = this.fruitTag();
            LogHelper.debug("Registering " + fruit.getDisplayName() + " to the ore dictionary as " + oreDictTag);
            if(ConfigurationHandler.registerCropProductsToOreDict && !OreDictHelper.hasOreId(fruit, oreDictTag)) {
                OreDictionary.registerOre(oreDictTag, fruit);
            }
        }

        @Override
        public String describe() {
            return "Removing fruit '"+fruit.getDisplayName()+"' from '"+crop.getUnlocalizedName()+"'";
        }

        @Override
        public String describeUndo() {
            return "Adding previously removed fruit'"+fruit.getDisplayName()+"' from '"+crop.getUnlocalizedName()+"'";
        }

        @Override
        public Object getOverrideKey() {
            return null;
        }

        private String fruitTag() {
            return crop.getUnlocalizedName().substring(crop.getUnlocalizedName().indexOf(':')+1);
        }
    }
}


text:
package org.apache.hadoop.yarn.sls.appmaster;

import com.codahale.metrics.MetricRegistry;
import org.apache.commons.io.FileUtils;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager;
import org.apache.hadoop.yarn.sls.conf.SLSConfiguration;
import org.apache.hadoop.yarn.sls.scheduler.ContainerSimulator;
import org.apache.hadoop.yarn.sls.scheduler.FairSchedulerMetrics;
import org.apache.hadoop.yarn.sls.scheduler.SchedulerWrapper;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class TestAMSimulator {
  private ResourceManager rm;
  private YarnConfiguration conf;
  private Path metricOutputDir;

  @Before
  public void setup() {
    createMetricOutputDir();

    conf = new YarnConfiguration();
    conf.set(SLSConfiguration.METRICS_OUTPUT_DIR, metricOutputDir.toString());
    conf.set(YarnConfiguration.RM_SCHEDULER,
        "org.apache.hadoop.yarn.sls.scheduler.ResourceSchedulerWrapper");
    conf.set(SLSConfiguration.RM_SCHEDULER,
        "org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FairScheduler");
    conf.setBoolean(SLSConfiguration.METRICS_SWITCH, true);
    rm = new ResourceManager();
    rm.init(conf);
    rm.start();
  }

  class MockAMSimulator extends AMSimulator {
    @Override
    protected void processResponseQueue()
        throws InterruptedException, YarnException, IOException {
    }

    @Override
    protected void sendContainerRequest()
        throws YarnException, IOException, InterruptedException {
    }

    @Override
    protected void checkStop() {
    }
  }

  private void verifySchedulerMetrics(String appId) {
    SchedulerWrapper schedulerWrapper = (SchedulerWrapper)
        rm.getResourceScheduler();
    MetricRegistry metricRegistry = schedulerWrapper.getMetrics();
    for (FairSchedulerMetrics.Metric metric :
        FairSchedulerMetrics.Metric.values()) {
      String key = "variable.app." + appId + "." + metric.getValue()
          + ".memory";
      Assert.assertTrue(metricRegistry.getGauges().containsKey(key));
      Assert.assertNotNull(metricRegistry.getGauges().get(key).getValue());
    }
  }

  private void createMetricOutputDir() {
    Path testDir = Paths.get(System.getProperty("test.build.data"));
    try {
      metricOutputDir = Files.createTempDirectory(testDir, "output");
    } catch (IOException e) {
      Assert.fail(e.toString());
    }
  }

  private void deleteMetricOutputDir() {
    try {
      FileUtils.deleteDirectory(metricOutputDir.toFile());
    } catch (IOException e) {
      Assert.fail(e.toString());
    }
  }

  @Test
  public void testAMSimulator() throws Exception {
    // Register one app
    MockAMSimulator app = new MockAMSimulator();
    String appId = "app1";
    String queue = "default";
    List<ContainerSimulator> containers = new ArrayList<>();
    app.init(1, 1000, containers, rm, null, 0, 1000000L, "user1", queue,
        true, appId);
    app.firstStep();

    verifySchedulerMetrics(appId);

    Assert.assertEquals(1, rm.getRMContext().getRMApps().size());
    Assert.assertNotNull(rm.getRMContext().getRMApps().get(app.appId));

    // Finish this app
    app.lastStep();
  }

  @After
  public void tearDown() {
    rm.stop();

    deleteMetricOutputDir();
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="MaterialTabHost">

        <attr name="hasIcons" format="boolean" />

    </declare-styleable>

</resources>


text:
<!doctype html>

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

Generating...

<button>Ting</button>

    <canvas id="canvas" width="300" height="300"></canvas>


text:
@implementation SpaceExampleOpenGLTests

- (void) setUp {
    [super setUp];
}

- (void) tearDown {
    [super tearDown];
}

- (void) testExample {
    STFail(@"Unit tests are not implemented yet in SpaceExampleOpenGLTests");
}

@end


text:
<?php

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20170212180613 extends AbstractMigration
{
    /**
     * @param Schema $schema
     */
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('CREATE TABLE cart (id INT AUTO_INCREMENT NOT NULL, created DATETIME NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
        $this->addSql('CREATE TABLE cart_product (cart_id INT NOT NULL, product_id INT NOT NULL, INDEX IDX_2890CCAA1AD5CDBF (cart_id), INDEX IDX_2890CCAA4584665A (product_id), PRIMARY KEY(cart_id, product_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
        $this->addSql('CREATE TABLE product (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, price NUMERIC(10, 2) NOT NULL, created DATETIME NOT NULL, UNIQUE INDEX UNIQ_D34A04AD5E237E06 (name), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
        $this->addSql('ALTER TABLE cart_product ADD CONSTRAINT FK_2890CCAA1AD5CDBF FOREIGN KEY (cart_id) REFERENCES cart (id) ON DELETE CASCADE');
        $this->addSql('ALTER TABLE cart_product ADD CONSTRAINT FK_2890CCAA4584665A FOREIGN KEY (product_id) REFERENCES product (id) ON DELETE CASCADE');
    }

    /**
     * @param Schema $schema
     */
    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE cart_product DROP FOREIGN KEY FK_2890CCAA1AD5CDBF');
        $this->addSql('ALTER TABLE cart_product DROP FOREIGN KEY FK_2890CCAA4584665A');
        $this->addSql('DROP TABLE cart');
        $this->addSql('DROP TABLE cart_product');
        $this->addSql('DROP TABLE product');
    }
}


text:
In 2014, I did some benchmarking of variant effect prediction algorithms. You can read about that in this [blog post](http://blog.goldenhelix.com/ajesaitis/the-sate-of-variant-annotation-a-comparison-of-annovar-snpeff-and-vep/).

I wanted to follow up on that work and see how the current batch of algorithms are preforming. [VEP](http://uswest.ensembl.org/info/docs/tools/vep/index.html) and [SnpEff](http://snpeff.sourceforge.net/) are the most commonly used algorithms these days, so I limited my analysis to them.

I used the same input VCF that I created originally. It contains all snps, all 1 base pair insertions and deletions, and 2 possible 2 and 3 base pair insertions and deletions at all locations spanning the CFTR gene with 100bp margins on either side.

You can annotate this vcf with each algorithm using the CWL scripts provided.

For VEP:

```
docker build --tag="andrewjesaitis/vep" -f Dockerfile.vep .
cwltool vep-workflow.cwl cftr-job-vep.yml
```

Similarly for SnpEff:

```
docker build --tag="andrewjesaitis/snpeff" -f Dockerfile.snpeff .
cwltool snpeff-workflow.cwl cftr-job-snpeff.yml
```

Then you can open the Jupyter Notebook and rerun all cells.

Otherwise just skip to the punchline and [open the notebook](https://github.com/andrewjesaitis/variant-annotation-comparison-2017/blob/master/Variant-Annotation-Comparsion-2017.ipynb) on Github.

I've written up a discussion of the results and dug into some particularly troublesome variants on [my blog](http://andrewjesaitis.com/2017/03/the-state-of-variant-annotation-in-2017/).

I've also added the gzip'd vcf that highligh some mismatches. Note that these vcfs contain repeated variants (since I am outputing a single variant-transcript pair per line). The keys in the `INFO` field are self documenting. These files are `impact_mismatch.vcf.gz`, `effect_mismatch.vcf.gz`, and `hgvs_mismatch.vcf.gz`.


text:
<?php
/**
 */
class NewsItemTable extends PackageNewsItemTable
{

}


text:
@interface PodViewController : UIViewController

// Method to Update the FadeOut View
- (void) fadeOut:(UIView *)animationView timeInterval:(NSTimeInterval)timeDuration timeDelay:(NSTimeInterval)timeDelay fadeOutValue:(CGFloat) fadeOutOpacity;

// Method to Update the FadeIn View
- (void) fadeIn:(UIView *)animationView timeInterval:(NSTimeInterval)timeDuration timeDelay:(NSTimeInterval)timeDelay fadeOutValue:(CGFloat) fadeOutOpacity;

// Method to Perform FadeOut Operations
-(void) fadeOperation:(UIView *) animationView WithTimeInterval:(NSTimeInterval) timeDuration WithTImeDelay:(NSTimeInterval) timeDelay fadeOutStartingValue:(CGFloat ) fadeOutStartingOpacity fadeOutEndingValue:(CGFloat) fadeOutEndingOpacity;

@end


text:
var loadGraph = require('./lib/loadGraph.js');
var graph = loadGraph(process.argv[2] || 'graph.out');

var save = require('ngraph.tobinary');
save(graph, { outDir: './data' });

console.log('Done.');
console.log('Copy `links.bin`, `labels.bin` and positions.bin into vis folder');


text:
<?php
namespace oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2;

/**
 * @xmlNamespace urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2
 * @xmlType CommodityCodeType
 * @xmlName CommodityCode
 * @var oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2\CommodityCode
 */
class CommodityCode extends CommodityCodeType
{
} // end class CommodityCode


text:
layout: post
title: OVERSTUFFED 6 - Scene 1
titleinfo: pornvd
desc: Watch OVERSTUFFED 6 - Scene 1. Pornhub is the ultimate xxx porn and sex site.
---

OVERSTUFFED 6 - Scene 1

Watch OVERSTUFFED 6 - Scene 1. Pornhub is the ultimate xxx porn and sex site.


text: Initial release of os-nginx


text:
define(["require", "exports", './move', './moves'], function (require, exports, move_1, moves_1) {
    var Chessboard = (function () {
        function Chessboard(moveHistory, executeMove) {
            if (executeMove === void 0) { executeMove = false; }
            this.moveHistory = moveHistory;
            this._fields = [
                [-2, -3, -4, -5, -6, -4, -3, -2],
                [-1, -1, -1, -1, -1, -1, -1, -1],
                [0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0],
                [1, 1, 1, 1, 1, 1, 1, 1],
                [2, 3, 4, 5, 6, 4, 3, 2]
            ];
            this.capturedPieces = new Array();
            this._isWhitePlaying = true;
            this.whiteKingHasMoved = false;
            this.whiteLeftRookHasMoved = false;
            this.whiteRightRookHasMoved = false;
            this.blackKingHasMoved = false;
            this.blackLeftRookHasMoved = false;
            this.blackRightRookHasMoved = false;
            this.enPassantCol = -1;
            this._moves = new moves_1.Moves(this);
        }
        Object.defineProperty(Chessboard.prototype, "moves", {
            get: function () { return this._moves; },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Chessboard.prototype, "check", {
            get: function () { return this._moves.check; },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Chessboard.prototype, "checkMate", {
            get: function () { return this._moves.checkMate; },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Chessboard.prototype, "staleMate", {
            get: function () { return this._moves.staleMate; },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Chessboard.prototype, "ownCheck", {
            get: function () { return this._moves.ownCheck; },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Chessboard.prototype, "ownCheckMate", {
            get: function () { return this._moves.ownCheckMate; },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Chessboard.prototype, "isWhitePlaying", {
            get: function () { return this._isWhitePlaying; },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Chessboard.prototype, "fields", {
            get: function () {
                return this._fields;
            },
            enumerable: true,
            configurable: true
        });
        Chessboard.prototype.ownThreats = function (row, col) {
            return this._moves.ownThreats[row][col];
        };
        Chessboard.prototype.opponentThreats = function (row, col) {
            return this._moves.opponentThreats[row][col];
        };
        Chessboard.prototype.isLegalMove = function (fromRow, fromCol, toRow, toCol) {
            var piece = this.fields[fromRow][fromCol];
            if (this.isWhitePlaying) {
                if (piece < 0)
                    return false;
            }
            else {
                if (piece > 0)
                    return false;
            }
            var targetPiece = this.fields[toRow][toCol];
            if (this.isWhitePlaying) {
                if (targetPiece > 0)
                    return false;
            }
            else {
                if (targetPiece < 0)
                    return false;
            }
            if (targetPiece > 0 && piece > 0)
                return false;
            if (targetPiece < 0 && piece < 0)
                return false;
            return this._moves.isLegalMove(fromRow, fromCol, toRow, toCol);
        };
        Chessboard.prototype.moveInternally = function (fromRow, fromCol, toRow, toCol, promotion) {
            var original_whiteKingHasMoved = this.whiteKingHasMoved;
            var original_whiteLeftRookHasMoved = this.whiteLeftRookHasMoved;
            var original_whiteRightRookHasMoved = this.whiteRightRookHasMoved;
            var original_blackKingHasMoved = this.blackKingHasMoved;
            var original_blackLeftRookHasMoved = this.blackLeftRookHasMoved;
            var original_blackRightRookHasMoved = this.blackRightRookHasMoved;
            var original_enPassantCol = this.enPassantCol;
            var piece = this.fields[fromRow][fromCol];
            var targetPiece = this.fields[toRow][toCol];
            var captureRow = toRow;
            this.fields[fromRow][fromCol] = 0;
            this.fields[toRow][toCol] = piece;
            this._isWhitePlaying = !this._isWhitePlaying;
            if (piece == 1 && fromRow == 1 && toRow == 0) {
                this.fields[toRow][toCol] = promotion;
            }
            else if (piece == -1 && fromRow == 6 && toRow == 7) {
                this.fields[toRow][toCol] = promotion;
            }
            else
                promotion = 0;
            this.enPassantCol = -1;
            if (piece == 1 && fromRow - toRow == 2) {
                this.enPassantCol = toCol;
            }
            if ((piece == 1 || piece == -1) && targetPiece == 0 && fromCol != toCol) {
                targetPiece = this.fields[fromRow][toCol];
                this.fields[fromRow][toCol] = 0;
                captureRow = fromRow;
            }
            var secondColFrom = -1;
            var secondColTo = -1;
            if (piece == -1 && fromRow - toRow == -2) {
                this.enPassantCol = toCol;
            }
            if (piece == 6) {
                this.whiteKingHasMoved = true;
                if (fromCol - toCol == 2) {
                    this.fields[fromRow][0] = 0;
                    this.fields[fromRow][3] = 2;
                    secondColFrom = 0;
                    secondColTo = 3;
                }
                else if (fromCol - toCol == -2) {
                    this.fields[fromRow][7] = 0;
                    this.fields[fromRow][5] = 2;
                    secondColFrom = 7;
                    secondColTo = 5;
                }
            }
            if (piece == -6) {
                this.blackKingHasMoved = true;
                if (fromCol - toCol == 2) {
                    this.fields[fromRow][0] = 0;
                    this.fields[fromRow][3] = -2;
                    secondColFrom = 0;
                    secondColTo = 3;
                }
                else if (fromCol - toCol == -2) {
                    this.fields[fromRow][7] = 0;
                    this.fields[fromRow][5] = -2;
                    secondColFrom = 7;
                    secondColTo = 5;
                }
            }
            if (piece == 2 && fromRow == 7 && fromCol == 0)
                this.whiteLeftRookHasMoved = true;
            if (piece == 2 && fromRow == 7 && fromCol == 7)
                this.whiteRightRookHasMoved = true;
            if (piece == -2 && fromRow == 0 && fromCol == 0)
                this.blackLeftRookHasMoved = true;
            if (piece == -2 && fromRow == 0 && fromCol == 7)
                this.blackRightRookHasMoved = true;
            this.moveHistory.push(new move_1.Move(fromRow, fromCol, toRow, toCol, promotion, targetPiece, original_whiteKingHasMoved, original_whiteLeftRookHasMoved, original_whiteRightRookHasMoved, original_blackKingHasMoved, original_blackLeftRookHasMoved, original_blackRightRookHasMoved, original_enPassantCol, captureRow, secondColFrom, secondColTo, this._moves));
            return targetPiece;
        };
        Chessboard.prototype.move = function (fromRow, fromCol, toRow, toCol, promotion) {
            var targetPiece = this.moveInternally(fromRow, fromCol, toRow, toCol, promotion);
            this.recalculateLegalMovesAndCheck();
            var move = this.moveHistory[this.moveHistory.length - 1];
            move.check = this._moves.ownCheck;
            move.checkMate = this._moves.ownCheckMate;
            move.staleMate = this._moves.staleMate;
            if (0 != targetPiece) {
                this.capturedPieces.push(targetPiece);
            }
            this.recalculateLegalMovesAndCheck();
        };
        Chessboard.prototype.recalculateLegalMovesAndCheck = function () {
            this._moves = new moves_1.Moves(this);
        };
        Chessboard.prototype.revertLastMoveInternally = function () {
            if (this.moveHistory.length == 0) {
                alert("Nothing to revert!");
            }
            else {
                var lastMove = this.moveHistory.pop();
                var piece = this.fields[lastMove.toRow][lastMove.toCol];
                if (lastMove.promotion > 1) {
                    if (piece > 0)
                        piece = 1;
                    else
                        piece = -1;
                }
                this.fields[lastMove.fromRow][lastMove.fromCol] = piece;
                this.fields[lastMove.toRow][lastMove.toCol] = 0;
                this.fields[lastMove.captureRow][lastMove.toCol] = lastMove.capture;
                this._isWhitePlaying = !this._isWhitePlaying;
                this.whiteKingHasMoved = lastMove.whiteKingHasMoved;
                this.whiteLeftRookHasMoved = lastMove.whiteLeftRookHasMoved;
                this.whiteRightRookHasMoved = lastMove.whiteRightRookHasMoved;
                this.blackKingHasMoved = lastMove.blackKingHasMoved;
                this.blackLeftRookHasMoved = lastMove.blackLeftRookHasMoved;
                this.blackRightRookHasMoved = lastMove.blackRightRookHasMoved;
                this.enPassantCol = lastMove.enPassantCol;
                this._moves = lastMove.legalMoves;
                if (lastMove.secondColTo > 0) {
                    this.fields[lastMove.fromRow][lastMove.secondColFrom] = this.fields[lastMove.toRow][lastMove.secondColTo];
                    this.fields[lastMove.toRow][lastMove.secondColTo] = 0;
                }
            }
            return lastMove.capture;
        };
        Chessboard.prototype.revertLastMove = function () {
            var capturedPiece = this.revertLastMoveInternally();
            if (0 != capturedPiece)
                this.capturedPieces.pop();
        };
        return Chessboard;
    })();
    exports.Chessboard = Chessboard;
});
//# sourceMappingURL=chessboard.js.map


text:
import sys
import os
from path import Path as path
import sys
import mock

MOCK_MODULES = [
    'webob',
    'lxml'
]

for mod_name in MOCK_MODULES:
    sys.modules[mod_name] = mock.Mock(class_that_is_extended=object)

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('..'))

# -- General configuration -----------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.coverage',
    'sphinx.ext.ifconfig',
    'sphinx.ext.todo',
    'sphinxcontrib.napoleon',
]

# The suffix of source filenames.
source_suffix = '.rst'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'XBlock API Guide'
copyright = u'2015, edX.org'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.4'
# The full version, including alpha/beta/rc tags.
#release = '0.3'

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []

# When auto-doc'ing a class, write the class' docstring and the __init__ docstring
# into the class docs.
autoclass_content = "both"

# Warn about unresolvable references, but not all of them.
nitpicky = True
nitpick_ignore = [
    ('py:obj', 'str'),
    ('py:obj', 'string'),
]

# -- Options for HTML output ---------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#html_theme = 'pyramid'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
#html_title = None

# A shorter title for the navigation bar.  Default is the same as html_title.
#html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
#html_static_path = ['_static']

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}

# If false, no module index is generated.
#html_domain_indices = True

# If false, no index is generated.
#html_use_index = False

# If true, the index is split into individual pages for each letter.
#html_split_index = False

# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None

# Output file base name for HTML help builder.
#htmlhelp_basename = 'XBlockdoc'

# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False

# If true, show page references after internal links.
#latex_show_pagerefs = False

# If true, show URL addresses after external links.
#latex_show_urls = False

# Documents to append as an appendix to all manuals.
#latex_appendices = []

# If false, no module index is generated.
#latex_domain_indices = True

on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
if not on_rtd:  # only import and set the theme if we're building docs locally
    import sphinx_rtd_theme
    html_theme = 'sphinx_rtd_theme'
    html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]

# Documents to append as an appendix to all manuals.
#texinfo_appendices = []

# If false, no module index is generated.
#texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'

exclude_patterns = ['api/*', 'links.rst']


text:
package calico.utils;

import java.awt.Color;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.fileupload.MultipartStream;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpRequest;

// TODO: The parser should only look for the byte of '\r' and use that to get the boundary, instead of parsing the whole request

// Parse the uploads to the admin server. stupid java cant be bothered to easily do it on its own.
public class CalicoUploadParser
{
	public class Filedata
	{
		private String name = "";
		private String contentType = "application/octet-stream";
		private byte[] data = null;

		public Filedata(String name, String contentType, byte[] data)
		{
			this.contentType = contentType;
			this.data = data;
			this.name = name;
		}

		public String getName()
		{
			return this.name;
		}
		public String getContentType()
		{
			return this.contentType;
		}
		public byte[] getData()
		{
			return this.data;
		}
		public String toString()
		{
			return "File: "+this.name+" ["+this.contentType+"] "+this.data.length+" bytes";
		}
	}

	private HashMap<String, Filedata> fileFields = new HashMap<String, Filedata>();

	private byte[] data = null;
	private byte[] boundary = null;

	private Properties params = new Properties();
	private Properties fileInfo = new Properties();

	private byte[] fileData = null;

	// used to match color strings
	private static Pattern parse_param = Pattern.compile("Content-Disposition: form-data; name=\"([^\"]+)\"");
	private static Pattern parse_file_param = Pattern.compile("Content-Disposition: form-data; name=\"([^\"]+)\"; filename=\"([^\"]+)\"\\s+Content-Type: ([-a-z0-9/]+)");

	public CalicoUploadParser(byte[] data)
	{
		this.data = data;
	}
	public CalicoUploadParser(byte[] data, final HttpRequest request)
	{
		this.data = data;

		String contentType = request.getFirstHeader("Content-Type").getValue();
		int boundaryIndex = contentType.indexOf("boundary=");
		this.boundary = (contentType.substring(boundaryIndex + 9)).getBytes();

	}

	public Properties getParams()
	{
		return this.params;
	}

	public byte[] getFileData()
	{
		return this.fileData;
	}

	public Filedata getFile(String file)
	{
		return this.fileFields.get(file);
	}

	public void parse() throws IOException
	{

		ByteArrayInputStream input = new ByteArrayInputStream(this.data);
		MultipartStream multipartStream = new MultipartStream(input, this.boundary);

		boolean nextPart = multipartStream.skipPreamble();
		while(nextPart)
		{
			String headers = multipartStream.readHeaders().replaceAll("\r", " ").replaceAll("\n", " ");
			System.out.println("Headers: [" + headers+"]");

			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			multipartStream.readBodyData(baos);

			Matcher param = parse_file_param.matcher(headers);
			if(param.find())
			{
				String pname = param.group(1);
				String filename = param.group(2);
				String contenttype = param.group(3);

				System.out.println("Pname="+pname+"|Filename="+filename+"|CType:"+contenttype);

				this.fileFields.put(pname, new Filedata(filename, contenttype, baos.toByteArray()));

			}
			else
			{

				Matcher param2 = parse_param.matcher(headers);
				if(param2.find())
				{
					this.params.setProperty(param2.group(1), new String(baos.toByteArray()) );
				}

			}

			//this.fileData = baos.toByteArray();

			//System.out.println();

			nextPart = multipartStream.readBoundary();
		}

		/*
		-----------------------------9849436581144108930470211272
Content-Disposition: form-data; name="testvar"

testvalue
-----------------------------9849436581144108930470211272
Content-Disposition: form-data; name="Filedata"; filename="1TB_SAS_HDD.pdf"
Content-Type: application/pdf

%PDF-1.5
...
-----------------------------9849436581144108930470211272--

		 */
		/*
		String strData = new String(data);
		String eol = new String("\r\n");
		String eol2 = new String("\r\n\r\n");

		String[] boundaryarr = strData.split(eol, 2);

		String boundary = boundaryarr[0].trim();

		String[] parts = strData.split(boundary);

		// http://www.oreillynet.com/onjava/blog/2006/06/parsing_formdata_multiparts.html

		for(int i=0;i<parts.length;i++)
		{
			String[] subpart = parts[i].split(eol2,2);
			if(subpart[0].indexOf("Content-Type")!=-1)
			{
				Matcher param = parse_file_param.matcher(subpart[0]);
				if(param.find())
				{
					String pname = param.group(1);
					String value = param.group(2);//subpart[1].trim();
					String filedata = subpart[1];
					StringUtils.stripEnd(filedata, eol);
					this.fileData = filedata.getBytes();

					this.fileInfo.setProperty("type",param.group(3));
					this.fileInfo.setProperty("name",param.group(2));
					this.fileInfo.setProperty("size",Long.toString((long) this.fileData.length));

					System.out.println("NAME: "+pname+"="+value+"|"+param.group(3));
				}
			}
			else
			{

				Matcher param = parse_param.matcher(subpart[0]);
				if(param.find())
				{
					this.params.setProperty(param.group(1), subpart[1].trim());
				}

			}
			//strbuilder.append(parts[i]);
		}
		*/
	}

	public Properties getFileInfo()
	{
		return this.fileInfo;
	}

}


text:
<!DOCTYPE html>

    <title>smartfood | Home</title>
    <meta charset="UTF-8">
    <meta name="author" content="Pooja Harsha">
    <meta name="viewport" content=" width=device-width, initial-scale=1.0">
    <meta name="description" content="This page is my assignments order page/smartfood business order page.">
    <link href="style.css" rel="stylesheet" type="text/css">

            Home
            About Us
            Contact
            What's New
            Support
            FAQ
            Products
            Order
            Jobs
            Multimedia

smARTfood

                cook smarter

 live smarter

Customer Information

                <form name="orderForm" method="post" action="http://itu.lewebcafe.com/sen910/form.php">

                        <fieldset>
                            <legend>Customer Information</legend>

                                First Name:
                                <input type="text" name="fName" id="fName">

                                Last Name:
                                <input type="text" name="lName" id="lName">

                                Street Address:
                                <input type="text" name="address" id="address">

                                City:
                                <input type="text" name="city" id="city">

                                State:
                                <select name="list1" id="stateList">
                                    <option value="" selected="selected">Select a State</option>
                                    <option value="AL">Alabama</option>
                                    <option value="AK">Alaska</option>
                                    <option value="AZ">Arizona</option>
                                    <option value="AR">Arkansas</option>
                                    <option value="CA">California</option>
                                    <option value="CO">Colorado</option>
                                    <option value="CT">Connecticut</option>
                                    <option value="DE">Delaware</option>
                                    <option value="DC">District Of Columbia</option>
                                    <option value="FL">Florida</option>
                                    <option value="GA">Georgia</option>
                                    <option value="HI">Hawaii</option>
                                    <option value="ID">Idaho</option>
                                    <option value="IL">Illinois</option>
                                    <option value="IN">Indiana</option>
                                    <option value="IA">Iowa</option>
                                    <option value="KS">Kansas</option>
                                    <option value="KY">Kentucky</option>
                                    <option value="LA">Louisiana</option>
                                    <option value="ME">Maine</option>
                                    <option value="MD">Maryland</option>
                                    <option value="MA">Massachusetts</option>
                                    <option value="MI">Michigan</option>
                                    <option value="MN">Minnesota</option>
                                    <option value="MS">Mississippi</option>
                                    <option value="MO">Missouri</option>
                                    <option value="MT">Montana</option>
                                    <option value="NE">Nebraska</option>
                                    <option value="NV">Nevada</option>
                                    <option value="NH">New Hampshire</option>
                                    <option value="NJ">New Jersey</option>
                                    <option value="NM">New Mexico</option>
                                    <option value="NY">New York</option>
                                    <option value="NC">North Carolina</option>
                                    <option value="ND">North Dakota</option>
                                    <option value="OH">Ohio</option>
                                    <option value="OK">Oklahoma</option>
                                    <option value="OR">Oregon</option>
                                    <option value="PA">Pennsylvania</option>
                                    <option value="RI">Rhode Island</option>
                                    <option value="SC">South Carolina</option>
                                    <option value="SD">South Dakota</option>
                                    <option value="TN">Tennessee</option>
                                    <option value="TX">Texas</option>
                                    <option value="UT">Utah</option>
                                    <option value="VT">Vermont</option>
                                    <option value="VA">Virginia</option>
                                    <option value="WA">Washington</option>
                                    <option value="WV">West Virginia</option>
                                    <option value="WI">Wisconsin</option>
                                    <option value="WY">Wyoming</option>
                                </select>

                                ZipCode:
                                <input type="text" name="zip" id="zip" maxlength="9">

                                Telephone number:
                                <input type="tel" name="phone" id="phone">

                                Email:
                                <input type="email" name="email" id="email">

                                Credit Card Number:
                                <input type="text" name="cc" id="cc" maxlength="16">

                                Credit Card Type:
                                <select name="list2" id="ccType">
                                    <option value="VISA" selected>VISA</option>
                                    <option value="MasterCard">MasterCard</option>
                                    <option value="AMEX">AMEX</option>
                                    <option value="Discover">Discover</option>
                                </select>

                                Credit Card Expiration:
                                <input type="month" name="month" id="month">

                                Enter your Comments:
                                <textarea name="comments" id="comments" rows="4" cols="35"></textarea>

                        </fieldset>

                        <fieldset>
                            <legend>Product Order</legend>

Order our products below:

                                    Category
                                    Description
                                    Unit price
                                    Quantity
                                    Total price

                                    Book
                                    The new book of soups
                                    $22

                                        <input type="number" name="qty" id="qty" min="0" max="50" step="1">

                                        <input type="text">

                                    The Daniel Plan
                                    $18

                                        <input type="number" name="qty4" id="qty4" min="0" max="50" step="1">

                                        <input type="text">

                                    Subtotal $

                                        <input type="text">

                                    Events
                                    Fit for Life Breakfast Workshop
                                    $20

                                        <input type="number" name="qty2" id="qty2" min="0" max="50" step="1">

                                        <input type="text">

                                    Potluck and Food photography workshop
                                    $15

                                        <input type="number" name="qty3" id="qt3" min="0" max="50" step="1">

                                        <input type="text">

                                    Subtotal $

                                        <input type="text">

                                <button class="btn" type="submit" name="SubmitButton" value="Submit">Submit Form</button>
                                <button class="btn" type="reset" name="ResetButton" value="Reset">Reset Form</button>

                        </fieldset>

                </form>

            Thanks for Visiting!

            Home
            About Us
            Contact
            What's New
            Support
            FAQ
            Products
            Order
            Jobs
            Multimedia


text:
module Users
  class FollowersPresenter < FollowPresenter
    def users
      @users ||= user.followers.paginate(page: @page)
    end

    def title
      "Followers"
    end

    def subtitle
      @subtitle ||= "Your Got #{h.pluralize(user.followers.size, "Followers")}"
    end
  end
end


text:
Portfolio

Lorem ipsum dolor sit amet consectetur.

            {% for project in site.projects %}

{{ project.title }}

{{ project.subtitle }}

            {% endfor %}


text:
namespace Restorant.Data.Migrations
{
    using Models;
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
    {
        public Configuration()
        {
            this.AutomaticMigrationsEnabled = true;

            // TODO: Remove in production
            this.AutomaticMigrationDataLossAllowed = true;
        }

        protected override void Seed(ApplicationDbContext context)
        {
            if (!context.Comments.Any())
            {
                for (int i = 0; i < 18; i++)
                {
                    var currentComment = new CommentForm
                    {
                        Title = $"Comment{i}",
                        Description = $"Automaticly Generated Description Lorem ipsum dolor color {i}",
                    };
                    context.Comments.Add(currentComment);
                }
                context.SaveChanges();
            }
            if (!context.Tables.Any())
            {
                for (int i = 1; i <= 10; i++)
                {
                    var currentTable = new Table
                    {
                        Id = i,
                        NumberOfChairs = 2,
                        IsTaken = false
                    };
                    context.Tables.Add(currentTable);
                }
                for (int i = 10; i <= 20; i++)
                {
                    var currentTable = new Table
                    {
                        Id = i,
                        NumberOfChairs = 4,
                        IsTaken = false
                    };
                    context.Tables.Add(currentTable);
                }
                for (int i = 20; i <= 30; i++)
                {
                    var currentTable = new Table
                    {
                        Id = i,
                        NumberOfChairs = 6,
                        IsTaken = false
                    };
                    context.Tables.Add(currentTable);
                }
                context.SaveChanges();
            }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <dimen name="lib_calendar_day_width">44dp</dimen>
    <dimen name="lib_calendar_day_height">44dp</dimen>

    <dimen name="lib_category_view_padding_startend">5dp</dimen>

    <dimen name="lib_category_size">4dp</dimen>

    <dimen name="lib_category_padding_sides">2dp</dimen>

    <dimen name="lib_category_padding_bottom">2dp</dimen>

    <dimen name="lib_calendar_day_textsize">22dp</dimen>
    <dimen name="lib_calendar_day_padding_sides">2dp</dimen>

    <dimen name="lib_default_title_indicator_text_size">14dp</dimen>
    <dimen name="lib_default_title_indicator_title_padding">4dp</dimen>
    <dimen name="lib_default_title_indicator_top_padding">4dp</dimen>
    <dimen name="lib_default_title_indicator_footer_indicator_height">4dp</dimen>
    <dimen name="lib_default_title_indicator_footer_indicator_underline_padding">20dp</dimen>
    <dimen name="lib_default_title_indicator_footer_padding">4dp</dimen>
    <dimen name="lib_default_title_indicator_clip_padding">4dp</dimen>
</resources>


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ"
    crossorigin="anonymous">
  <link rel="stylesheet" href="node_modules/ng-drag-drop/style.css">
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN"
    crossorigin="anonymous">
  <title>ng-drag-drop Demo</title>

    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault"
      aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">

      </button>

    Angular Drag Drop (ng-drag-drop)

    <demo-app>

      Loading...
    </demo-app>