text:
using System;
using System.Text;
using System.Security.Permissions;
using System.Runtime.Serialization;
using OpenADK.Library;
using OpenADK.Library.Global;
using OpenADK.Library.au.Common;

namespace OpenADK.Library.au.Student{

/// A CalendarDate
/// <remarks>
///
/// <para>Author: Generated by adkgen</para>
/// <para>Version: 2.6</para>
/// <para>Since: 2.3</para>
/// </remarks>
[Serializable]
public class CalendarDate : SifDataObject
{
	///
	/// Creates an instance of a CalendarDate
	///
	public CalendarDate() : base( Adk.SifVersion, StudentDTD.CALENDARDATE ){}

	///
	/// Constructor that accepts values for all mandatory fields
	///
	///<param name="date">A specific school day that occurs within the school year.</param>
	///<param name="calendarSummaryRefId">The ID (GUID) of the calendar summary in which this calendar date is.</param>
	///<param name="schoolInfoRefId">The ID (GUID) of the school for which this calendar information is being reported.</param>
	///<param name="schoolYear">A SchoolYear</param>
	///<param name="calendarDateType">A CalendarDateType</param>
	///
	public CalendarDate( DateTime? date, string calendarSummaryRefId, string schoolInfoRefId, int? schoolYear, CalendarDateType calendarDateType ) : base( Adk.SifVersion, StudentDTD.CALENDARDATE )
	{
		this.Date = date;
		this.CalendarSummaryRefId = calendarSummaryRefId;
		this.SchoolInfoRefId = schoolInfoRefId;
		this.SchoolYear = schoolYear;
		this.CalendarDateType = calendarDateType;
	}

	///
	/// Constructor used by the .Net Serialization formatter
	///
	[SecurityPermission( SecurityAction.Demand, SerializationFormatter=true )]
	protected CalendarDate( SerializationInfo info, StreamingContext context ) : base( info, context ) {}
	///
	/// Gets the metadata fields that make up the key of this object
	///
	/// <value>
	/// an array of metadata fields that make up the object's key
	/// </value>
	public override IElementDef[] KeyFields {
		get { return new IElementDef[] { StudentDTD.CALENDARDATE_DATE, StudentDTD.CALENDARDATE_CALENDARSUMMARYREFID }; }
	}

	///
	/// Gets or sets the value of the <c>Date</c> attribute.
	///
	/// <value> The <c>Date</c> attribute of this object.</value>
	/// <remarks>
	/// <para>The SIF specification defines the meaning of this attribute as: "A specific school day that occurs within the school year."</para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.3</para>
	/// </remarks>
	public DateTime? Date
	{
		get
		{
			return (DateTime?) GetSifSimpleFieldValue( StudentDTD.CALENDARDATE_DATE ) ;
		}
		set
		{
			SetFieldValue( StudentDTD.CALENDARDATE_DATE, new SifDate( value ), value );
		}
	}

	///
	/// Gets or sets the value of the <c>CalendarSummaryRefId</c> attribute.
	///
	/// <value> The <c>CalendarSummaryRefId</c> attribute of this object.</value>
	/// <remarks>
	/// <para>The SIF specification defines the meaning of this attribute as: "The ID (GUID) of the calendar summary in which this calendar date is."</para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.3</para>
	/// </remarks>
	public string CalendarSummaryRefId
	{
		get
		{
			return (string) GetSifSimpleFieldValue( StudentDTD.CALENDARDATE_CALENDARSUMMARYREFID ) ;
		}
		set
		{
			SetFieldValue( StudentDTD.CALENDARDATE_CALENDARSUMMARYREFID, new SifString( value ), value );
		}
	}

	///
	/// Gets or sets the value of the <c><CalendarDateRefId></c> element.
	///
	/// <value> The <c>CalendarDateRefId</c> element of this object.</value>
	/// <remarks>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.6</para>
	/// </remarks>
	public string CalendarDateRefId
	{
		get
		{
			return (string) GetSifSimpleFieldValue( StudentDTD.CALENDARDATE_CALENDARDATEREFID ) ;
		}
		set
		{
			SetFieldValue( StudentDTD.CALENDARDATE_CALENDARDATEREFID, new SifString( value ), value );
		}
	}

	///
	/// Gets or sets the value of the <c><SchoolInfoRefId></c> element.
	///
	/// <value> The <c>SchoolInfoRefId</c> element of this object.</value>
	/// <remarks>
	/// <para>The SIF specification defines the meaning of this element as: "The ID (GUID) of the school for which this calendar information is being reported."</para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.3</para>
	/// </remarks>
	public string SchoolInfoRefId
	{
		get
		{
			return (string) GetSifSimpleFieldValue( StudentDTD.CALENDARDATE_SCHOOLINFOREFID ) ;
		}
		set
		{
			SetFieldValue( StudentDTD.CALENDARDATE_SCHOOLINFOREFID, new SifString( value ), value );
		}
	}

	///
	/// Gets or sets the value of the <c><SchoolYear></c> element.
	///
	/// <value> The <c>SchoolYear</c> element of this object.</value>
	/// <remarks>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.3</para>
	/// </remarks>
	public int? SchoolYear
	{
		get
		{
			return (int?) GetSifSimpleFieldValue( StudentDTD.CALENDARDATE_SCHOOLYEAR ) ;
		}
		set
		{
			SetFieldValue( StudentDTD.CALENDARDATE_SCHOOLYEAR, new SifInt( value ), value );
		}
	}

	///Sets the value of the <c><CalendarDateType></c> element.
	/// <param name="Code">Code indicating the type of school day.</param>
	///<remarks>
	/// <para>This form of <c>setCalendarDateType</c> is provided as a convenience method
	/// that is functionally equivalent to the <c>CalendarDateType</c></para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.3</para>
	/// </remarks>
	public void SetCalendarDateType( AU0084CalendarEventType Code ) {
		RemoveChild( StudentDTD.CALENDARDATE_CALENDARDATETYPE);
		AddChild( StudentDTD.CALENDARDATE_CALENDARDATETYPE, new CalendarDateType( Code ) );
	}

	///
	/// Gets or sets the value of the <c><CalendarDateType></c> element.
	///
	/// <value> A CalendarDateType </value>
	/// <remarks>
	/// <para>To remove the <c>CalendarDateType</c>, set <c>CalendarDateType</c> to <c>null</c></para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.3</para>
	/// </remarks>
	public CalendarDateType CalendarDateType
	{
		get
		{
			return (CalendarDateType)GetChild( StudentDTD.CALENDARDATE_CALENDARDATETYPE);
		}
		set
		{
			RemoveChild( StudentDTD.CALENDARDATE_CALENDARDATETYPE);
			if( value != null)
			{
				AddChild( StudentDTD.CALENDARDATE_CALENDARDATETYPE, value );
			}
		}
	}

	///Sets the value of the <c><StudentAttendance></c> element.
	/// <param name="CountsTowardAttendance">Designates whether this date should be counted toward student attendance.</param>
	/// <param name="AttendanceValue">An AttendanceValue</param>
	///<remarks>
	/// <para>This form of <c>setStudentAttendance</c> is provided as a convenience method
	/// that is functionally equivalent to the <c>StudentAttendance</c></para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.3</para>
	/// </remarks>
	public void SetStudentAttendance( YesNo CountsTowardAttendance, decimal? AttendanceValue ) {
		RemoveChild( StudentDTD.CALENDARDATE_STUDENTATTENDANCE);
		AddChild( StudentDTD.CALENDARDATE_STUDENTATTENDANCE, new CalendarAttendance( CountsTowardAttendance, AttendanceValue ) );
	}

	///
	/// Gets or sets the value of the <c><StudentAttendance></c> element.
	///
	/// <value> A CalendarAttendance </value>
	/// <remarks>
	/// <para>To remove the <c>CalendarAttendance</c>, set <c>StudentAttendance</c> to <c>null</c></para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.3</para>
	/// </remarks>
	public CalendarAttendance StudentAttendance
	{
		get
		{
			return (CalendarAttendance)GetChild( StudentDTD.CALENDARDATE_STUDENTATTENDANCE);
		}
		set
		{
			RemoveChild( StudentDTD.CALENDARDATE_STUDENTATTENDANCE);
			if( value != null)
			{
				AddChild( StudentDTD.CALENDARDATE_STUDENTATTENDANCE, value );
			}
		}
	}

	///
	/// Gets or sets the value of the <c><CalendarDateNumber></c> element.
	///
	/// <value> The <c>CalendarDateNumber</c> element of this object.</value>
	/// <remarks>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.4</para>
	/// </remarks>
	public int? CalendarDateNumber
	{
		get
		{
			return (int?) GetSifSimpleFieldValue( StudentDTD.CALENDARDATE_CALENDARDATENUMBER ) ;
		}
		set
		{
			SetFieldValue( StudentDTD.CALENDARDATE_CALENDARDATENUMBER, new SifInt( value ), value );
		}
	}

	///Sets the value of the <c><TeacherAttendance></c> element.
	/// <param name="CountsTowardAttendance">Designates whether this date should be counted toward student attendance.</param>
	/// <param name="AttendanceValue">An AttendanceValue</param>
	///<remarks>
	/// <para>This form of <c>setTeacherAttendance</c> is provided as a convenience method
	/// that is functionally equivalent to the <c>TeacherAttendance</c></para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.4</para>
	/// </remarks>
	public void SetTeacherAttendance( YesNo CountsTowardAttendance, decimal? AttendanceValue ) {
		RemoveChild( StudentDTD.CALENDARDATE_TEACHERATTENDANCE);
		AddChild( StudentDTD.CALENDARDATE_TEACHERATTENDANCE, new CalendarAttendance( CountsTowardAttendance, AttendanceValue ) );
	}

	///
	/// Gets or sets the value of the <c><TeacherAttendance></c> element.
	///
	/// <value> A CalendarAttendance </value>
	/// <remarks>
	/// <para>To remove the <c>CalendarAttendance</c>, set <c>TeacherAttendance</c> to <c>null</c></para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.4</para>
	/// </remarks>
	public CalendarAttendance TeacherAttendance
	{
		get
		{
			return (CalendarAttendance)GetChild( StudentDTD.CALENDARDATE_TEACHERATTENDANCE);
		}
		set
		{
			RemoveChild( StudentDTD.CALENDARDATE_TEACHERATTENDANCE);
			if( value != null)
			{
				AddChild( StudentDTD.CALENDARDATE_TEACHERATTENDANCE, value );
			}
		}
	}

	///Sets the value of the <c><AdministratorAttendance></c> element.
	/// <param name="CountsTowardAttendance">Designates whether this date should be counted toward student attendance.</param>
	/// <param name="AttendanceValue">An AttendanceValue</param>
	///<remarks>
	/// <para>This form of <c>setAdministratorAttendance</c> is provided as a convenience method
	/// that is functionally equivalent to the <c>AdministratorAttendance</c></para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.4</para>
	/// </remarks>
	public void SetAdministratorAttendance( YesNo CountsTowardAttendance, decimal? AttendanceValue ) {
		RemoveChild( StudentDTD.CALENDARDATE_ADMINISTRATORATTENDANCE);
		AddChild( StudentDTD.CALENDARDATE_ADMINISTRATORATTENDANCE, new CalendarAttendance( CountsTowardAttendance, AttendanceValue ) );
	}

	///
	/// Gets or sets the value of the <c><AdministratorAttendance></c> element.
	///
	/// <value> A CalendarAttendance </value>
	/// <remarks>
	/// <para>To remove the <c>CalendarAttendance</c>, set <c>AdministratorAttendance</c> to <c>null</c></para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.4</para>
	/// </remarks>
	public CalendarAttendance AdministratorAttendance
	{
		get
		{
			return (CalendarAttendance)GetChild( StudentDTD.CALENDARDATE_ADMINISTRATORATTENDANCE);
		}
		set
		{
			RemoveChild( StudentDTD.CALENDARDATE_ADMINISTRATORATTENDANCE);
			if( value != null)
			{
				AddChild( StudentDTD.CALENDARDATE_ADMINISTRATORATTENDANCE, value );
			}
		}
	}

}}


text:
namespace gantt {

	bool loadConfig (GanttConfig & config, QString const & fname)
	{
		std::ifstream ifs(fname.toLatin1());
		if (!ifs) return false;
		boost::archive::xml_iarchive ia(ifs);
		ia >> BOOST_SERIALIZATION_NVP(config);
		ifs.close();
		return true;
	}

	bool saveConfig (GanttConfig const & config, QString const & fname)
	{
		std::ofstream ofs(fname.toLatin1());
		if (!ofs) return false;
		boost::archive::xml_oarchive oa(ofs);
		oa << BOOST_SERIALIZATION_NVP(config);
		ofs.close();
		return true;
	}

	void fillDefaultConfig (GanttConfig & config)
	{
		config = GanttConfig();
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.google.bamboo.soy.parser;

import java.util.List;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import com.intellij.psi.PsiElement;
import com.google.bamboo.soy.elements.TagElement;

public interface SoyBeginChoice extends TagElement {

  @Nullable
  SoyAttributeKeyValuePair getAttributeKeyValuePair();

  @Nullable
  SoyExpr getExpr();

}


text:
/**
 * Interface du PersonManager
 * @author Jonathan, Philippe, Marcel
 * @version 1.0
 */

package springapp.persons;

import java.util.Collection;

public interface IPersonManager {

	/**
	 * Récupérer les personnes
	 * @return Collection<Person>
	 */
	Collection<Person> findAll();

	/**
	 * Lire une personne
	 * @param String id
	 * @return Person
	 */
	Person find(String id);

	/**
	 * Fonction cherchant un ensemble de personnes à partir de leur nom ou prénom
	 * @param name
	 * @return
	 */
	Collection<Person> findByName(String name);

	/**
	 * Modification ou ajout d'une nouvelle personne
	 * @param Person p
	 * @return Person
	 */
	Person save(Person p);

	/**
	 * Suppression d'une personne
	 * @param String id
	 * @return int
	 */
	int delete(String id);
}


text:
"""
Classify an image using individual model files

Use this script as an example to build your own tool
"""

import argparse
import os
import time
import string
import PIL.Image
import numpy as np
import scipy.misc
from google.protobuf import text_format

os.environ['GLOG_minloglevel'] = '2' # Suppress most caffe output
import caffe
from caffe.proto import caffe_pb2
import enchant

CONFIDENCE_THRESHOLD = 80
WINDOW_WIDTH = 32
WINDOW_HEIGHT = 32
STRIDE_X = 2
STRIDE_Y = 2

MIN_CHARS_PER_BLOCK = 3
BLOCK_WIDTH = 8
BLOCK_HEIGHT = 8
CHAR_EXCLUSION_X = 4.0
CHAR_EXCLUSION_Y = 7.0
SPACE_THRESHOLD = 10
LINE_HEIGHT = 9
COMBINE_X_THRESHOLD = 4
COMBINE_Y_THRESHOLD = 9.0
COMBINE_COUNT_MAX = 10 # if there are more than this number in the block, it can't be combined into another char
BLOCK_COUNT_SATURATED = 10

COMBINE_LETTERS = {
    'lk': 'k',
    'kc': 'k',
    'nm': 'm',
    'mn': 'm',
    'dl': 'd',
    'rc': 'r',
    'lb': 'b',
    'od': 'd',
    'oa': 'a'
}

COMBINE_LETTERS_WINNER = (
    'ad'
    'ec'
    'uw'
    'tf'
)

OUT_FORMAT = "PNG"
OUT_EXTENSION = ".png"

FULL_WIDTH = -1
FULL_HEIGHT = -1
STRIDE_WIDTH = -1

def get_net(caffemodel, deploy_file, use_gpu=True):
    """
    Returns an instance of caffe.Net

    Arguments:
    caffemodel -- path to a .caffemodel file
    deploy_file -- path to a .prototxt file

    Keyword arguments:
    use_gpu -- if True, use the GPU for inference
    """
    if use_gpu:
        caffe.set_mode_gpu()

    # load a new model
    return caffe.Net(deploy_file, caffemodel, caffe.TEST)

def get_transformer(deploy_file, mean_file=None):
    """
    Returns an instance of caffe.io.Transformer

    Arguments:
    deploy_file -- path to a .prototxt file

    Keyword arguments:
    mean_file -- path to a .binaryproto file (optional)
    """
    network = caffe_pb2.NetParameter()
    with open(deploy_file) as infile:
        text_format.Merge(infile.read(), network)

    dims = network.input_dim

    t = caffe.io.Transformer(
            inputs = {'data': dims}
            )
    t.set_transpose('data', (2,0,1)) # transpose to (channels, height, width)

    # color images
    if dims[1] == 3:
        # channel swap
        t.set_channel_swap('data', (2,1,0))

    if mean_file:
        # set mean pixel
        with open(mean_file) as infile:
            blob = caffe_pb2.BlobProto()
            blob.MergeFromString(infile.read())
            if blob.HasField('shape'):
                blob_dims = blob.shape
                assert len(blob_dims) == 4, 'Shape should have 4 dimensions - shape is "%s"' % blob.shape
            elif blob.HasField('num') and blob.HasField('channels') and \
                    blob.HasField('height') and blob.HasField('width'):
                blob_dims = (blob.num, blob.channels, blob.height, blob.width)
            else:
                raise ValueError('blob does not provide shape or 4d dimensions')
            pixel = np.reshape(blob.data, blob_dims[1:]).mean(1).mean(1)
            t.set_mean('data', pixel)

    return t

def load_image(path, height, width, mode='L'):
    image = PIL.Image.open(path)
    image = image.convert(mode)
    image = np.array(image)
    # squash
    image = scipy.misc.imresize(image, (height, width), 'bilinear')
    return image

def load_and_splice_image(file_path, height, width, mode='L'):
    global STRIDE_WIDTH
    image = PIL.Image.open(file_path)
    image = image.convert(mode)
    (FULL_WIDTH, FULL_HEIGHT) = image.size

    """black_threshold = 230
    for y in range(0, image.size[1]):
        for x in range(0, image.size[0]):
            if image.getpixel((x,y)) > black_threshold:
                image.putpixel((x,y), 255)
            else:
                image.putpixel((x,y), 0)"""

    crops = []
    STRIDE_WIDTH = 0
    print "image.size = " + str(image.size)
    for y in range(0, FULL_HEIGHT - height+1, STRIDE_Y):
        for x in range(0, FULL_WIDTH - width+1, STRIDE_X):
            if y == 0:
                STRIDE_WIDTH += 1
            if len(crops) < 80000:
                crop = image.crop((x, y, x+ width, y + height))
                # crop.save("dump/crop_" + str(y) + "_" + str(x) + OUT_EXTENSION, OUT_FORMAT)
                crop = np.array(crop)
                crops.append(crop)
    print "STRIDE_WIDTH = " + str(STRIDE_WIDTH)
    return crops

def forward_pass(images, net, transformer, batch_size=1):
    """
    Returns scores for each image as an np.ndarray (nImages x nClasses)

    Arguments:
    images -- a list of np.ndarrays
    net -- a caffe.Net
    transformer -- a caffe.io.Transformer

    Keyword arguments:
    batch_size -- how many images can be processed at once
        (a high value may result in out-of-memory errors)
    """
    caffe_images = []
    for image in images:
        if image.ndim == 2:
            caffe_images.append(image[:,:,np.newaxis])
        else:
            caffe_images.append(image)

    caffe_images = np.array(caffe_images)

    dims = transformer.inputs['data'][1:]

    scores = None
    for chunk in [caffe_images[x:x+batch_size] for x in xrange(0, len(caffe_images), batch_size)]:
        new_shape = (len(chunk),) + tuple(dims)
        if net.blobs['data'].data.shape != new_shape:
            net.blobs['data'].reshape(*new_shape)
        for index, image in enumerate(chunk):
            image_data = transformer.preprocess('data', image)
            net.blobs['data'].data[index] = image_data
        output = net.forward()[net.outputs[-1]]
        if scores is None:
            scores = output
        else:
            scores = np.vstack((scores, output))
        # print 'Processed %s/%s images ...' % (len(scores), len(caffe_images))
    print "Processed ", len(caffe_images), " images"

    return scores

def read_labels(labels_file):
    """
    Returns a list of strings

    Arguments:
    labels_file -- path to a .txt file
    """
    if not labels_file:
        print 'WARNING: No labels file provided. Results will be difficult to interpret.'
        return None

    labels = []
    with open(labels_file) as infile:
        for line in infile:
            label = line.strip()
            if label:
                labels.append(label)
    assert len(labels), 'No labels found'
    return labels

def getPrintChar(classification):
    # space between words
    if classification == "space":
        return " "
    # this could also be a space between words
    if classification == "blank":
        return " "
    # 0 = noise
    if classification == "underline":
        return " "
    # 1 = space in between characters
    if classification == "overline":
        return " "
    if classification == "between lines":
        return " "
    # space between chars
    if classification == "between chars":
        return " "
    if classification == "part":
        return " "
    if classification == "blank_between":
        return " "
    if classification == "blank_below":
        return " "
    if classification == "blank_above":
        return " "
    return classification

def classify(caffemodel, deploy_file, image_files,
        mean_file=None, labels_file=None, use_gpu=True):
    """
    Classify some images against a Caffe model and print the results

    Arguments:
    caffemodel -- path to a .caffemodel
    deploy_file -- path to a .prototxt
    image_files -- list of paths to images

    Keyword arguments:
    mean_file -- path to a .binaryproto
    labels_file path to a .txt file
    use_gpu -- if True, run inference on the GPU
    """
    # Load the model and images
    net = get_net(caffemodel, deploy_file, use_gpu)
    transformer = get_transformer(deploy_file, mean_file)
    _, channels, height, width = transformer.inputs['data']
    print "target height, width: ", height,  " ", width
    if channels == 3:
        mode = 'RGB'
    elif channels == 1:
        mode = 'L'
    else:
        raise ValueError('Invalid number for channels: %s' % channels)

    # images = [load_image(image_file, height, width, mode) for image_file in image_files]
    images = load_and_splice_image(image_files[0], height, width, mode)
    labels = read_labels(labels_file)

    # Classify the image
    classify_start_time = time.time()
    scores = forward_pass(images, net, transformer)
    print 'Classification took %s seconds.' % (time.time() - classify_start_time,)

    ### Process the results

    indices = (-scores).argsort()[:, :5] # take top 5 results
    classifications = []
    for image_index, index_list in enumerate(indices):
        result = []
        for i in index_list:
            # 'i' is a category in labels and also an index into scores
            if labels is None:
                label = 'Class #%s' % i
            else:
                label = labels[i]
            result.append((label, round(100.0*scores[image_index, i],4)))
        classifications.append(result)

    ''' for index, classification in enumerate(classifications):
        print '{:-^80}'.format(' Prediction for %s ' % str(index))
        for label, confidence in classification:
            print '{:9.4%} - "{}"'.format(confidence/100.0, label)
        print '''

    '''for index, classification in enumerate(classifications):
        print index,
        print '{:9.4%} - "{}"'.format(classification[0][1]/100.0, classification[0][0])
    '''

    # classifcations[index][1..5][label, confidence]
    count = 0
    line = ""
    for index, classification in enumerate(classifications):
        if classification[0][1] > CONFIDENCE_THRESHOLD:
            line += getPrintChar(classification[0][0])
        else:
            line += " "
        if count % STRIDE_WIDTH == 0:
            print line
            line = ""
        count += 1
    return classifications

isMarked = []
def generateConnectedComponent(chars, y, x):
    global isMarked
    # print "y, x", y, " ", x
    if y < 0 or x < 0 or y >= len(chars) or x >= len(chars[y]):
        return []
    if isMarked[y][x]:
        return []
    if chars[y][x] == " ":
        return []
    isMarked[y][x] = True
    r = [(y,x)]
    r += generateConnectedComponent(chars, y-1, x-1)
    r += generateConnectedComponent(chars, y-1, x)
    r += generateConnectedComponent(chars, y-1, x+1)
    r += generateConnectedComponent(chars, y, x-1)
    r += generateConnectedComponent(chars, y, x+1)
    r += generateConnectedComponent(chars, y+1, x-1)
    r += generateConnectedComponent(chars, y+1, x)
    r += generateConnectedComponent(chars, y+1, x+1)
    return r

def predictLine(classifications):
    ''' returns False if line skipped (whitespace etc) '''
    ''' if True is returned, skipped the next 16 lines '''
    dchars = []
    for y in range(len(classifications)):
        line = ""
        for c in classifications[y]:
            if c[0][1] > CONFIDENCE_THRESHOLD:
                line += getPrintChar(c[0][0])
            else:
                line += " "
        # print "adding line: ", line
        dchars.append(line)

    if dchars[0].count(" ") >= len(dchars[0])-2:
        print "skipping this line"
        return None

    # count the biggest connected components
    charLine = []
    global isMarked
    isMarked = [[False] * len(line) for line in dchars]
    for y in range(len(dchars)):
        for x in range(len(dchars[y])):
            if dchars[y][x] != " " and not isMarked[y][x]:
                indices = generateConnectedComponent(dchars, y, x)
                # print "y, x, char, size: ", y, " ", x, " ", dchars[y][x], " ", len(indices)
                # take max char
                charCount = {}
                for (py, px) in indices:
                    if not dchars[py][px] in charCount:
                        charCount[dchars[py][px]] = 0
                    charCount[dchars[py][px]] += 1
                maxCount = 0
                componentChar = ""
                for k in charCount:
                    if charCount[k] > maxCount:
                        maxCount = charCount[k]
                        componentChar = k
                # print "\t component char: ", componentChar
                charLine.append((x, componentChar, maxCount))

    charLine = sorted(charLine, key=lambda comp: -comp[2])
    # grab the biggest components by size, don't add if x-coordinate is too close
    # print "charLine: ", charLine
    bigLine = []
    for (x, ch, sz) in charLine:
        tooClose = False
        for (x2, ch2) in bigLine:
            # consider adjusting this parameter
            if abs(x-x2) < 5:
                tooClose = True
                break
        if not tooClose:
            bigLine.append((x, ch))
    bigLine = sorted(bigLine, key=lambda comp: comp[0])
    print "bigLine: ", bigLine
    return bigLine

def containsWordSeparator(x1, x2, classifications):
    ''' returns true if "space" or "blank" occurs anywhere between x1 and x2 '''
    for pxLine in classifications:
        for x in range(x1+1, x2):
            if pxLine[x][0][1] > CONFIDENCE_THRESHOLD and \
                    (pxLine[x][0][0] == "space" or pxLine[x][0][0] == "blank"):
                return True
    return False

def makeWords(bigLine, classifications):
    words = []
    currentWord = ""
    for index in range(len(bigLine)):
        # make space?
        # check if big space (word separator) occurs between x1 and x2
        if index > 1 and bigLine[index][0] - bigLine[index-1][0] > 6 and \
                containsWordSeparator(bigLine[index-1][0], bigLine[index][0], classifications):
            # there's a space here, dump current word
            if currentWord != "":
                words.append(currentWord)
                currentWord = ""

        currentWord += bigLine[index][1]

    if currentWord != "":
        words.append(currentWord)
    return words

# old predictLine
''' def predictLine(classifications):
    assert(len(classifications) == STRIDE_WIDTH)
    allChars = [x[0][0] for x in classifications]
    # print allChars
    chars = [x[0][0] for x in classifications if x[0][1] > CONFIDENCE_THRESHOLD]
    # print chars
    # filter out 0's (noise)
    # treat 1's as spaces
    chars = filter(lambda c: c != '0', chars)
    # transform all same-letter-pairs (XX) into (X)
    for i in range(len(chars)):
        if len(chars[i]) > 1:
            chars[i] = chars[i][0]
    # 1/4 the number of repeated characters, rounding down, at least 1
    singleChars = []
    index = 0
    while index < len(chars):
        start = index
        while index < len(chars) and chars[index] == chars[start]:
            index += 1
        singleChars += [chars[start]] * max(1, int((index-start+1)/4.0))
    # split words by spaces
    words = []
    currentWord = ""
    for c in singleChars:
        if c == "1" and currentWord != "":
            words.append(currentWord)
            currentWord = ""
        elif c != "1":
            currentWord += c
    if currentWord != "":
        words.append(currentWord)
    print "words: ", words
    # check against en_US spelling
    endict = enchant.request_dict("en_US")
    dictWords = []
    for w in words:
        if endict.check(w):
            dictWords.append(w)
        else:
            suggestions = endict.suggest(w)
            # just append the first one
            if len(suggestions) > 0:
                dictWords.append(suggestions[0])
            # else we have unrecoverable garbage?
    print "\t dict: ", dictWords
'''

def runThruDictionary(words):
    # check against en_US spelling
    endict = enchant.request_dict("en_US")
    dictWords = []
    for w in words:
        if endict.check(w):
            dictWords.append(w)
        else:
            suggestions = endict.suggest(w)
            # just append the first one
            if len(suggestions) > 0:
                dictWords.append(suggestions[0])
            # else we have unrecoverable garbage?
    return dictWords

def predictWords(classifications):
    # STRIDE_WIDTH is one line
    lineIndex = 0
    while (lineIndex + (WINDOW_HEIGHT/STRIDE_Y) - 1) * STRIDE_WIDTH < len(classifications):
        print "#", lineIndex, ": ",
        # splice here
        r = predictLine([classifications[(lineIndex + i) * STRIDE_WIDTH : (lineIndex + i +1) * STRIDE_WIDTH]
                         for i in range(0, WINDOW_HEIGHT/STRIDE_Y)])
        if not r:
            lineIndex += 1
            continue

        words = makeWords(r,
                          [classifications[(lineIndex + i) * STRIDE_WIDTH : (lineIndex + i +1) * STRIDE_WIDTH]
                           for i in range(0, WINDOW_HEIGHT/STRIDE_Y)])
        print "words: ", words
        dictWords = runThruDictionary(words)
        print "\t: ", dictWords

        lineIndex += WINDOW_HEIGHT/STRIDE_Y

def get_center_weight(grid, char, corner_x, corner_y):
    sum = 0
    count = 0
    center_x = corner_x + BLOCK_WIDTH / 2
    center_y = corner_y + BLOCK_HEIGHT / 2
    for y in range(corner_y, corner_y + BLOCK_HEIGHT):
        for x in range(corner_x, corner_x + BLOCK_WIDTH):
            if x < 0:
                continue
            if y < 0:
                continue
            if x >= STRIDE_WIDTH:
                continue
            index = x + y * STRIDE_WIDTH
            if index >= len(grid):
                break
            if grid[index] == char:
                dx = abs(x - center_x)
                dy = abs(y - center_y)
                sum += BLOCK_WIDTH - dx
                sum += BLOCK_HEIGHT - dy
                count += 1
    return sum

def erase_char(grid, char, corner_x, corner_y):
    erase_count = 0
    sum_x = 0
    sum_y = 0
    for y in range(corner_y, corner_y + BLOCK_HEIGHT):
        for x in range(corner_x, corner_x + BLOCK_WIDTH):
            if x < 0:
                continue
            if y < 0:
                continue
            if x >= STRIDE_WIDTH:
                continue
            index = x + y * STRIDE_WIDTH
            if index >= len(grid):
                break
            if grid[index] == char:
                erase_count += 1
                sum_x += x
                sum_y += y
                grid[index] = "~"
    x_avg = float(sum_x) / erase_count
    y_avg = float(sum_y) / erase_count
    #print char + " count: " + str(erase_count) + " at: " + str(x_avg) + ", " + str(y_avg)
    return erase_count, x_avg, y_avg

def find_char_in_grid(grid, char):
    # find a character of the given type
    # move around untill the mass is centered
    index = grid.index(char)
    y = index / STRIDE_WIDTH
    x = index - y * STRIDE_WIDTH
    better_found = True
    current_weight = get_center_weight(grid, char, x, y)
    if current_weight == -1:
        print "ERROR find_char_in_grid current_weight == -1"
        return 0,0,"@",1
    while better_found:
        # search nearby
        better_found = False
        left = get_center_weight(grid, char, x - 1, y)
        if left > current_weight:
            better_found = True
            current_weight = left
            x -= 1
            continue
        top = get_center_weight(grid, char, x, y - 1)
        if top > current_weight:
            better_found = True
            current_weight = top
            y -= 1
            continue
        right = get_center_weight(grid, char, x + 1, y)
        if right > current_weight:
            better_found = True
            current_weight = right
            x += 1
            continue
        bottom = get_center_weight(grid, char, x, y + 1)
        if bottom > current_weight:
            better_found = True
            current_weight = bottom
            y += 1
            continue
    count, avg_x, avg_y = erase_char(grid, char, x, y)
    return avg_x, avg_y, char, count

def can_place(placed, char):
    #exclusion_zone = CHAR_EXCLUSION_X * (0.5 + 0.5 * float(BLOCK_COUNT_SATURATED - char[3]) / BLOCK_COUNT_SATURATED)
    #exclusion_zone = max(0.5 * CHAR_EXCLUSION_X, exclusion_zone)
    exclusion_zone = CHAR_EXCLUSION_X
    for test in placed:
        if abs(test[0] - char[0]) < exclusion_zone and abs(test[1] - char[1]) < CHAR_EXCLUSION_Y:
            return False
    return True

def get_next_line_chars(found_chars):
    # find the highest char, and search left and right for more line chars
    found_chars.sort(key=lambda tup: tup[1])
    line_chars = []
    left = found_chars[0]
    right = left
    found_chars.remove(left)
    line_chars.append(left)
    while left:
        next_char = None
        for char in found_chars:
            if abs(left[1] - char[1]) <= LINE_HEIGHT:
                if char[0] < left[0] and ((not next_char) or (char[0] > next_char[0])):
                    next_char = char
        if next_char:
            gap = abs(next_char[0] - left[0])
            if gap > SPACE_THRESHOLD:
                line_chars.insert(0, (0,0," ",1))
        left = next_char
        if left:
            found_chars.remove(left)
            line_chars.insert(0, left)

    while right:
        next_char = None
        for char in found_chars:
            if abs(right[1] - char[1]) <= LINE_HEIGHT:
                if char[0] > right[0] and ((not next_char) or (char[0] < next_char[0])):
                    next_char = char
        if next_char:
            gap = abs(next_char[0] - right[0])
            if gap > SPACE_THRESHOLD:
                line_chars.append((0,0," ",1))
        right = next_char
        if right:
            found_chars.remove(right)
            line_chars.append(right)
    return line_chars

def combine_common_mistakes(found_chars):
    combination_found = True
    while combination_found:
        combination_found = False
        for char1 in found_chars:
            for char2 in found_chars:
                dx = char2[0] - char1[0]
                dy = char2[1] - char1[1]
                key = char1[2] + char2[2]
                if abs(dy) >= COMBINE_Y_THRESHOLD:
                    continue
                if key in COMBINE_LETTERS_WINNER and dx <= COMBINE_X_THRESHOLD:
                    if char1[3] > char2[3]:
                        if char2[3] > COMBINE_COUNT_MAX:
                            continue
                        found_chars.remove(char1)
                        found_chars.remove(char2)
                        found_chars.append((char1[0], char1[1], char1[2], char1[3]))
                        combination_found = True
                        break
                    else:
                        if char1[3] > COMBINE_COUNT_MAX:
                            continue
                        found_chars.remove(char1)
                        found_chars.remove(char2)
                        found_chars.append((char2[0], char2[1], char2[2], char2[3]))
                        combination_found = True
                        break
                if COMBINE_LETTERS.has_key(key) and dx > 0 and dx <= COMBINE_X_THRESHOLD:
                    result = COMBINE_LETTERS[key]
                    if result == char1[2]:
                        if char2[3] > COMBINE_COUNT_MAX:
                            continue
                        found_chars.remove(char1)
                        found_chars.remove(char2)
                        found_chars.append((char1[0], char1[1], result, char1[3]))
                        combination_found = True
                        break
                    elif result == char2[2]:
                        if char1[3] > COMBINE_COUNT_MAX:
                            continue
                        found_chars.remove(char1)
                        found_chars.remove(char2)
                        found_chars.append((char2[0], char2[1], result, char2[3]))
                        combination_found = True
                        break
                    else:
                        if char1[3] > COMBINE_COUNT_MAX:
                            continue
                        if char2[3] > COMBINE_COUNT_MAX:
                            continue
                        found_chars.remove(char1)
                        found_chars.remove(char2)
                        if char1[3] > char2[3]:
                            found_chars.append((char1[0], char1[1], result, char1[3] + char2[3]))
                        else:
                            found_chars.append((char2[0], char2[1], result, char1[3] + char2[3]))
                        combination_found = True
                        break
            if combination_found:
                break

def predictWords2(classifications):
    # STRIDE_WIDTH is one line
    found_characters = []
    lineIndex = 0

    #place all classifications on a grid
    #search for and center on masses of a given character, note the location and strength, then remove attributed chars
    #find where characters 'fit' characters with larger mass get preferential treatment
    #consider combining characters that are too close and are common mistakes for the classifier

    char_grid = []
    for c in classifications:
        if c[0][1] >= CONFIDENCE_THRESHOLD:
            char_grid.append(getPrintChar(c[0][0]))
        else:
            char_grid.append(" ")

    found_chars = []

    for a in string.ascii_lowercase:
        count = 0
        #print "Searching: " + a + " count: " + str(char_grid.count(a))
        while a in char_grid and count < 1000:
            count += 1
            char = find_char_in_grid(char_grid, a)
            found_chars.append(char)

    #combine_common_mistakes(found_chars)

    #found_chars = filter(lambda test_char: test_char[3] > MIN_CHARS_PER_BLOCK , found_chars)

    # sort chars by mass and place them one by one
    found_chars.sort(key=lambda tup: -tup[3])
    # if there's no room for a char, skip it

    placed_chars = []
    for char in found_chars:
        if char[3] < MIN_CHARS_PER_BLOCK:
            break
        if can_place(placed_chars, char):
            placed_chars.append(char)

    alllines = []
    while len(placed_chars) > 0:
        line_chars = get_next_line_chars(placed_chars)
        line = ""
        for char in line_chars:
            line += char[2]
        print line
        alllines.append(line)
    return alllines

def writeTextToFile(imgfilename, lines):
    txtname = imgfilename.split(".")[0] + ".txt"
    count = 0
    while os.path.isfile(txtname):
        count += 1
        txtname = imgfilename.split(".")[0] + "." + str(count) + ".txt"

    f = open(txtname, "w")
    for line in lines:
        f.write(line + "\n")
    f.close()

if __name__ == '__main__':
    script_start_time = time.time()

    parser = argparse.ArgumentParser(description='Classification example - DIGITS')

    ### Positional arguments

    parser.add_argument('caffemodel',   help='Path to a .caffemodel')
    parser.add_argument('deploy_file',  help='Path to the deploy file')
    parser.add_argument('image',        help='Path to an image')

    ### Optional arguments

    parser.add_argument('-m', '--mean',
            help='Path to a mean file (*.npy)')
    parser.add_argument('-l', '--labels',
            help='Path to a labels file')
    parser.add_argument('--nogpu',
            action='store_true',
            help="Don't use the GPU")

    args = vars(parser.parse_args())

    image_files = [args['image']]

    classifications = classify(args['caffemodel'], args['deploy_file'], image_files,
                               args['mean'], args['labels'], not args['nogpu'])

    lines = predictWords2(classifications)
    writeTextToFile(image_files[0], lines)

    print 'Script took %s seconds.' % (time.time() - script_start_time,)


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

namespace Test.ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.ReadLine().Dump();
        }
    }
}


text:
using System.Collections.Generic;

using CollegeFbsRankings.Domain.Conferences;

namespace CollegeFbsRankings.Domain.Repositories
{
    public interface IDivisionQuery<out T> : IQuery<IReadOnlyDivisionList<T>> where T : Division
    {
        IDivisionQuery<T> ById(DivisionId id);

        IDivisionQuery<T> ByName(string name);

        IDivisionQuery<T> ForConference(ConferenceId conferenceId);

        IDivisionQuery<FbsDivision> Fbs();
    }

    public static class DivisionQueryExtensions
    {
        public static IDivisionQuery<T> ForConference<T>(this IDivisionQuery<T> query, Conference conference) where T : Division
        {
            return query.ForConference(conference.Id);
        }

        public static IDivisionQuery<FbsDivision> ForConference<T>(this IDivisionQuery<T> query, FbsConference conference) where T : Division
        {
            return query.ForConference(conference.Id).Fbs();
        }
    }
}


text:
#ifndef _BB_ACTION_SCHEDULECOMMIT_H_
#define _BB_ACTION_SCHEDULECOMMIT_H_

#include "bbaction.h"

class BBSvn;

class BBActionScheduleCommit : public BBAction
{
    Q_OBJECT

public:
    BBActionScheduleCommit(QObject *parent = 0);
    ~BBActionScheduleCommit();

public:
    void run();
    bool compare(const BBAction *action);
};

#endif


text:
import sys
from tkinter import *
makemodal = (len(sys.argv) > 1)

def dialog():
    win = Toplevel()
    Label(win, text = 'Hard drive reformatted!').pack()
    Button(win, text = 'Ok', command = win.destroy).pack()
    if makemodal:
        win.focus_set()
        win.grab_set()
        win.wait_window()
    print('dialog exit')

if __name__ == '__main__':
    root = Tk()
    Button(root, text = 'popup', command = dialog).pack()
    root.mainloop()


text:
<!DOCTYPE html>

        <meta charset="utf-8" />
        <base href="<?php echo strip_tags($request_url); ?>" />
        <title><?php echo mb_convert_encoding($title, "HTML-ENTITIES", "UTF-8"); ?> - Gracecode.com</title>
        <?php include DIR_ROOT . '/template/header.inc.html'; ?>

無標題文檔

<a title="back to original page"
                   href="<?php echo strip_tags($request_url); ?>"><?php
                   echo mb_convert_encoding($title, 'HTML-ENTITIES', "UTF-8"); ?>

            <?php echo $content; ?>

        <?php include DIR_ROOT . '/template/footer.inc.html'; ?>


text:
package se.emilsjolander.stickylistheaders;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

/**
 *
 * the view that wrapps a divider header and a normal list item. The listview sees this as 1 item
 *
 * @author Emil Sjölander
 */
public class WrapperView extends ViewGroup {

	View mItem;
	Drawable mDivider;
	int mDividerHeight;
	View mHeader;
	int mItemTop;

	WrapperView(Context c) {
		super(c);
	}

	public boolean hasHeader() {
		return mHeader != null;
	}

	public View getItem() {
		return mItem;
	}

	public View getHeader() {
		return mHeader;
	}

	void update(View item, View header, Drawable divider, int dividerHeight) {

		//every wrapperview must have a list item
		if (item == null) {
			throw new NullPointerException("List view item must not be null.");
		}

		//only remove the current item if it is not the same as the new item. this can happen if wrapping a recycled view
		if (this.mItem != item) {
			removeView(this.mItem);
			this.mItem = item;
			final ViewParent parent = item.getParent();
			if(parent != null && parent != this) {
				if(parent instanceof ViewGroup) {
					((ViewGroup) parent).removeView(item);
				}
			}
			addView(item);
		}

		//same logik as above but for the header
		if (this.mHeader != header) {
			if (this.mHeader != null) {
				removeView(this.mHeader);
			}
			this.mHeader = header;
			if (header != null) {
				addView(header);
			}
		}

		if (this.mDivider != divider) {
			this.mDivider = divider;
			this.mDividerHeight = dividerHeight;
			invalidate();
		}
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		int measuredWidth = MeasureSpec.getSize(widthMeasureSpec);
		int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(measuredWidth,
				MeasureSpec.EXACTLY);
		int measuredHeight = 0;

		//measure header or divider. when there is a header visible it acts as the divider
		if (mHeader != null) {
			LayoutParams params = mHeader.getLayoutParams();
			if (params != null && params.height > 0) {
				mHeader.measure(childWidthMeasureSpec,
						MeasureSpec.makeMeasureSpec(params.height, MeasureSpec.EXACTLY));
			} else {
				mHeader.measure(childWidthMeasureSpec,
						MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
			}
			measuredHeight += mHeader.getMeasuredHeight();
		} else if (mDivider != null&&mItem.getVisibility()!=View.GONE) {
			measuredHeight += mDividerHeight;
		}

		//measure item
		LayoutParams params = mItem.getLayoutParams();
        //enable hiding listview item,ex. toggle off items in group
		if(mItem.getVisibility()==View.GONE){
            mItem.measure(childWidthMeasureSpec,
                    MeasureSpec.makeMeasureSpec(0, MeasureSpec.EXACTLY));
        }else if (params != null && params.height >= 0) {
			mItem.measure(childWidthMeasureSpec,
					MeasureSpec.makeMeasureSpec(params.height, MeasureSpec.EXACTLY));
            measuredHeight += mItem.getMeasuredHeight();
		} else {
			mItem.measure(childWidthMeasureSpec,
					MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            measuredHeight += mItem.getMeasuredHeight();
		}

		setMeasuredDimension(measuredWidth, measuredHeight);
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {

		l = 0;
		t = 0;
		r = getWidth();
		b = getHeight();

		if (mHeader != null) {
			int headerHeight = mHeader.getMeasuredHeight();
			mHeader.layout(l, t, r, headerHeight);
			mItemTop = headerHeight;
			mItem.layout(l, headerHeight, r, b);
		} else if (mDivider != null) {
			mDivider.setBounds(l, t, r, mDividerHeight);
			mItemTop = mDividerHeight;
			mItem.layout(l, mDividerHeight, r, b);
		} else {
			mItemTop = t;
			mItem.layout(l, t, r, b);
		}
	}

	@Override
	protected void dispatchDraw(Canvas canvas) {
		super.dispatchDraw(canvas);
		if (mHeader == null && mDivider != null&&mItem.getVisibility()!=View.GONE) {
			// Drawable.setBounds() does not seem to work pre-honeycomb. So have
			// to do this instead
			if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
				canvas.clipRect(0, 0, getWidth(), mDividerHeight);
			}
			mDivider.draw(canvas);
		}
	}
}


text:
package gigigo.com.orchextra.data.datasources.db.model.mappers;

import com.gigigo.ggglib.mappers.Mapper;
import com.gigigo.orchextra.domain.model.vo.OrchextraStatus;
import gigigo.com.orchextra.data.datasources.db.model.OrchextraStatusRealm;

/**
 * Created by Sergio Martinez Rodriguez
 * Date 4/3/16.
 */
public class OrchextraStatusRealmMapper implements Mapper<OrchextraStatus, OrchextraStatusRealm> {

  @Override public OrchextraStatus externalClassToModel(OrchextraStatusRealm data) {
    OrchextraStatus orchextraStatus = new OrchextraStatus();
    orchextraStatus.setInitialized(data.isInitialized());
    orchextraStatus.setStarted(data.isStarted());
    return orchextraStatus;
  }

  @Override public OrchextraStatusRealm modelToExternalClass(OrchextraStatus orchextraStatus) {

    OrchextraStatusRealm orchextraStatusRealm = new OrchextraStatusRealm();
    orchextraStatusRealm.setInitialized(orchextraStatus.isInitialized());
    orchextraStatusRealm.setStarted(orchextraStatus.isStarted());
    return orchextraStatusRealm;
  }

}


text:
require 'flic/protocol/primitives'
require 'flic/protocol/primitives/enum'

module Flic
  module Protocol
    module Primitives
      # [:success] Indicates that a button was successfully paired and verified. You may now create a connection channel to that button.
      # [:cancelled_by_user] A CmdCancelScanWizard was sent.
      # [:timeout] The scan wizard did not make any progress for some time. Current timeouts are 20 seconds for finding any button, 20 seconds for finding a public button (in case of a private button was found), 10 seconds for connecting the button, 30 seconds for pairing and verifying the button.
      # [:button_private] First the button was advertising public status, but after connecting it reports private. Probably it switched from public to private just when the connection attempt was started.
      # [:bluetooth_unavailable] The bluetooth controller is not attached.
      # [:internet_backend_error] The internet request to the Flic backend failed.
      # [:invalid_data] According to the Flic backend, this Flic button supplied invalid identity data.
    class ScanWizardResult < Enum
        option :success
        option :cancelled_by_user
        option :timeout
        option :button_private
        option :bluetooth_unavailable
        option :internet_backend_error
        option :invalid_data
      end
    end
  end
end


text:
<?php

/**
 * OTAdmin protocol client.
 *
 * @package POT
 * @version 0.2.0+SVN
 * @since 0.1.2
 * @property-read bool $requiresLogin {@link OTS_Admin::requiresLogin() requiresLogin()} wrapper.
 * @property-read bool $requiresEncryption {@link OTS_Admin::requiresEncryption() requiresEncryption()} wrapper.
 * @property-read bool $usesRSA1024XTEA {@link OTS_Admin::usesRSA1024XTEA() usesRSA1024XTEA()} wrapper.
 * @property-read int $ping Ping time.
 * @property-write string $login Logs in with given password.
 * @property-write string $broadcast Sends given broadcast message.
 * @property-write string $kick Kicks player with given name from server.
 * @tutorial POT/OTAdmin.pkg
 * @example examples/admin.php admin.php
 * @example examples/save.php save.php
 */
class OTS_Admin
{
/**
 * User login.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const REQUEST_LOGIN = 1;
/**
 * Encryption packet.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const REQUEST_ENCRYPTION = 2;
/**
 * RSA key exchange.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const REQUEST_KEY_EXCHANGE = 3;
/**
 * OTAdmin commnd.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const REQUEST_COMMAND = 4;
/**
 * Ping.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const REQUEST_PING = 5;

/**
 * Hello respond.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const RESPOND_HELLO = 1;
/**
 * Keys exchange success.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const RESPOND_KEY_EXCHANGE_OK = 2;
/**
 * Keys exchange failed.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const RESPOND_KEY_EXCHANGE_FAILED = 3;
/**
 * Login success.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const RESPOND_LOGIN_OK = 4;
/**
 * Login incorrect.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const RESPOND_LOGIN_FAILED = 5;
/**
 * Command success.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const RESPOND_COMMAND_OK = 6;
/**
 * Command failed.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const RESPOND_COMMAND_FAILED = 7;
/**
 * Encryption initialization success.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const RESPOND_ENCRYPTION_OK = 8;
/**
 * Encryption initialization failed.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const RESPOND_ENCRYPTION_FAILED = 9;
/**
 * Ping success.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const RESPOND_PING_OK = 10;
/**
 * Message.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const RESPOND_MESSAGE = 11;
/**
 * Error.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const RESPOND_ERROR = 12;

/**
 * Broadcast message.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const COMMAND_BROADCAST = 1;
/**
 * Closes server.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const COMMAND_CLOSE_SERVER = 2;
/**
 * Pays all rented shouses.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const COMMAND_PAY_HOUSES = 3;
/**
 * Opens server for players.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const COMMAND_OPEN_SERVER = 4;
/**
 * Shutdowns the server.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const COMMAND_SHUTDOWN_SERVER = 5;
/**
 * Not supported in current OTAdmin imlpementation.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const COMMAND_RELOAD_SCRIPTS = 6;
/**
 * Not supported in current OTAdmin imlpementation.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const COMMAND_PLAYER_INFO = 7;
/**
 * Not supported in current OTAdmin imlpementation.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const COMMAND_GETONLINE = 8;
/**
 * Kicks player.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const COMMAND_KICK = 9;
/**
 * Not supported in current OTAdmin imlpementation.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const COMMAND_BAN_MANAGER = 10;
/**
 * Not supported in current OTAdmin imlpementation.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const COMMAND_SERVER_INFO = 11;
/**
 * Not supported in current OTAdmin imlpementation.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const COMMAND_GETHOUSE = 12;
/**
 * Calls server save.
 *
 * @version 0.1.6
 * @since 0.1.6
 */
    const COMMAND_SAVE_SERVER = 13;

/**
 * Server requires login.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const REQUIRE_LOGIN = 1;
/**
 * Server requires encryption.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const REQUIRE_ENCRYPTION = 2;

/**
 * Server uses XTEA encryption, XTEA key is being sent in 1024bit RSA encrypted packet.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    const ENCRYPTION_RSA1024XTEA = 1;

/**
 * Socket handle.
 *
 * @version 0.1.2
 * @since 0.1.2
 * @var resource
 */
    private $socket;

/**
 * Server security policy.
 *
 * @version 0.1.2
 * @since 0.1.2
 * @var int
 */
    private $policy;

/**
 * Protocol options.
 *
 * @version 0.1.2
 * @since 0.1.2
 * @var int
 */
    private $options;

/**
 * Packets cipher.
 *
 * @version 0.1.2
 * @since 0.1.2
 * @var IOTS_Cipher
 */
    private $cipher;

/**
 * Host address for session sleep/wakeup.
 *
 * @version 0.1.2
 * @since 0.1.2
 * @var string
 */
    private $host;

/**
 * Port number for session sleep/wakeup.
 *
 * @version 0.1.2
 * @since 0.1.2
 * @var int
 */
    private $port;

/**
 * Creates new connection to OTServ administration backend.
 *
 *

 * This method automaticly handles RSA and XTEA encryption if such method is required by server including keys negotiations.
 *

 *
 *

 * After connecting you should check {@link OTS_Admin::requiresLogin() if server requires login}.
 *

 *
 * @version 0.1.2
 * @since 0.1.2
 * @param string $host Target server.
 * @param int $port Port (7171 by default).
 * @throws E_OTS_ErrorCode When receive failed respond or unexpected message.
 * @throws E_OTS_OutOfBuffer When there is read attemp after end of packet stream.
 */
    public function __construct($host, $port = 7171)
    {
        // saves connection sessint
        $this->host = $host;
        $this->port = $port;

        // opens connection
        $this->socket = fsockopen($this->host, $this->port);

        // 254 = OTAdmin protocol identifier
        $message = new OTS_Buffer( chr(254) );

        // sends initial packet
        $respond = $this->send($message);
        $message->reset();

        $byte = $respond->getChar();

        // checks if it's HELLO packet
        if($byte != self::RESPOND_HELLO)
        {
            throw new E_OTS_ErrorCode($byte);
        }

        // skips respond signature and protocol version
        $respond->getLong();
        $respond->getString();

        // saves protocol settings
        $this->policy = $respond->getShort();
        $this->options = $respond->getLong();

        // handles encryption initialisation if required
        if( $this->requiresEncryption() && $this->usesRSA1024XTEA() )
        {
            // requests public key
            $message->putChar(self::REQUEST_KEY_EXCHANGE);
            $message->putChar(self::ENCRYPTION_RSA1024XTEA);
            $respond = $this->send($message);
            $message->reset();

            $byte = $respond->getChar();

            // checks if it succeded
            if($byte != self::RESPOND_KEY_EXCHANGE_OK)
            {
                throw new E_OTS_ErrorCode($byte, $respond->getString() );
            }

            // we support only RSA 1024bit encryption for XTEA key sending
            if( $respond->getChar() != self::ENCRYPTION_RSA1024XTEA)
            {
                throw new E_OTS_ErrorCode($byte);
            }

            // reads binary form of public key (128 bytes)
            $key = OTS_BinaryTools::bin2Int( strrev( $respond->getString(128) ) );

            // creates RSA cipher
            // as we have ready N computer here and we don't compute it by ourselves we can use a little hack, to save N as P * Q we will use P = N and Q = 1
            $rsa = new OTS_RSA($key, '1');

            $key = '';

            // generates random XTEA key
            for($i = 0; $i < 4; $i++)
            {
                $key .= pack('L', rand(0, 4294967295) );
            }

            $xtea = new OTS_XTEA($key);

            // sends XTEA key
            $message->putChar(self::REQUEST_ENCRYPTION);
            $message->putChar(self::ENCRYPTION_RSA1024XTEA);
            $message->putString( $rsa->encrypt( chr(0) . $key), false);

            // we can't bind cipher yet since only respnd will be XTEA encrypted
            $respond = new OTS_Buffer( $xtea->decrypt( $this->send($message)->getBuffer() ) );

            $byte = $respond->getChar();

            // checks if encryption negotation succeeded
            if($byte != self::RESPOND_ENCRYPTION_OK)
            {
                throw new E_OTS_ErrorCode($byte, $respond->getString());
            }

            // saves encryption/decryption cipher
            $this->cipher = $xtea;
        }
    }

/**
 * Checks if protocol requires login.
 *
 * @version 0.1.2
 * @since 0.1.2
 * @return bool True if protocol requires user login.
 */
    public function requiresLogin()
    {
        return ($this->policy & self::REQUIRE_LOGIN) == self::REQUIRE_LOGIN;
    }

/**
 * Checks if protocol requires encryption.
 *
 * @version 0.1.2
 * @since 0.1.2
 * @return bool True if protocol requires encryption.
 */
    public function requiresEncryption()
    {
        return ($this->policy & self::REQUIRE_ENCRYPTION) == self::REQUIRE_ENCRYPTION;
    }

/**
 * Checks if protocol requires XTEA encryption with RSA-encrypted key.
 *
 * @version 0.1.2
 * @since 0.1.2
 * @return bool True if protocol requires that encryption.
 */
    public function usesRSA1024XTEA()
    {
        return ($this->options & self::ENCRYPTION_RSA1024XTEA) == self::ENCRYPTION_RSA1024XTEA;
    }

/**
 * Sends OTAdmin packet.
 *
 * @version 0.1.2
 * @since 0.1.2
 * @param OTS_Buffer $message Packet to be sent.
 * @return OTS_Buffer Server respond.
 * @throws E_OTS_ErrorCode When receive RESPOND_ERROR message.
 * @throws E_OTS_OutOfBuffer When there is read attemp after end of packet stream.
 */
    public function send(OTS_Buffer $message)
    {
        $message = $message->getBuffer();

        // encrypts message if required
        if( isset($this->cipher) )
        {
            $message = $this->cipher->encrypt($message);
        }

        $message = pack('v', strlen($message) ) . $message;

        fputs($this->socket, $message);

        // reads respond length
        $length = unpack('v', fgets($this->socket, 3) );

        $buffer = fgets($this->socket, $length[1] + 1);

        // decrypts buffer if required
        if(  isset($this->cipher) )
        {
            $buffer = $this->cipher->decrypt($buffer);
        }

        // checks for error code
        $respond = new OTS_Buffer($buffer);

        if( $respond->getChar() == self::RESPOND_ERROR)
        {
            throw new E_OTS_ErrorCode(self::RESPOND_ERROR, $respond->getString() );
        }

        // returns respond
        $respond->setPos(0);
        return $respond;
    }

/**
 * Closes connection.
 *
 * @version 0.1.2
 * @since 0.1.2
 */
    public function __destruct()
    {
        fclose($this->socket);
    }

/**
 * Magic PHP5 method.
 *
 * @version 0.1.3
 * @since 0.1.3
 * @param string $name Property name.
 * @param mixed $value Property value.
 * @throws OutOfBoundsException For non-supported properties.
 * @throws E_OTS_ErrorCode When receive failed respond or unexpected message.
 * @throws E_OTS_OutOfBuffer When there is read attemp after end of packet stream.
 */
    public function __get($name)
    {
        switch($name)
        {
            case 'requiresLogin':
                return $this->requiresLogin();

            case 'requiresEncryption':
                return $this->requiresEncryption();

            case 'usesRSA1024XTEA':
                return $this->usesRSA1024XTEA();

            case 'ping':
                return $this->ping();

            default:
                throw new OutOfBoundsException();
        }
    }

/**
 * Magic PHP5 method.
 *
 * @version 0.1.4
 * @since 0.1.3
 * @param string $name Property name.
 * @param mixed $value Property value.
 * @throws OutOfBoundsException For non-supported properties.
 * @throws E_OTS_ErrorCode When receive failed respond or unexpected message.
 * @throws E_OTS_OutOfBuffer When there is read attemp after end of packet stream.
 */
    public function __set($name, $value)
    {
        switch($name)
        {
            case 'login':
                $this->login($value);
                break;

            case 'broadcast':
                $this->broadcast($value);
                break;

            case 'kick':
                $this->kick($value);
                break;

            default:
                throw new OutOfBoundsException();
        }
    }

/**
 * Logs into server.
 *
 *

 * Call this method if after connection is established login required flag is set.
 *

 *
 * @version 0.1.2
 * @since 0.1.2
 * @param string $password Admin password.
 * @throws E_OTS_ErrorCode When receive failed respond or unexpected message.
 * @throws E_OTS_OutOfBuffer When there is read attemp after end of packet stream.
 */
    public function login($password)
    {
        // password packet
        $message = new OTS_Buffer();
        $message->putChar(self::REQUEST_LOGIN);
        $message->putString($password);

        // reads respond
        $message = $this->send($message);

        $byte = $message->getChar();

        // checks respond
        if($byte != self::RESPOND_LOGIN_OK)
        {
            throw new E_OTS_ErrorCode($byte, $message->getString());
        }
    }

/**
 * Ping command.
 *
 *

 * Note: This methods calculates ping time based on {@link OTS_Admin::send() OTS_Admin::send()} sub-call. This means ping time will be time used for entire seding operation including packet encryption, packing, unpacking and decryption.
 *

 *
 * @version 0.1.2
 * @since 0.1.2
 * @return int Ping time.
 * @throws E_OTS_ErrorCode When receive failed respond or unexpected message.
 * @throws E_OTS_OutOfBuffer When there is read attemp after end of packet stream.
 */
    public function ping()
    {
        // constructs message
        $message = new OTS_Buffer();
        $message->putChar(self::REQUEST_PING);

        // start
        $ping = microtime(true);
        $message = $this->send($message);

        // stop
        $ping = microtime(true) - $ping;

        $byte = $message->getChar();

        // checks if command succeeded
        if($byte != self::RESPOND_PING_OK)
        {
            throw new E_OTS_ErrorCode($byte, $respond->getString());
        }

        return $ping;
    }

/**
 * Sends command message.
 *
 *

 * This method wraps another buffer within command byte and also checks for command success.
 *

 *
 * @version 0.1.2
 * @since 0.1.2
 * @param OTS_Buffer $message Command to be send.
 * @return OTS_Buffer Respond.
 * @throws E_OTS_ErrorCode If failure respond received.
 * @throws E_OTS_OutOfBuffer When there is read attemp after end of packet stream.
 */
    private function sendCommand(OTS_Buffer $message)
    {
        // prepends command byte
        $buffer = new OTS_Buffer();
        $buffer->putChar(self::REQUEST_COMMAND);
        $buffer->putString( $message->getBuffer(), false);

        // sends command
        $buffer = $this->send($buffer);
        $byte = $buffer->getChar();

        // checks for error code
        if($byte != self::RESPOND_COMMAND_OK)
        {
            throw new E_OTS_ErrorCode($byte, $buffer->getString() );
        }

        // returns respond with reseted position
        $buffer->setPos(0);
        return $buffer;
    }

/**
 * Sends COMMAND_BROADCAST command with given parameter.
 *
 *

 * Sends broadcast message to all players.
 *

 *
 * @version 0.1.2
 * @since 0.1.2
 * @param string $message Broadcast to be sent.
 * @throws E_OTS_ErrorCode If failure respond received.
 * @throws E_OTS_OutOfBuffer When there is read attemp after end of packet stream.
 */
    public function broadcast($message)
    {
        // sends message
        $buffer = new OTS_Buffer();
        $buffer->putChar(self::COMMAND_BROADCAST);
        $buffer->putString($message);
        $this->sendCommand($buffer);
    }

/**
 * Sends COMMAND_OPEN_SERVER command.
 *
 *

 * Opens server. This command enables server for connections.
 *

 *
 * @version 0.1.6
 * @since 0.1.6
 * @throws E_OTS_ErrorCode If failure respond received.
 * @throws E_OTS_OutOfBuffer When there is read attemp after end of packet stream.
 */
    public function open()
    {
        // sends message
        $buffer = new OTS_Buffer();
        $buffer->putChar(self::COMMAND_OPEN_SERVER);
        $this->sendCommand($buffer);
    }

/**
 * Sends COMMAND_CLOSE_SERVER command.
 *
 *

 * Closes server. This command closes server for connections to enable maintenance but doesn't shut it down.
 *

 *
 * @version 0.1.2
 * @since 0.1.2
 * @throws E_OTS_ErrorCode If failure respond received.
 * @throws E_OTS_OutOfBuffer When there is read attemp after end of packet stream.
 */
    public function close()
    {
        // sends message
        $buffer = new OTS_Buffer();
        $buffer->putChar(self::COMMAND_CLOSE_SERVER);
        $this->sendCommand($buffer);
    }

/**
 * Sends COMMAND_PAY_HOUSES command.
 *
 *

 * Takes fees for all rented houses.
 *

 *
 * @version 0.1.2
 * @since 0.1.2
 * @throws E_OTS_ErrorCode If failure respond received.
 * @throws E_OTS_OutOfBuffer When there is read attemp after end of packet stream.
 */
    public function payHouses()
    {
        // sends message
        $buffer = new OTS_Buffer();
        $buffer->putChar(self::COMMAND_PAY_HOUSES);
        $this->sendCommand($buffer);
    }

/**
 * Sends COMMAND_SHUTDOWN_SERVER command.
 *
 *

 * Shutdowns server. This command closes server thread.
 *

 *
 * @version 0.1.2
 * @since 0.1.2
 * @throws E_OTS_ErrorCode If failure respond received.
 * @throws E_OTS_OutOfBuffer When there is read attemp after end of packet stream.
 */
    public function shutdown()
    {
        // sends message
        $buffer = new OTS_Buffer();
        $buffer->putChar(self::COMMAND_SHUTDOWN_SERVER);
        $this->sendCommand($buffer);
    }

/**
 * Sends COMMAND_KICK command with given parameter.
 *
 *

 * Kicks given player from server.
 *

 *
 * @version 0.1.4
 * @since 0.1.4
 * @param string $name Name of player to be kicked.
 * @throws E_OTS_ErrorCode If failure respond received.
 * @throws E_OTS_OutOfBuffer When there is read attemp after end of packet stream.
 */
    public function kick($name)
    {
        // sends message
        $buffer = new OTS_Buffer();
        $buffer->putChar(self::COMMAND_KICK);
        $buffer->putString($name);
        $this->sendCommand($buffer);
    }

/**
 * Sends COMMAND_SAVE_SERVER command.
 *
 *

 * Proceeds server save.
 *

 *
 * @version 0.1.6
 * @since 0.1.6
 * @throws E_OTS_ErrorCode If failure respond received.
 * @throws E_OTS_OutOfBuffer When there is read attemp after end of packet stream.
 */
    public function save()
    {
        // sends message
        $buffer = new OTS_Buffer();
        $buffer->putChar(self::COMMAND_SAVE_SERVER);
        $this->sendCommand($buffer);
    }

/**
 * Magic PHP5 method.
 *
 *

 * Allows object importing from {@link http://www.php.net/manual/en/function.var-export.php var_export()}.
 *

 *
 * @version 0.2.0+SVN
 * @since 0.1.2
 * @param array $properties List of object properties.
 * @throws E_OTS_ErrorCode When receive failed respond or unexpected message.
 * @throws E_OTS_OutOfBuffer When there is read attemp after end of packet stream.
 */
    public static function __set_state(array $properties)
    {
        return new self($properties['host'], $properties['port']);
    }

/**
 * Magic PHP5 method.
 *
 *

 * Creates new socket connection to server.
 *

 *
 * @version 0.1.2
 * @since 0.1.2
 * @throws E_OTS_ErrorCode When receive failed respond or unexpected message.
 * @throws E_OTS_OutOfBuffer When there is read attemp after end of packet stream.
 */
    public function __clone()
    {
        $this->__construct($this->host, $this->port);
    }

/**
 * Magic PHP5 method.
 *
 *

 * Allows object serialisation.
 *

 *
 * @version 0.1.2
 * @since 0.1.2
 * @return array List of properties that should be saved.
 */
    public function __sleep()
    {
        return array('host', 'port');
    }

/**
 * Magic PHP5 method.
 *
 *

 * Allows object unserialisation.
 *

 *
 * @version 0.1.2
 * @since 0.1.2
 * @throws E_OTS_ErrorCode When receive failed respond or unexpected message.
 * @throws E_OTS_OutOfBuffer When there is read attemp after end of packet stream.
 */
    public function __wakeup()
    {
        $this->__construct($this->host, $this->port);
    }
}

?>


text:
class spin_lock
{
public:
    spin_lock(): _locked(false) {}

    void lock() {
        static bool false_val = false;
        std::atomic_compare_exchange_strong(&_locked, &false_val, true);
    }

    void unlock() {
        static bool true_val = true;
        std::atomic_compare_exchange_strong(&_locked, &true_val, true);
    }

private:
    volatile std::atomic<bool> _locked;
};

#endif //_ARKANOID_SPIN_LOCK_H_


text:
**PartialFlow** is a lightweight extension to [TensorFlow](https://www.tensorflow.org) that simplifies the training of
large neural networks on graphic cards with limited memory resources. It allows to **trade off** additional
computation **time** for lower **memory** consumption.

PartialFlow was primarily designed with back-propagation on neural networks in mind. It therefore assumes
that the computation can be decomposed into a cheap forward pass that computes intermediate results and an expensive
backward pass that computes gradients and updates parameters.

The price for lower memory consumption roughly amounts to a **second forward pass**, plus data transfers between GPU and
main memory.

**Note that PartialFlow is considered experimental.** Please report bugs in the GitHub issue tracker.

Tested with Tensorflow v0.12.1, not yet tested with Tensorflow v1.0.

## How to use
Please read the [MNIST Example Notebook](MNIST-example.ipynb) for an introduction. There are some subtleties that need
to be considered when training a neural network partially. See below for more information.

## Comparison with basic Training
Take a look at the [Sanity Check Notebook](Sanity-Check.ipynb) for a simple comparison between a network training with
and without PartialFlow. We compare training progress and update duration.

## How it works
PartialFlow allows to split the graph into multiple *sections* that are trained separately. It automatically
analyzes the data flow between sections, caches intermediate results as needed, and
abstracts away the logic of running forward and backward passes over multiple sections.

For a training cycle, PartialFlow first runs a forward pass over the graph and caches each section's
inputs. It then runs separate backward passes over all sections in reversed order and caches gradient values needed for
following sections. A section's backward pass may include a second forward pass, as gradient computations often
 require intermediate results computed inside a section.

## Subtleties
There are some subtleties when it comes to training a neural network with partial evaluations. Although PartialFlow takes
 care of some of them, some (still) need to be considered during development.

### Caching
PartialFlow caches the _inputs_ to each graph section in a first forward pass and reuses them during the
backward pass. It should therefore be ensured that all tensors for which multiple evaluations may result in different values
are only used as input to a section (and hence cached).

**Problematic Example**: A batch queue is used for loading and processing of input images and labels. If the network's
loss is defined outside the graph sections, the labels will not be cached during the forward pass, whereas the input
images will be. In the backward pass the images are reused, but new labels are drawn from the batch queue. This
results in inconsistent loss and gradient information.

**Solution**: Define queues outside the graph's sections and all operations on their outputs inside (e.g. first layer, loss). In
general, do not use tensors outside of graph sections if their values change across multiple evaluations.
Keep in mind that each section's forward pass might be run multiple times, with only the section's input kept fixed.

### Batch Normalization
PartialFlow generates a single training operation for each section, which only computes and applies the gradients for
the corresponding part of the graph. There might be other operations that need to be run during training, e.g. moving
average updates for batch normalization. PartialFlow groups all operations in the section's `UPDATE_OPS` collection
and runs them exactly once during the section's backward pass.

**Problematic Example**: A network architecture enforces updates of moving averages during the forward pass of the network.
This can e.g. be achieved by explicitly defining the operations as dependencies. Since PartialFlow runs multiple forward
passes over each section, those updates might or might not be executed multiple times.

**Solution**: Use the `UPDATE_OPS` graph collection for operations that need to be run once for each training batch.

## License
MIT


text:
description: docker-compose help
keywords: fig, composition, compose, docker, orchestration, cli, help
title: docker-compose help
notoc: true
---

```
Usage: help COMMAND
```

Displays help and usage instructions for a command.


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Copyright 2016-2017 AWACS Project.

    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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>awacs-component</artifactId>
        <groupId>io.awacs</groupId>
        <version>0.2.5</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>awacs-fernflower-component</artifactId>

    <dependencies>
        <dependency>
            <groupId>io.awacs</groupId>
            <artifactId>awacs-common</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
    </dependencies>

    <build>
        <finalName>awacs-fernflow-component</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-dep</id>
                        <phase>process-sources</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <stripVersion>true</stripVersion>
                            <outputDirectory>${project.basedir}/../target</outputDirectory>
                            <overWriteReleases>true</overWriteReleases>
                            <overWriteIfNewer>true</overWriteIfNewer>
                        </configuration>
                    </execution>
                    <execution>
                        <id>copy-artifact</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>${project.groupId}</groupId>
                                    <artifactId>${project.artifactId}</artifactId>
                                    <version>${project.version}</version>
                                    <type>${project.packaging}</type>
                                </artifactItem>
                            </artifactItems>
                            <stripVersion>true</stripVersion>
                            <outputDirectory>${project.basedir}/../target</outputDirectory>
                            <overWriteReleases>true</overWriteReleases>
                            <overWriteIfNewer>true</overWriteIfNewer>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
@implementation SDLSingleTireStatus

-(id) init {
    if (self = [super init]) {}
    return self;
}

-(id) initWithDictionary:(NSMutableDictionary*) dict {
    if (self = [super initWithDictionary:dict]) {}
    return self;
}

-(void) setStatus:(SDLComponentVolumeStatus*) status {
    if (status != nil) {
        [store setObject:status forKey:NAMES_status];
    } else {
        [store removeObjectForKey:NAMES_status];
    }
}

-(SDLComponentVolumeStatus*) status {
    NSObject* obj = [store objectForKey:NAMES_status];
    if ([obj isKindOfClass:SDLComponentVolumeStatus.class]) {
        return (SDLComponentVolumeStatus*)obj;
    } else {
        return [SDLComponentVolumeStatus valueOf:(NSString*)obj];
    }
}

@end


text:
@interface GTMCarbonEventTest : GTMTestCase {
 @private
  GTMCarbonEvent *event_;
}
@end

@interface GTMCarbonEventHandlerTest : GTMTestCase {
 @private
  GTMCarbonEventHandler *handler_;
}
@end

@interface GTMCarbonEventMonitorHandlerTest : GTMTestCase
@end

@interface GTMCarbonEventApplicationEventHandlerTest : GTMTestCase
@end

@interface GTMCarbonEventDispatcherHandlerTest : GTMTestCase {
 @private
  XCTestExpectation *hotKeyHitExpectation_;
}
@end

static const UInt32 kTestClass = 'foo ';
static const UInt32 kTestKind = 'bar ';
static const UInt32 kTestParameterName = 'baz ';
static const UInt32 kTestBadParameterName = 'bom ';
static const UInt32 kTestParameterValue = 'bam ';

@implementation GTMCarbonEventTest
- (void)setUp {
  event_ = [[GTMCarbonEvent eventWithClass:kTestClass kind:kTestKind] retain];
}

- (void)tearDown {
  [event_ release];
}

- (void)testCopy {
  GTMCarbonEvent *event2 = [[event_ copy] autorelease];
  XCTAssertNotNil(event2);
}

- (void)testEventWithClassAndKind {
  XCTAssertEqual([event_ eventClass], kTestClass);
  XCTAssertEqual([event_ eventKind], kTestKind);
}

- (void)testEventWithEvent {
  GTMCarbonEvent *event2 = [GTMCarbonEvent eventWithEvent:[event_ event]];
  XCTAssertEqual([event2 event], [event_ event]);
}

- (void)testCurrentEvent {
  EventRef eventRef = GetCurrentEvent();
  GTMCarbonEvent *event = [GTMCarbonEvent currentEvent];
  XCTAssertEqual([event event], eventRef);
}

- (void)testEventClass {
  [self testEventWithClassAndKind];
}

- (void)testEventKind {
  [self testEventWithClassAndKind];
}

- (void)testSetTime {
  EventTime eventTime = [event_ time];
  XCTAssertNotEqualWithAccuracy(eventTime, kEventDurationNoWait, 0.01);
  XCTAssertNotEqualWithAccuracy(eventTime, kEventDurationForever, 0.01);
  [event_ setTime:kEventDurationForever];
  EventTime testTime = [event_ time];
  XCTAssertEqualWithAccuracy(testTime, kEventDurationForever, 0.01);
  [event_ setTime:eventTime];
  XCTAssertEqualWithAccuracy([event_ time], eventTime, 0.01);
}

- (void)testTime {
  [self testSetTime];
}

- (void)testEvent {
  [self testEventWithEvent];
}

- (void)testSetParameterNamed {
  UInt32 theData = kTestParameterValue;
  [event_ setUInt32ParameterNamed:kTestParameterName data:&theData];
  theData = 0;
  XCTAssertEqual([event_ sizeOfParameterNamed:kTestParameterName
                                         type:typeUInt32],
                  sizeof(UInt32));
  XCTAssertTrue([event_ getUInt32ParameterNamed:kTestParameterName
                                           data:&theData]);
  XCTAssertEqual(theData, kTestParameterValue);
}

- (void)testGetParameterNamed {
  [self testSetParameterNamed];
  UInt32 theData = kTestParameterValue;
  XCTAssertFalse([event_ getUInt32ParameterNamed:kTestBadParameterName
                                            data:&theData]);
  XCTAssertFalse([event_ getUInt32ParameterNamed:kTestBadParameterName
                                            data:NULL]);

}

- (void)testSizeOfParameterNamed {
  [self testSetParameterNamed];
}

- (void)testHasParameterNamed {
  [self testSetParameterNamed];
}

- (OSStatus)gtm_eventHandler:(GTMCarbonEventHandler *)sender
               receivedEvent:(GTMCarbonEvent *)event
                     handler:(EventHandlerCallRef)handler {
  OSStatus status = eventNotHandledErr;
  if ([event eventClass] == kTestClass && [event eventKind] == kTestKind) {
    status = noErr;
  }
  return status;
}

- (void)testSendToTarget {
  EventTypeSpec types = { kTestClass, kTestKind };
  GTMCarbonEventDispatcherHandler *handler
    = [[GTMCarbonEventDispatcherHandler sharedEventDispatcherHandler]
       autorelease];
  [handler registerForEvents:&types count:1];
  OSStatus status = [event_ sendToTarget:handler options:0];
  XCTAssertErr(status, eventNotHandledErr, @"status: %d", (int)status);
  [handler setDelegate:self];
  status = [event_ sendToTarget:handler options:0];
  XCTAssertNoErr(status, @"status: %d", (int)status);
  [handler unregisterForEvents:&types count:1];
}

- (void)testPostToQueue {
  EventQueueRef eventQueue = GetMainEventQueue();
  [event_ postToMainQueue];
  OSStatus status = [event_ postToQueue:eventQueue
                               priority:kEventPriorityStandard];
  XCTAssertErr(status, eventAlreadyPostedErr, @"status: %d", (int)status);
  EventTypeSpec types = { kTestClass, kTestKind };
  status = FlushEventsMatchingListFromQueue(eventQueue, 1, &types);
  XCTAssertNoErr(status, @"status: %ld", (long)status);

  eventQueue = GetCurrentEventQueue();
  [event_ postToCurrentQueue];
  status = [event_ postToQueue:eventQueue priority:kEventPriorityStandard];
  XCTAssertErr(status, eventAlreadyPostedErr, @"status: %d", (int)status);
  status = FlushEventsMatchingListFromQueue(eventQueue, 1, &types);
  XCTAssertNoErr(status, @"status: %ld", (long)status);
}

- (void)testPostToMainQueue {
  [self testPostToQueue];
}

- (void)testPostToCurrentQueue {
  XCTAssertEqual(GetCurrentEventQueue(), GetMainEventQueue());
  [self testPostToMainQueue];
}

- (void)testDescription {
  NSString *descString
    = [NSString stringWithFormat:@"GTMCarbonEvent 'foo ' %lu",
       (unsigned long)kTestKind];
  XCTAssertEqualObjects([event_ description], descString);
}
@end

@implementation GTMCarbonEventHandlerTest

- (void)setUp {
  handler_ = [[GTMCarbonEventHandler alloc] init];
}

- (void)tearDown {
  [handler_ release];
}

- (void)testEventTarget {
  XCTAssertNULL([handler_ eventTarget]);
}

- (void)testEventHandler {
  XCTAssertErr([handler_ handleEvent:nil handler:nil],
               (long)eventNotHandledErr);
}

- (void)testDelegate {
  [handler_ setDelegate:self];
  XCTAssertEqualObjects([handler_ delegate], self);
  [handler_ setDelegate:nil];
  XCTAssertNil([handler_ delegate]);
}

- (void)testSetDelegate {
  [self testDelegate];
}

@end

@implementation GTMCarbonEventMonitorHandlerTest

- (void)testEventHandler {
  GTMCarbonEventMonitorHandler *monitor
    = [GTMCarbonEventMonitorHandler sharedEventMonitorHandler];
  XCTAssertEqual([monitor eventTarget], GetEventMonitorTarget());
}

@end

@implementation GTMCarbonEventApplicationEventHandlerTest

- (void)testEventHandler {
  GTMCarbonEventApplicationEventHandler *handler
    = [GTMCarbonEventApplicationEventHandler sharedApplicationEventHandler];
  XCTAssertEqual([handler eventTarget], GetApplicationEventTarget());
}

@end

@implementation GTMCarbonEventDispatcherHandlerTest

- (void)testEventHandler {
  GTMCarbonEventDispatcherHandler *dispatcher
    = [GTMCarbonEventDispatcherHandler sharedEventDispatcherHandler];
  XCTAssertEqual([dispatcher eventTarget], GetEventDispatcherTarget());
}

- (void)hitHotKey:(GTMCarbonHotKey *)key {
  XCTAssertEqualObjects([key userInfo], self);
  [hotKeyHitExpectation_ fulfill];
}

- (void)hitExceptionalHotKey:(GTMCarbonHotKey *)key {
  XCTAssertEqualObjects([key userInfo], self);
  [hotKeyHitExpectation_ fulfill];
  [NSException raise:@"foo" format:@"bar"];
}

- (void)testRegisterHotKeyModifiersTargetActionWhenPressed {
  GTMCarbonEventDispatcherHandler *dispatcher
    = [GTMCarbonEventDispatcherHandler sharedEventDispatcherHandler];
  XCTAssertNotNil(dispatcher, @"Unable to acquire singleton");
  UInt32 keyMods = (NSShiftKeyMask | NSControlKeyMask
                    | NSAlternateKeyMask | NSCommandKeyMask);
  XCTAssertNil([dispatcher registerHotKey:0x5
                                modifiers:keyMods
                                   target:nil
                                   action:nil
                                 userInfo:nil
                              whenPressed:YES],
                @"Shouldn't have created hotkey");
  GTMCarbonHotKey *hotKey = [dispatcher registerHotKey:0x5
                                             modifiers:keyMods
                                                target:self
                                                action:@selector(hitHotKey:)
                                              userInfo:self
                                           whenPressed:YES];
  XCTAssertNotNil(hotKey, @"Unable to create hotkey");

  // Post the hotkey combo to the event queue. If everything is working
  // correctly hitHotKey: should get called, and hotKeyHitExpecatation_ will
  // be set for us. We run the event loop for a set amount of time waiting for
  // this to happen.
  hotKeyHitExpectation_ = [self expectationWithDescription:@"hotKey"];
  [GTMAppKitUnitTestingUtilities postTypeCharacterEvent:'g' modifiers:keyMods];
  [self waitForExpectationsWithTimeout:60 handler:NULL];
  [dispatcher unregisterHotKey:hotKey];
}

- (void)testRegisterHotKeyModifiersTargetActionWhenPressedException {
  GTMCarbonEventDispatcherHandler *dispatcher
    = [GTMCarbonEventDispatcherHandler sharedEventDispatcherHandler];
  XCTAssertNotNil(dispatcher, @"Unable to acquire singleton");
  UInt32 keyMods = (NSShiftKeyMask | NSControlKeyMask
                    | NSAlternateKeyMask | NSCommandKeyMask);
  GTMCarbonHotKey *hotKey
    = [dispatcher registerHotKey:0x5
                       modifiers:keyMods
                          target:self
                          action:@selector(hitExceptionalHotKey:)
                        userInfo:self
                     whenPressed:YES];
  XCTAssertNotNil(hotKey, @"Unable to create hotkey");

  // Post the hotkey combo to the event queue. If everything is working
  // correctly hitHotKey: should get called, and hotKeyHitExpecatation_ will
  // be set for us. We run the event loop for a set amount of time waiting for
  // this to happen.
  hotKeyHitExpectation_ = [self expectationWithDescription:@"hotKey"];
  [GTMAppKitUnitTestingUtilities postTypeCharacterEvent:'g' modifiers:keyMods];
  [self waitForExpectationsWithTimeout:60 handler:NULL];
  [dispatcher unregisterHotKey:hotKey];
}

- (void)testKeyModifiers {
  struct {
    NSUInteger cocoaKey_;
    UInt32 carbonKey_;
  } keyMap[] = {
      {NSEventModifierFlagCapsLock, alphaLock},
      {NSEventModifierFlagShift, shiftKey},
      {NSEventModifierFlagControl, controlKey},
      {NSEventModifierFlagOption, optionKey},
      {NSEventModifierFlagCommand, cmdKey},
  };
  size_t combos = pow(2, sizeof(keyMap) / sizeof(keyMap[0]));
  for (size_t i = 0; i < combos; i++) {
    NSUInteger cocoaMods = 0;
    UInt32 carbonMods = 0;
    for (size_t j = 0; j < 32 && j < sizeof(keyMap) / sizeof(keyMap[0]); j++) {
      if (i & 1 << j) {
        cocoaMods |= keyMap[j].cocoaKey_;
        carbonMods |= keyMap[j].carbonKey_;
      }
    }
    XCTAssertEqual(GTMCocoaToCarbonKeyModifiers(cocoaMods), carbonMods);
    XCTAssertEqual(GTMCarbonToCocoaKeyModifiers(carbonMods), cocoaMods);
  }
}

@end