text:
package flex2.tools;

import flash.swf.Frame;
import flash.swf.Movie;
import flash.swf.tags.DoABC;
import flex2.compiler.mxml.lang.StandardDefs;
import flex2.linker.LinkerConfiguration;
import flex2.linker.ConsoleApplication;
import flex2.linker.FlexMovie;
import macromedia.abc.BytecodeBuffer;
import macromedia.abc.ConstantPool;
import macromedia.abc.Decoder;
import macromedia.abc.Encoder;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Implementation of flex2.linker.PostLink which merges ABC blocks and
 * runs a peephole optimizer on the byte code.
 */
public class PostLink implements flex2.linker.PostLink
{
	public PostLink(boolean debug, boolean optimize)
	{
		this.debug = debug;
		this.optimize = optimize;
		as3metadata = StandardDefs.DefaultAS3Metadata;
	}

	public PostLink(LinkerConfiguration linkerConfiguration)
	{
        this.linkerConfiguration = linkerConfiguration;
		debug = linkerConfiguration.debug() || linkerConfiguration.verboseStacktraces();
		optimize = linkerConfiguration.optimize();
		as3metadata = linkerConfiguration.getMetadataToKeep();
	}

    private boolean debug;
    private boolean optimize;
    private String[] as3metadata;
    LinkerConfiguration linkerConfiguration;

	public void run(ConsoleApplication app)
	{
        List<byte[]> abcList = new ArrayList<byte[]>(1);
		abcList.add(null);

		if (optimize)
		{
			merge(app.getABCs(), app.enableDebugger || debug, optimize);
		}
		else
		{
			for (int j = 0, codeSize = app.getABCs().size(); j < codeSize; j++)
			{
				byte[] abc = app.getABCs().get(j);

				abcList.set(0, abc);
				merge(abcList, app.enableDebugger || debug, optimize);
				app.getABCs().set(j, abcList.get(0));
			}
		}
	}

	public void run(Movie movie)
	{
        // See if a flex movie has metadata it needs saved.
        if (movie instanceof FlexMovie)
        {
            Set<String> moreMetadata = ((FlexMovie)movie).getMetadata();
            if (moreMetadata.size() > 0)
            {
                // merge metadata from the flex movie with any existing
                // metadata from the configuration.
                Set<String> mergedMetaData = null;
                if (as3metadata != null && as3metadata.length > 0)
                {
                    mergedMetaData = new HashSet<String>();
                    mergedMetaData.addAll(moreMetadata);
                    mergedMetaData.addAll(Arrays.asList(as3metadata));
                }
                else
                {
                    mergedMetaData = moreMetadata;
                }
                as3metadata = mergedMetaData.toArray(new String[mergedMetaData.size()]);
            }
        }
		List<DoABC> doABCs = new ArrayList<DoABC>(1);
		doABCs.add(null);

		// abc merge... frame by frame... if merging fails on one of the frames, it will continue.
		for (int i = 0, frameSize = movie.frames.size(); i < frameSize; i++)
		{
			Frame f = movie.frames.get(i);
			if (optimize)
			{
				merge(f.doABCs, movie.enableDebugger != null || debug, optimize, "frame" + (i + 1));
			}
			else
			{
				for (int j = 0, codeSize = f.doABCs.size(); j < codeSize; j++)
				{
					DoABC abc = f.doABCs.get(j);

					doABCs.set(0, abc);
					merge(doABCs, movie.enableDebugger != null || debug, optimize, abc.name);
					f.doABCs.set(j, doABCs.get(0));
				}
			}
		}
	}

	private void merge(List<DoABC> doABCs, boolean debug, boolean runPeephole, String name)
	{
		Encoder encoder;
		Decoder decoder;

		boolean skipFrame = false;
		int majorVersion = 0, minorVersion = 0, abcSize = doABCs.size(), flag = 1;

		if (abcSize == 0)
		{
			return;
		}
		else if (abcSize == 1)
		{
			flag = doABCs.get(0).flag;
		}
		else
		{
			flag = 1;
		}

		Decoder[] decoders = new Decoder[abcSize];
		ConstantPool[] pools = new ConstantPool[abcSize];

		// create decoders...
		for (int j = 0; j < abcSize; j++)
		{
			DoABC tag = doABCs.get(j);
			BytecodeBuffer in = new BytecodeBuffer(tag.abc);

			try
			{
				// ThreadLocalToolkit.logInfo(tag.name);
				decoders[j] = new Decoder(in);
				majorVersion = decoders[j].majorVersion;
				minorVersion = decoders[j].minorVersion;
				pools[j] = decoders[j].constantPool;
			}
			catch (Throwable ex)
			{
				StringWriter stringWriter = new StringWriter();
				ex.printStackTrace(new PrintWriter(stringWriter));
				assert false : stringWriter.toString();
				skipFrame = true;
				break;
			}
		}

		if (skipFrame)
		{
			return;
		}

		encoder = new Encoder(majorVersion, minorVersion);
		// all the constant pools are merged here...
		try
		{
			encoder.addConstantPools(pools);
			if (!debug)
			{
				encoder.disableDebugging();
			}

			// always remove metadata...
			encoder.removeMetadata();

			// keep the following metadata
			for (int m = 0; as3metadata != null && m < as3metadata.length; m++)
			{
				encoder.addMetadataToKeep(as3metadata[m]);
			}

			// always enable peephole optimization...
			if (runPeephole)
			{
				encoder.enablePeepHole();
			}

			encoder.configure(decoders);
		}
		catch (Throwable ex)
		{
			StringWriter stringWriter = new StringWriter();
			ex.printStackTrace(new PrintWriter(stringWriter));
			assert false : stringWriter.toString();
			return;
		}

		// decode methodInfo...
		for (int j = 0; j < abcSize; j++)
		{
			decoder = decoders[j];
			encoder.useConstantPool(j);

			Decoder.MethodInfo methodInfo = decoder.methodInfo;

			try
			{
				for (int k = 0, infoSize = methodInfo.size(); k < infoSize; k++)
				{
					methodInfo.decode(k, encoder);
				}
			}
			catch (Throwable ex)
			{
				StringWriter stringWriter = new StringWriter();
				ex.printStackTrace(new PrintWriter(stringWriter));
				assert false : stringWriter.toString();
				skipFrame = true;
				break;
			}
		}

		if (skipFrame)
		{
			return;
		}

		// decode metadataInfo...
		for (int j = 0; j < abcSize; j++)
		{
			decoder = decoders[j];
			encoder.useConstantPool(j);

			Decoder.MetaDataInfo metadataInfo = decoder.metadataInfo;

			try
			{
				for (int k = 0, infoSize = metadataInfo.size(); k < infoSize; k++)
				{
					metadataInfo.decode(k, encoder);
				}
			}
			catch (Throwable ex)
			{
				StringWriter stringWriter = new StringWriter();
				ex.printStackTrace(new PrintWriter(stringWriter));
				assert false : stringWriter.toString();
				skipFrame = true;
				break;
			}
		}

		if (skipFrame)
		{
			return;
		}

		// decode classInfo...

		for (int j = 0; j < abcSize; j++)
		{
			decoder = decoders[j];
			encoder.useConstantPool(j);

			Decoder.ClassInfo classInfo = decoder.classInfo;

			try
			{
				for (int k = 0, infoSize = classInfo.size(); k < infoSize; k++)
				{
					classInfo.decodeInstance(k, encoder);
				}
			}
			catch (Throwable ex)
			{
				StringWriter stringWriter = new StringWriter();
				ex.printStackTrace(new PrintWriter(stringWriter));
				assert false : stringWriter.toString();
				skipFrame = true;
				break;
			}
		}

		if (skipFrame)
		{
			return;
		}

		for (int j = 0; j < abcSize; j++)
		{
			decoder = decoders[j];
			encoder.useConstantPool(j);

			Decoder.ClassInfo classInfo = decoder.classInfo;

			try
			{
				for (int k = 0, infoSize = classInfo.size(); k < infoSize; k++)
				{
					classInfo.decodeClass(k, 0, encoder);
				}
			}
			catch (Throwable ex)
			{
				StringWriter stringWriter = new StringWriter();
				ex.printStackTrace(new PrintWriter(stringWriter));
				assert false : stringWriter.toString();
				skipFrame = true;
				break;
			}
		}

		if (skipFrame)
		{
			return;
		}

		// decode scripts...
		for (int j = 0; j < abcSize; j++)
		{
			decoder = decoders[j];
			encoder.useConstantPool(j);

			Decoder.ScriptInfo scriptInfo = decoder.scriptInfo;

			try
			{
				for (int k = 0, scriptSize = scriptInfo.size(); k < scriptSize; k++)
				{
					scriptInfo.decode(k, encoder);
				}
			}
			catch (Throwable ex)
			{
				StringWriter stringWriter = new StringWriter();
				ex.printStackTrace(new PrintWriter(stringWriter));
				assert false : stringWriter.toString();
				skipFrame = true;
				break;
			}
		}

		if (skipFrame)
		{
			return;
		}

		// decode method bodies...
		for (int j = 0; j < abcSize; j++)
		{
			decoder = decoders[j];
			encoder.useConstantPool(j);

			Decoder.MethodBodies methodBodies = decoder.methodBodies;

			try
			{
				for (int k = 0, bodySize = methodBodies.size(); k < bodySize; k++)
				{
					methodBodies.decode(k, 2, encoder);
				}
			}
			catch (Throwable ex)
			{
				StringWriter stringWriter = new StringWriter();
				ex.printStackTrace(new PrintWriter(stringWriter));
				assert false : stringWriter.toString();
				skipFrame = true;
				break;
			}
		}

		if (skipFrame)
		{
			return;
		}

		// 0: eager
		// 1: lazy
		DoABC doABC = new DoABC(name, flag);
		doABC.abc = encoder.toABC();

		if (doABC.abc != null)
		{
			doABCs.clear();
			doABCs.add(doABC);
		}
	}

	// C: This is for console applications. don't refactor this method and the other merge()
	//    before we ship.
	private void merge(List<byte[]> abcList, boolean debug, boolean runPeephole)
	{
		Encoder encoder;
		Decoder decoder;

		boolean skipFrame = false;
		int majorVersion = 0, minorVersion = 0, abcSize = abcList.size();

		if (abcSize == 0)
		{
			return;
		}

		Decoder[] decoders = new Decoder[abcSize];
		ConstantPool[] pools = new ConstantPool[abcSize];

		// create decoders...
		for (int j = 0; j < abcSize; j++)
		{
			byte[] abc = abcList.get(j);
			BytecodeBuffer in = new BytecodeBuffer(abc);

			try
			{
				decoders[j] = new Decoder(in);
				majorVersion = decoders[j].majorVersion;
				minorVersion = decoders[j].minorVersion;
				pools[j] = decoders[j].constantPool;
			}
			catch (Throwable ex)
			{
				StringWriter stringWriter = new StringWriter();
				ex.printStackTrace(new PrintWriter(stringWriter));
				assert false : stringWriter.toString();
				skipFrame = true;
				break;
			}
		}

		if (skipFrame)
		{
			return;
		}

		encoder = new Encoder(majorVersion, minorVersion);
		// all the constant pools are merged here...
		try
		{
			encoder.addConstantPools(pools);
			if (!debug)
			{
				encoder.disableDebugging();
			}

			// always remove metadata...
			encoder.removeMetadata();

			// keep the following metadata
			/*
			encoder.addMetadataToKeep(StandardDefs.MD_BINDABLE);
			encoder.addMetadataToKeep(StandardDefs.MD_MANAGED);
			encoder.addMetadataToKeep(StandardDefs.MD_CHANGEEVENT);
			encoder.addMetadataToKeep(StandardDefs.MD_NONCOMMITTINGCHANGEEVENT);
			encoder.addMetadataToKeep(StandardDefs.MD_TRANSIENT);
			*/

			// always enable peephole optimization...
			if (runPeephole)
			{
				encoder.enablePeepHole();
			}

			encoder.configure(decoders);
		}
		catch (Throwable ex)
		{
			StringWriter stringWriter = new StringWriter();
			ex.printStackTrace(new PrintWriter(stringWriter));
			assert false : stringWriter.toString();
			return;
		}

		// decode methodInfo...
		for (int j = 0; j < abcSize; j++)
		{
			decoder = decoders[j];
			encoder.useConstantPool(j);

			Decoder.MethodInfo methodInfo = decoder.methodInfo;

			try
			{
				for (int k = 0, infoSize = methodInfo.size(); k < infoSize; k++)
				{
					methodInfo.decode(k, encoder);
				}
			}
			catch (Throwable ex)
			{
				StringWriter stringWriter = new StringWriter();
				ex.printStackTrace(new PrintWriter(stringWriter));
				assert false : stringWriter.toString();
				skipFrame = true;
				break;
			}
		}

		if (skipFrame)
		{
			return;
		}

		// decode metadataInfo...
		for (int j = 0; j < abcSize; j++)
		{
			decoder = decoders[j];
			encoder.useConstantPool(j);

			Decoder.MetaDataInfo metadataInfo = decoder.metadataInfo;

			try
			{
				for (int k = 0, infoSize = metadataInfo.size(); k < infoSize; k++)
				{
					metadataInfo.decode(k, encoder);
				}
			}
			catch (Throwable ex)
			{
				StringWriter stringWriter = new StringWriter();
				ex.printStackTrace(new PrintWriter(stringWriter));
				assert false : stringWriter.toString();
				skipFrame = true;
				break;
			}
		}

		if (skipFrame)
		{
			return;
		}

		// decode classInfo...

		for (int j = 0; j < abcSize; j++)
		{
			decoder = decoders[j];
			encoder.useConstantPool(j);

			Decoder.ClassInfo classInfo = decoder.classInfo;

			try
			{
				for (int k = 0, infoSize = classInfo.size(); k < infoSize; k++)
				{
					classInfo.decodeInstance(k, encoder);
				}
			}
			catch (Throwable ex)
			{
				StringWriter stringWriter = new StringWriter();
				ex.printStackTrace(new PrintWriter(stringWriter));
				assert false : stringWriter.toString();
				skipFrame = true;
				break;
			}
		}

		if (skipFrame)
		{
			return;
		}

		for (int j = 0; j < abcSize; j++)
		{
			decoder = decoders[j];
			encoder.useConstantPool(j);

			Decoder.ClassInfo classInfo = decoder.classInfo;

			try
			{
				for (int k = 0, infoSize = classInfo.size(); k < infoSize; k++)
				{
					classInfo.decodeClass(k, 0, encoder);
				}
			}
			catch (Throwable ex)
			{
				StringWriter stringWriter = new StringWriter();
				ex.printStackTrace(new PrintWriter(stringWriter));
				assert false : stringWriter.toString();
				skipFrame = true;
				break;
			}
		}

		if (skipFrame)
		{
			return;
		}

		// decode scripts...
		for (int j = 0; j < abcSize; j++)
		{
			decoder = decoders[j];
			encoder.useConstantPool(j);

			Decoder.ScriptInfo scriptInfo = decoder.scriptInfo;

			try
			{
				for (int k = 0, scriptSize = scriptInfo.size(); k < scriptSize; k++)
				{
					scriptInfo.decode(k, encoder);
				}
			}
			catch (Throwable ex)
			{
				StringWriter stringWriter = new StringWriter();
				ex.printStackTrace(new PrintWriter(stringWriter));
				assert false : stringWriter.toString();
				skipFrame = true;
				break;
			}
		}

		if (skipFrame)
		{
			return;
		}

		// decode method bodies...
		for (int j = 0; j < abcSize; j++)
		{
			decoder = decoders[j];
			encoder.useConstantPool(j);

			Decoder.MethodBodies methodBodies = decoder.methodBodies;

			try
			{
				for (int k = 0, bodySize = methodBodies.size(); k < bodySize; k++)
				{
					methodBodies.decode(k, 2, encoder);
				}
			}
			catch (Throwable ex)
			{
				StringWriter stringWriter = new StringWriter();
				ex.printStackTrace(new PrintWriter(stringWriter));
				assert false : stringWriter.toString();
				skipFrame = true;
				break;
			}
		}

		if (skipFrame)
		{
			return;
		}

		byte[] abc = encoder.toABC();

		if (abc != null)
		{
			abcList.clear();
			abcList.add(abc);
		}
	}
}


text:
package iso20022

type ExternalBankTransactionFamily1Code string

redpajama_set_name: RedPajamaGithub


text:
package com.deleidos.rtws.commons.util;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Arrays;
import java.util.List;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.deleidos.rtws.commons.config.RtwsConfig;
import com.deleidos.rtws.commons.net.shutdown.LogListingResponse;

/**
 * The Class SimpleLogDirectoryListingSender.
 */
public class SimpleLogDirectoryListingSender implements
		LogDirectoryListingSender, FilenameFilter {

	/** The logger. */
	private Logger logger = LoggerFactory.getLogger(getClass());

	/** The directory. */
	private File directory = null;

	/** The socket. */
	private Socket socket = null;

	/** The output stream. */
	private OutputStream os = null;

	/** The container. */
	private StringBuilder container = new StringBuilder(1024);

	/** The response. */
	private LogListingResponse listingEntry = new LogListingResponse();

	public List<String> directoriesToFilter;

	/*
	 * (non-Javadoc)
	 *
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		if (directory != null && (socket != null || os != null)) {

			directoriesToFilter = Arrays.asList(RtwsConfig.getInstance()
					.getString("log.transport.allowed.filter.directories")
					.split(";"));

			try {
				if (socket != null) {
					os = socket.getOutputStream();
				}

				/*
				 * Note: Response will be in a JSON format dynamically
				 * constructed to reduce memory footprint
				 */
				container.append("{\"directory\":\""
						+ directory.getAbsolutePath() + "\",\"contents\":[\n");

				os.write(container.toString().getBytes());

				container.delete(0, container.length());
				directory.listFiles(this);

				// Close json response
				os.write("{}]}".getBytes());

				if (os != null)
					os.flush();
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.deleidos.rtws.commons.util.LogDirectoryListingSender#setLogDirectory(
	 * java.io.File, java.net.Socket)
	 */
	@Override
	public void setLogDirectory(File directoryOfLogs, Socket socket) {
		this.directory = directoryOfLogs;
		this.socket = socket;
	}

	@Override
	public void setLogDirectory(File directoryOfLogs, OutputStream os) {
		this.directory = directoryOfLogs;
		this.os = os;
	}

	private boolean shouldFilter(String dir) {
		boolean shouldFilter = false;
		for (String dirToFilter : directoriesToFilter) {
			if (dirToFilter.equals(dir))
				shouldFilter = true;
		}

		return shouldFilter;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.io.FilenameFilter#accept(java.io.File, java.lang.String)
	 */
	@Override
	public boolean accept(File dir, String name) {

		LogListingUtil util = new LogListingUtil();
		try {
			if (socket != null) {
				os = socket.getOutputStream();
			}

			File file = new File(dir.getAbsolutePath() + File.separator + name);

			if (file.length() > 0 && file.isFile()) {

				boolean shouldProcess = true;

				if (shouldFilter(dir.getAbsolutePath())) {
					shouldProcess = util.isAcceptable(name);
				}

				if (shouldProcess) {
					listingEntry.setName(name);
					listingEntry.setSize(Long.toString(file.length()));

					container.append(JSONObject.fromObject(listingEntry)
							.toString());
					container.append(",\n");
					os.write(container.toString().getBytes());
					container.delete(0, container.length());
				}
			} else {
				logger.warn("Ignoring log: '{}'", file.getAbsolutePath());
			}
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}

		// returning false to avoid array building of useless entries :)
		return false;
	}
}


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateFollowersTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{

        Schema::create('followers', function(Blueprint $table){

			$table->increments('id');
			$table->integer('user_id')->unsigned();
			$table->foreign('user_id')->references('id')->on('users');

			$table->integer('follower_id')->unsigned();
			$table->foreign('follower_id')->references('id')->on('users');

			$table->unique( array('user_id','follower_id') );

	        $table->timestamps();
	    });

	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
        Schema::drop('followers');
	}

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>G-Index</title>
<meta name="date" content="2016-05-17">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A C D E G L M O R S V

G

getBtnDivision() - Method in class vista.Ventana

getBtnMultiplicacion() - Method in class vista.Ventana

getBtnResta() - Method in class vista.Ventana

getBtnSuma() - Method in class vista.Ventana

getN1() - Method in class modelo.Operaciones

getN1() - Method in class vista.Ventana

getN2() - Method in class modelo.Operaciones

getN2() - Method in class vista.Ventana

getResultado() - Method in class modelo.Operaciones

A C D E G L M O R S V

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
package io.zucchiniui.backend.scenario.domain;

import com.google.common.base.MoreObjects;
import io.zucchiniui.backend.shared.domain.BasicInfo;
import io.zucchiniui.backend.shared.domain.Location;

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

public class Step {

    private BasicInfo info;

    private StepStatus status;

    private String errorMessage;

    private String[][] table;

    private String comment;

    private String output;

    private List<Attachment> attachments = new ArrayList<>();

    private Location definitionLocation;

    /**
     * Private constructor for Morphia.
     */
    private Step() {

    }

    protected Step(final StepBuilder builder) {
        info = Objects.requireNonNull(builder.getInfo());
        status = Objects.requireNonNull(builder.getStatus());
        errorMessage = builder.getErrorMessage();
        table = builder.getTable();
        comment = builder.getComment();
        output = builder.getOutput();
        attachments = builder.getAttachments();
        definitionLocation = builder.getDefinitionLocation();
    }

    public BasicInfo getInfo() {
        return info;
    }

    public StepStatus getStatus() {
        return status;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public String[][] getTable() {
        return table;
    }

    public String getComment() {
        return comment;
    }

    public String getOutput() {
        return output;
    }

    public List<Attachment> getAttachments() {
        return attachments;
    }

    public Location getDefinitionLocation() {
        return definitionLocation;
    }

    protected Step copy() {
        final Step newStep = new Step();
        newStep.info = info;
        newStep.status = status;
        newStep.errorMessage = errorMessage;
        newStep.table = table;
        newStep.comment = comment;
        newStep.output = output;
        newStep.attachments = attachments;
        newStep.definitionLocation = definitionLocation;
        return newStep;
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
            .add("info", info)
            .add("status", status)
            .toString();
    }

    protected void setStatus(final StepStatus newStatus) {
        Objects.requireNonNull(newStatus);

        if (newStatus == status) {
            return;
        }

        status = newStatus;
        if (newStatus != StepStatus.FAILED && newStatus != StepStatus.UNDEFINED) {
            errorMessage = null;
        }
    }

    protected void clearOutput() {
        output = null;
    }

}


text:
require 'test_helper'

###
# This class tests Utils methods.
class TestUtils < Test::Unit::TestCase
  include Orientdb4r::Utils

  def test_verify_options
    opt_pattern = {:a => :mandatory, :b => :optional, :c => 'predefined', :d => [1, false]}
    assert_nothing_thrown do verify_options({:a => 'A', :b => 'B', :c => 'C', :d => 1}, opt_pattern); end

    # missing mandatory
    assert_raise ArgumentError do verify_options({}, opt_pattern); end
    # unknown key
    assert_raise ArgumentError do verify_options({:a => 1, :z => 2}, opt_pattern); end
    # value not in predefined set
    assert_raise ArgumentError do verify_options({:a => 1, :d => 3}, opt_pattern); end
  end

  def test_verify_and_sanitize_options
    opt_pattern = {:a => 'A', :b => 'B'}
    options = {:a => 'X'}
    verify_and_sanitize_options(options, opt_pattern)
    assert_equal 2, options.size
    assert_equal 'X', options[:a]
    assert_equal 'B', options[:b]

    # :optional cannot be set as default value
    opt_pattern = {:a => :optional, :b => 'B'}
    options = {}
    verify_and_sanitize_options(options, opt_pattern)
    assert_equal 1, options.size
    assert !options.include?(:a)
    assert_equal 'B', options[:b]
  end

  def test_compare_versions
    assert_raise ArgumentError do compare_versions 'foo', 'bar'; end
    assert_raise ArgumentError do compare_versions nil, 'bar'; end
    assert_raise ArgumentError do compare_versions 'foo', nil; end
    assert_raise ArgumentError do compare_versions '1.0.0', 'bar'; end
    assert_raise ArgumentError do compare_versions 'foo', '1.0.0'; end
    assert_nothing_thrown do compare_versions '1.0.0', '1.1.0'; end

    assert_equal 0, compare_versions('1.0.0', '1.0.0')
    assert_equal 0, compare_versions('1.2.0', '1.2.0')
    assert_equal 0, compare_versions('1.2.3', '1.2.3')

    assert_equal 1, compare_versions('1.0.1', '1.0.0')
    assert_equal 1, compare_versions('1.1.0', '1.0.0')
    assert_equal 1, compare_versions('2.0.0', '1.0.0')

    assert_equal -1, compare_versions('1.0.0', '1.0.1')
    assert_equal -1, compare_versions('1.0.0', '1.1.0')
    assert_equal -1, compare_versions('1.0.0', '2.0.0')

    # test block
    tmp = -100;
    compare_versions('1.0.0', '1.0.0') { |comp| tmp = comp }
    assert_equal 0, tmp
    compare_versions('1.0.0', '2.0.0') { |comp| tmp = comp }
    assert_equal -1, tmp
    compare_versions('3.0.0', '2.0.0') { |comp| tmp = comp }
    assert_equal 1, tmp
  end

end


text:
<?php

namespace Discord\WebSockets\Events;

use Discord\Parts\Guild\Ban;
use Discord\WebSockets\Event;
use React\Promise\Deferred;

class GuildBanAdd extends Event
{
    /**
     * {@inheritdoc}
     */
    public function handle(Deferred $deferred, $data)
    {
        $guild = $this->discord->guilds->get('id', $data->guild_id);
        $ban   = $this->factory->create(Ban::class, [
            'guild' => $guild,
            'user'  => $data->user,
        ], true);

        $guild = $this->discord->guilds->get('id', $ban->guild->id);
        $guild->bans->push($ban);

        $deferred->resolve($ban);
    }
}


text:
package klaue.furrycrossposter.sites;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.JOptionPane;

import klaue.furrycrossposter.FurryCrossposter;
import klaue.furrycrossposter.ImageInfo;
import klaue.furrycrossposter.ImageInfo.Gender;
import klaue.furrycrossposter.ImageInfo.RatingSexual;
import klaue.furrycrossposter.ImageInfo.RatingViolence;
import klaue.furrycrossposter.ImageTools;
import klaue.furrycrossposter.Tag;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

public class InkBunny extends Site {
	private WebDriver driver;

	@Override
	public boolean doUpload(ImageInfo imageInfo) {
		if (!canUpload(imageInfo)) return false;

		// before we start, let's resize the images, if need be
		Path imagePath = imageInfo.getImagePath();
		Path thumbPath = imageInfo.getThumbPath();

		try {
			BufferedImage image = ImageIO.read(imageInfo.getImagePath().toFile());
			// is image below 36 MP?
			int width          = image.getWidth();
			int height         = image.getHeight();
			if (width * height > 36000000) { // 36 megapixel max
				Path newImgPath = FurryCrossposter.workingDir.resolve(imagePath.getFileName());
				ImageTools.getResizedFile(36000000, image, newImgPath.toFile());
				imagePath = newImgPath;
				// newImgPath.toFile().deleteOnExit(); seems not to work
			}
		} catch (Exception e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, "Could not resize image file that is over 36MP", "Furry Crossposter - InkBunny", JOptionPane.ERROR_MESSAGE);
			return false;
		}

		if (thumbPath != null) {
			try {
				BufferedImage image = ImageIO.read(imageInfo.getThumbPath().toFile());
				// is image below 36 MP?
				int width          = image.getWidth();
				int height         = image.getHeight();
				if (width * height > 36000000) { // 36 megapixel max?
					Path newImgPath = FurryCrossposter.workingDir.resolve(imagePath.getFileName());
					ImageTools.getResizedFile(36000000, image, newImgPath.toFile());
					thumbPath = newImgPath;
					//newImgPath.toFile().deleteOnExit(); seems not to work
				}
			} catch (Exception e) {
				e.printStackTrace();
				JOptionPane.showMessageDialog(null, "Could not resize thumb file that is over 36MP", "Furry Crossposter - InkBunny", JOptionPane.ERROR_MESSAGE);
				return false;
			}
		}

		driver = getDriver();

		driver.get("https://inkbunny.net/login.php");

		// wait for login
		WebDriverWait wait = new WebDriverWait(driver, 60);
		wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("privatemessage_notification")));

		// go to upload (menu will only show on hover)
		WebElement menu = driver.findElement(By.xpath("//div[@id='usernavigation']/div[4]/ul/li[2]"));
		//build and perform the mouseOver with Advanced User Interactions API
		Actions builder = new Actions(driver);
		builder.moveToElement(menu).build().perform();
		driver.findElement(By.xpath("//div[@id='usernavigation']/div[4]/ul/li[2]/ul/li/a/span")).click();

		// upload image and thumb, wait for upload to complete, give it 2 mins
		driver.findElement(By.name("uploadedfile[]")).sendKeys(imagePath.toString());

		if (thumbPath != null) {
			driver.findElement(By.name("uploadedthumbnail[]")).sendKeys(thumbPath.toString());
		}
		driver.findElement(By.xpath("//input[@value='Upload']")).click();
		wait = new WebDriverWait(driver, 120);
		WebElement elem = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@value='Next >']")));
		elem.click();

		// image type, only change if sketch
		if (imageInfo.getType() == ImageInfo.Type.SKETCH) {
			new Select(driver.findElement(By.id("typeselector"))).selectByVisibleText("Sketch");
		}

		if (imageInfo.isToScraps()) {
			driver.findElement(By.id("scraps")).click();
		}

		driver.findElement(By.name("title")).clear();
		driver.findElement(By.name("title")).sendKeys(imageInfo.getTitle());

		if (!imageInfo.getDescription().trim().isEmpty()) {
			driver.findElement(By.id("desc")).clear();
			driver.findElement(By.id("desc")).sendKeys(imageInfo.getDescription());
		}

		// gender
		if (imageInfo.getGenders().size() > 0) {
			StringBuffer genders = new StringBuffer();
			boolean containsIntersex = false;
			boolean containsTrans = false;
			for (Gender gender : imageInfo.getGenders()) {
				genders.append(gender.getTag()).append(" ");
				if (!containsIntersex) containsIntersex = !(gender.equals(Gender.M2F) || gender.equals(Gender.F2M) || gender.equals(Gender.MALE) || gender.equals(Gender.FEMALE) || gender.equals(Gender.AMBIGUOUS));
				if (!containsTrans) containsTrans = (gender.equals(Gender.M2F) || gender.equals(Gender.F2M));
			}
			genders.deleteCharAt(genders.length() - 1);
			if (containsIntersex) genders.append(" intersex");
			if (containsTrans) genders.append(" gender_transformation");

			driver.findElement(By.id("keywords_sexgender")).sendKeys(genders.toString());
		} else {
			driver.findElement(By.id("keywords_sexgender_na")).click();
		}

		// species
		if (imageInfo.getSpeciesTags().size() > 0) {
			StringBuffer animals = new StringBuffer();
			for (String species : imageInfo.getSpeciesTags()) {
				animals.append(species).append(" ");
			}
			animals.deleteCharAt(animals.length() - 1);
			driver.findElement(By.id("keywords_species")).sendKeys(animals.toString());
		} else {
			driver.findElement(By.id("keywords_species_na")).click();
		}

		// themes
		if (imageInfo.getKinkTags().size() > 0) {
			StringBuffer kinks = new StringBuffer();
			for (String kink : imageInfo.getKinkTags()) {
				kinks.append(kink).append(" ");
			}
			kinks.deleteCharAt(kinks.length() - 1);
			driver.findElement(By.id("keywords_themes")).sendKeys(kinks.toString());
		} else {
			driver.findElement(By.id("keywords_themes_na")).click();
		}

		// others
		if (imageInfo.getOtherTags().size() > 0) {
			StringBuffer others = new StringBuffer();
			for (String other : imageInfo.getOtherTags()) {
				others.append(other).append(" ");
			}
			others.deleteCharAt(others.length() - 1);
			driver.findElement(By.id("keywords_other")).sendKeys(others.toString());
		}

		// rating
		if (imageInfo.getSexualRating() == RatingSexual.NONE && imageInfo.getViolenceRating() == RatingViolence.NONE) {
			driver.findElement(By.id("general_norating")).click();
		} else {
			if (imageInfo.getSexualRating() == RatingSexual.NUDITY_MOD) {
				driver.findElement(By.id("ct_2")).click();
			} else if (imageInfo.getSexualRating() == RatingSexual.NUDITY_EX) {
				driver.findElement(By.id("ct_4")).click();
			}

			if (imageInfo.getViolenceRating() == RatingViolence.VIOLENCE_MOD) {
				driver.findElement(By.id("ct_3")).click();
			} else if (imageInfo.getViolenceRating() == RatingViolence.VIOLENCE_EX) {
				driver.findElement(By.id("ct_5")).click();
			}
		}

		if (imageInfo.getFolders().size() > 0) {
			driver.findElement(By.id("pools")).click();
		}

		if (imageInfo.isFriendsOnly()) {
			driver.findElement(By.id("friends_only")).click();
		}

		if (imageInfo.isUnlisted()) {
			new Select(driver.findElement(By.name("visibility"))).selectByValue("no");
		} else if(imageInfo.hasNoNotification()) {
			new Select(driver.findElement(By.name("visibility"))).selectByValue("yes_nowatch");
		}

		driver.findElement(By.xpath("//input[@value='Next >']")).click();

		if (imageInfo.getFolders().size() > 0) {
			// we selected the pool button, so now we're at pool choosing
			List<WebElement> poolLinks = driver.findElements(By.xpath("//a[contains(@href, 'poolview_process.php?pool_id=')]"));

			//boolean poolFound = false;
			for (WebElement element : poolLinks) {
				String text = element.getText().trim().toLowerCase().replace(" ", "_");
				if (imageInfo.getFolders().contains(text)) {
					//poolFound = true;
					String href = element.getAttribute("href");
					int start = href.indexOf("pool_id=") + 8;
					String poolId = href.substring(start);
					driver.findElement(By.xpath("//a[contains(@onclick, '" + poolId + "') and @title='Add to Pool']")).click();
				}
			}

			driver.findElement(By.xpath("//input[@value='Done']")).click();
		}

		showFinishMessage(driver);

		// delete img/thumb if resized to working dir
		try {
			if (imagePath.getParent().equals(FurryCrossposter.workingDir)) Files.delete(imagePath);
			if (thumbPath != null && thumbPath.getParent().equals(FurryCrossposter.workingDir))  Files.delete(thumbPath);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		//driver.quit();
		return true;
	}

	@Override
	public ArrayList<String> getErrorReasons(ImageInfo imageInfo) {
		ArrayList<String> reasons = new ArrayList<String>();

		/*
		 * main image
		 */
		// does file exist?
		if (imageInfo.getImagePath() == null || !Files.exists(imageInfo.getImagePath())) {
			reasons.add("no image");
		} else {
			// is file of correct type?
			int i = imageInfo.getImagePath().getFileName().toString().lastIndexOf('.');
			String extension = "";
			if (i > 0) {
				extension = imageInfo.getImagePath().getFileName().toString().substring(i+1).toLowerCase();
			}
			if (!extension.equals("jpeg") && !extension.equals("jpg") && !extension.equals("png") && !extension.equals("gif")) {
				reasons.add("unsupported image type ." + extension);
			} else {
				// how about filesize
				try {
					long bytes = Files.size(imageInfo.getImagePath());
					if (bytes > 36 * 1024 * 1024) { // 36 MB
						reasons.add("image file too large (>36MB)");
					}
				} catch (IOException e) {
					e.printStackTrace();
					// shouldn't happen, but let's assume it's correct
				}
			}
		}

		/*
		 * thumb
		 */
		// only if set
		if (imageInfo.getThumbPath() != null && Files.exists(imageInfo.getThumbPath())) {
			// is file of correct type?
			int i = imageInfo.getThumbPath().getFileName().toString().lastIndexOf('.');
			String extension = "";
			if (i > 0) {
				extension = imageInfo.getThumbPath().getFileName().toString().substring(i+1).toLowerCase();
			}
			if (!extension.equals("jpeg") && !extension.equals("jpg") && !extension.equals("png") && !extension.equals("gif")) {
				reasons.add("unsupported thumb image type ." + extension);
			} else {
				// how about filesize
				try {
					long bytes = Files.size(imageInfo.getThumbPath());
					if (bytes > 36 * 1024 * 1024) { // 36 MB
						reasons.add("thumb file too large (>36MB)");
					}
				} catch (IOException e) {
					e.printStackTrace();
					// shouldn't happen, but let's assume it's correct
				}
			}
		}

		if (imageInfo.getTitle().isEmpty()) reasons.add("no title");
		if (imageInfo.getDescription().length() >= 100000) reasons.add("description too long (>100000 characters)");

		// https://wiki.inkbunny.net/wiki/Keyword_Policy#Minimum_Required_Keywords
		if (imageInfo.getGenders().size() == 0) reasons.add("no genders set");
		boolean foundCorrect = false;
		for (String species : imageInfo.getSpeciesTags()) {
			Tag tag = FurryCrossposter.tags.get(species);
			if (tag == null || tag.getType() != Tag.Type.SPECIES) continue;
			foundCorrect = true;
			break;
		}
		if (!foundCorrect) reasons.add("no species set");

		foundCorrect = false;
		ArrayList<String> cummulativeTags = new ArrayList<String>();
		cummulativeTags.addAll(imageInfo.getKinkTags());
		cummulativeTags.addAll(imageInfo.getOtherTags());
		for (String other : cummulativeTags) {
			Tag tag = FurryCrossposter.tags.get(other);
			if (tag == null || tag.getType() != Tag.Type.GENERAL) continue;
			foundCorrect = true;
			break;
		}
		if (!foundCorrect) reasons.add("no themes set");

		// cannot be both at same time, but unlisted implies the other
		//if (imageInfo.isUnlisted() && imageInfo.hasNoNotification()) reasons.add("");

		//https://wiki.inkbunny.net/wiki/ACP
		if (imageInfo.getSexualRating() != ImageInfo.RatingSexual.NONE && imageInfo.getSpeciesTags().contains("human")) {
			reasons.add("humans in sexual context");
		}

		return reasons;
	}

	@Override
	public ArrayList<String> getWarningReasons(ImageInfo imageInfo) {
		ArrayList<String> reasons = new ArrayList<String>();

		try {
			BufferedImage image = ImageIO.read(imageInfo.getImagePath().toFile());
			// is image below 36 MP?
			int width          = image.getWidth();
			int height         = image.getHeight();
			if (width * height > 36000000) { // 36 megapixel max
				reasons.add("image too large (>36MP), will be resized before upload");
			}

			if (imageInfo.getThumbPath() != null) {
				image = ImageIO.read(imageInfo.getThumbPath().toFile());
				// is image below 36 MP?
				width          = image.getWidth();
				height         = image.getHeight();
				if (width * height > 36000000) { // 36 megapixel max?
					reasons.add("thumb too large (>36MP), will be resized before upload");
				}
			}
		} catch (IOException e) {
			// If that generates an error, getErrorReasons() or the main window image display would already
			// have reported it, eat the error
			e.printStackTrace();
		}

		return reasons;
	}

	@Override
	public String getName() {
		return "InkBunny";
	}

}


text:
'''
Routines to make it easier to process C and C++.
'''

import re, collections

_hash_block_pat = re.compile('[ \t]*(#[ \t]*(if(n?def)?|endif|else))(?![a-zA-Z0-9_])')

MASK_CPP_COMMENTS = 1
MASK_C_COMMENTS = 2
MASK_LITERALS = 3
MASK_IF_0 = 4

'''

'''
region = collections.namedtuple('region', ['begin', 'end', 'line_num', 'region_type', 'hash_start_line_num'])

class _parse_state:
    def __init__(self, txt):
        self.txt = txt
        self.i = 0
        self.end = len(txt)
        self.regions = []
        self.func = _code_region
        self.line_num = 1
    def log(self):
        return
        name = 'None'
        if self.func:
            name = self.func.func_name
        print('In %s at index %s (line %s, %s...)' % (name, self.i, self.line_num, repr(self.txt[self.i:self.i+3])))

def _save_region(state, end, region_type, hash_line_num=None):
    state.regions.append(region(state.i, end, state.line_num, region_type, hash_line_num))
    state.i = end

def _double_quote_region(state):
    state.log()
    i = state.i + 1
    while i < state.end:
        c = state.txt[i]
        if c == '\\':
            i += 2
        elif c == '"':
            i += 1
            break
        elif c == '\n':
            break
        else:
            i += 1
    if i >= state.end:
        state.func = None
    else:
        state.func = _code_region
    _save_region(state, i, '"')

def _save_code_region_if_not_empty(state, end):
    if end > state.i:
        _save_region(state, end, 'code')

def _code_region(state):
    state.log()
    # Use a temporary idx until we know we have to hand control to another func.
    i = state.i

    # When we begin scanning, behave the same way we do right after we find '\n'...
    previous_was_line_break = (i == 0)

    while True:

        # Any time we start a new line in the default state, look for preprocessor
        # directives that would cause us to recognize "section" boundaries...
        if previous_was_line_break:
            previous_was_line_break = False
            next_chunk = state.txt[i:i+80]
            m = _hash_block_pat.match(next_chunk)
            if m:
                _save_code_region_if_not_empty(state, i)
                i = _find_end_of_condition(state.txt, m, i)
                _save_region(state, i, '#%s' % m.group(2), state.line_num)
                if i >= state.end:
                    state.func = None
                    break

        c = state.txt[i]
        if c == '"':
            _save_code_region_if_not_empty(state, i)
            state.func = _double_quote_region
            break
        elif c == "'":
            i += 2
            first = txt[i]
            if first == '\\':
                i += 1
            assert txt[i - 1] == "'"
        elif c == '/':
            second = state.txt[i + 1]
            if second == '/':
                _save_code_region_if_not_empty(state, i)
                i = state.txt.find('\n', i + 2)
                if i == -1:
                    i = state.end
                else:
                    i += 1
                _save_region(state, i, '//')
                state.line_num += 1
            elif second == '*':
                _save_code_region_if_not_empty(state, i)
                x = state.i
                i = state.txt.find('*/', i + 2)
                if i == -1:
                    i = state.end
                else:
                    i += 2
                _save_region(state, i, '/*')
                state.line_num += state.txt[x:i].count('\n')
            else:
                i += 1
        elif c == '\n':
            i += 1
            state.line_num += 1
            previous_was_line_break = True
        else:
            i += 1
        if i >= state.end:
            _save_code_region_if_not_empty(state, i)
            state.func = None
            state.log()
            break
    state.i = i

def _find_end_of_condition(txt, m, offset = 0):
    end = m.end() + offset
    i = txt.find('\n', end)
    if i > -1:
        rest = txt[end:i]
        j = rest.find('//')
        k = rest.find('/*')
        if k > -1 and (k < j or j == -1):
            j = k
        if j != -1:
            return m.end() + offset + j
        # Consume line break to avoid clutter
        return i + 1
    else:
        j = txt.find('//', end)
        k = txt.find('/*', end)
        if k > -1 and (k < j or j == -1):
            j = k
        if j != -1:
            return j
    return len(txt)

def find_code_regions(txt):
    '''
    Break C/C++ code into logical regions based on a simple scan. This allows
    processors to correctly parse string literals, comments, and #ifdefs without
    becoming confused and without re-inventing the wheel.

    A region

    @return a list of region tuples (begin, end, line_num, region_type, hash_start_line_num).
    '''
    state = _parse_state(txt)
    while state.func and (state.i < state.end):
        state.func(state)
    return state.regions

def _get_maskable_range(r):
    if r.region_type == '//':
        return r.begin + 2, r.end
    elif r.region_type == '/*':
        return r.begin + 2, r.end - 2
    elif r.region_type == '"':
        return r.begin + 1, r.end - 1
    elif r.region_type == '#':
        m = _hash_block_pat.match(txt[r.begin:])
        assert m
        return r.begin + m.end(1)
    else:
        return r.begin, r.end

def _mask_regions_of_type(txt, regions, region_type, mask_char):
    for r in regions:
        if r.region_type == region_type:
            begin, end = _get_maskable_range(r)
            prefix = txt[0:begin]
            suffix = txt[end:]
            infix = ''
            for i in xrange(begin, end):
                c = txt[i]
                if c != '\n':
                    c = mask_char
                infix += c
            txt = prefix + infix + suffix
    return txt

mask_code = 1
mask_c_comments = 2
mask_cpp_comments = 4
mask_strings = 8
mask_conditions = 16

code_mask_char = '-'
c_comments_mask_char = '*'
cpp_comments_mask_char = '/'
strings_mask_char = '.'
conditions_mask_char = 'X'
default_mask_chars = code_mask_char + comments_mask_char + strings_mask_char + conditions_mask_char

def mask(txt, mask_bitmask, mask_chars=default_mask_chars):
    '''
    Hide some aspects of code using a char that replaces so regex and search/replace operations won't
    be confused. Line numbers are preserved.
    '''
    if not mask_bitmask:
        return txt
    regions = find_code_regions(txt)
    if mask_chars & mask_code:
        txt = _mask_regions_of_type(txt, regions, 'code', mask_chars[0])
    if mask_chars & mask_c_comments:
        txt = _mask_regions_of_type(txt, regions, '/*', mask_chars[1])
    if mask_chars & mask_cpp_comments:
        txt = _mask_regions_of_type(txt, regions, '//', mask_chars[2])
    if mask_chars & mask_strings:
        txt = _mask_regions_of_type(txt, regions, '"', mask_chars[3])
    if mask_chars & mask_conditions:
        txt = _mask_regions_of_type(txt, regions, '#', mask_chars[4])
    return txt

if __name__ == '__main__':
    import os, sys
    if len(sys.argv) == 2 and not re.match('-?-h(elp)?', sys.argv[1]):
        with open(sys.argv[1], 'r') as f:
            txt = f.read()
        regions = find_code_regions(txt)
        i = 0
        for r in regions:
            print('%s: %s' % (i, r))
            i += 1
    else:
        print('python %s FNAME -- print code regions in FNAME.' % os.path.split(__file__)[1])


text:
/*
 * dyn_ring_queue.c
 *
 *  Created on: May 31, 2014
 *      Author: mdo
 */

#include "dyn_array.h"
#include "dyn_core.h"
#include "dyn_gossip.h"
#include "dyn_ring_queue.h"
#include "dyn_token.h"

//should use pooling to store struct ring_message so that we can reuse
struct ring_msg *
create_ring_msg(void)
{
	struct ring_msg *msg = dn_alloc(sizeof(*msg));

	if (msg == NULL)
		return NULL;

	ring_msg_init(msg, 1, true);
	msg->data = NULL;

	return msg;
}

struct ring_msg *
create_ring_msg_with_data(int capacity)
{
	struct ring_msg *msg = dn_alloc(sizeof(*msg));

	if (msg == NULL)
		return NULL;

	rstatus_t status = ring_msg_init(msg, 1, true);
	if (status != DN_OK) {
		dn_free(msg);
		return NULL;
	}

	msg->data = dn_zalloc(sizeof(uint8_t) * capacity);
	msg->capacity = capacity;
	msg->len = 0;

	return msg;
}

struct ring_msg *
create_ring_msg_with_size(uint32_t size, bool init_node)
{
	struct ring_msg *msg = dn_alloc(sizeof(*msg));

	if (msg == NULL)
		return NULL;

	rstatus_t status = ring_msg_init(msg, size, init_node);
	if (status != DN_OK) {
		dn_free(msg);
		return NULL;
	}

	msg->data = NULL;
	msg->capacity = 0;
	msg->len = 0;

	return msg;
}

rstatus_t
ring_msg_init(struct ring_msg *msg, uint32_t n, bool init_node)
{
	if (msg == NULL)
		return DN_ERROR;

	rstatus_t status = array_init(&msg->nodes, n, sizeof(struct node));
	if (status != DN_OK)
		return status;

	if (init_node) {
		uint32_t i;
		for(i=0; i<n; i++) {
			struct node *node = array_push(&msg->nodes);
			node_init(node);
		}
	}

	return DN_OK;
}

rstatus_t
ring_msg_deinit(struct ring_msg *msg)
{
	if (msg == NULL)
		return DN_ERROR;

	uint32_t i;
	for(i=0; i<array_n(&msg->nodes); i++) {
		struct node *node = array_get(&msg->nodes, i);
		node_deinit(node);
	}
	array_deinit(&msg->nodes);

	if (msg->data != NULL) {
		dn_free(msg->data);
	}

	dn_free(msg);

	return DN_OK;
}

struct node *
create_node()
{
	struct node *result = dn_alloc(sizeof(*result));
	node_init(result);

	return result;
}

rstatus_t
node_init(struct node *node)
{
	if (node == NULL)
		return DN_ERROR;

	init_dyn_token(&node->token);
	string_init(&node->dc);
	string_init(&node->rack);
	string_init(&node->name);
	string_init(&node->pname);

	node->port = 8101;

	node->next_retry = 0;
	node->last_retry = 0;
	node->failure_count = 0;

	node->is_seed = false;
	node->is_local = false;
	node->state = INIT;

	return DN_OK;
}

rstatus_t
node_deinit(struct node *node)
{
	if (node == NULL)
		return DN_ERROR;

	//array_deinit(&node->tokens);
	string_deinit(&node->dc);
	string_deinit(&node->rack);
	string_deinit(&node->name);
	string_deinit(&node->pname);
	deinit_dyn_token(&node->token);

	//dn_free(node);

	return DN_OK;
}

rstatus_t
node_copy(const struct node *src, struct node *dst)
{
	if (src == NULL || dst == NULL)
		return DN_ERROR;

	dst->state = src->state;
	dst->is_local = src->is_local;
	dst->is_seed = src->is_seed;
	dst->failure_count = src->failure_count;
	dst->last_retry = src->last_retry;
	dst->next_retry = src->next_retry;
	dst->port = src->port;
	dst->is_secure = src->is_secure;

	string_copy(&dst->pname, src->pname.data, src->pname.len);
	string_copy(&dst->name, src->name.data, src->name.len);
	string_copy(&dst->rack, src->rack.data, src->rack.len);
	string_copy(&dst->dc, src->dc.data, src->dc.len);

	copy_dyn_token(&src->token, &dst->token);
    return DN_OK;
}


text:
declare module ContentType {
    interface StaticFunctions {
        parse(string: string): MediaType;
        parse(req: { headers: any; }): MediaType;
        parse(res: { getHeader(key: string): string; }): MediaType;
        format(obj: MediaType): string;
    }

    interface MediaType {
        type: string;
        parameters?: any;
    }
}

declare module "content-type" {
    var x: ContentType.StaticFunctions;
    export = x;
}


text:
package com.lyy.yugioh.activity;

import java.util.ArrayList;
import java.util.Set;
import com.lyy.yugioh.R;
import com.lyy.yugioh.adapter.CardAdapter;
import com.lyy.yugioh.db.CardEntity;
import com.lyy.yugioh.db.OrmliteDbHelper;
import com.lyy.yugioh.utils.U;
import com.slidingmenu.lib.SlidingMenu;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Intent;
import android.graphics.Bitmap;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity implements IActivity, OnItemClickListener, TextWatcher, Callback, OnClickListener
{

	private EditText met_search;
	private ListView mlv_cards;
	private TextView mtv_count;
	private CardAdapter mAdapter;
	private ArrayList<CardEntity> cards;
	private Handler handler;
	private boolean isExit = false;
	private SlidingMenu slidingMenu;
	private ViewHolder viewHolder;
	private Builder bType, bType2, bCamp, bRare, bBan, bAttribute, bRace;
	private AlertDialog adType, adType2, adCamp, adRare, adBan, adAttribute, adRace;
	private ListView lvCamp, lvType2, lvBan, lvAttribute;
	private GridView gvType, gvRare, gvRace;

	private String cardName, cardCamp, cardRare, cardBan, cardType, cardType2, cardStarNum, cardAttribute, cardRace, cardAtk, cardDef;
	public static ImageView iv_add;

	private class ViewHolder
	{
		TextView tv_startSearch, tv_search, tv_reset, tv_banList, tv_cardSet;
		EditText et_name, et_camp, et_rare, et_ban, et_type, et_type2, et_starNum, et_attribute, et_race, et_atk, et_def;
		LinearLayout layout_search, layout_monster;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		findViews();
		initVars();
		setListeners();
	}

	@Override
	public void findViews()
	{
		met_search = (EditText) findViewById(R.id.search);
		mlv_cards = (ListView) findViewById(R.id.cards);
		mtv_count = (TextView) findViewById(R.id.count);
	}

	@Override
	public void initVars()
	{
		handler = new Handler(this);
		if (U.results != null)
		{
			cards = U.results;
			mAdapter = new CardAdapter(this, cards);
			mlv_cards.setAdapter(mAdapter);
			mtv_count.setText("显示" + cards.size() + "张卡片");
		}
		initSlidingMenu();
		initDialog();
	}

	@Override
	public void setListeners()
	{
		met_search.addTextChangedListener(this);
		mlv_cards.setOnItemClickListener(this);

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
	{
		U.selectCard = cards.get(position);
		Intent intent = new Intent();
		intent.putExtra("screenOrientation", "v");
		intent.setClass(this, InfoActivity.class);
		startActivity(intent);
	}

	@Override
	public void afterTextChanged(Editable s)
	{
		String text = met_search.getText().toString().toLowerCase();
		if (!TextUtils.isEmpty(text))
		{
			cards = new ArrayList<CardEntity>();
			for (int i = 0; i < U.upperResult.size(); i++)
			{
				CardEntity entity = U.upperResult.get(i);
				if (entity.getSCCardAttribute().contains(text) || entity.getSCCardBan().contains(text) || entity.getSCCardDepict().contains(text) || entity.getSCCardName().contains(text)
						|| entity.getSCCardRace().contains(text) || entity.getSCCardRare().contains(text) || entity.getSCCardType().contains(text) || entity.getCardStarNumStr().contains(text))
				{
					cards.add(U.results.get(i));
				}
			}
		} else
		{
			cards = U.results;
		}
		mAdapter = new CardAdapter(this, cards);
		mlv_cards.setAdapter(mAdapter);
		mtv_count.setText("显示" + cards.size() + "张卡片");

	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after)
	{

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count)
	{

	}

	@Override
	public void onBackPressed()
	{
		if (!isExit)
		{
			isExit = true;
			U.sysOut(this, "再按一次退出查卡器");
			handler.sendEmptyMessageDelayed(0, 3000);
		} else
		{
			try
			{
				OrmliteDbHelper.getConnection().close();
				OrmliteDbHelper.getInstance().close();
				if (U.imageBuffer.size() > 0)
				{
					Set<String> keys = U.imageBuffer.keySet();
					for (String key : keys)
					{
						Bitmap bm = U.imageBuffer.get(key);
						if (bm != null && !bm.isRecycled())
						{
							bm.recycle();
							bm = null;
						}
					}
					U.imageBuffer.clear();
				}
			} catch (Exception e)
			{
				e.printStackTrace();
			}
			System.exit(0);
		}
	}

	@Override
	public boolean handleMessage(Message msg)
	{
		switch (msg.what)
		{
		case 0:
			isExit = false;
			break;
		default:
			break;
		}
		return false;
	}

	public void initSlidingMenu()
	{
		slidingMenu = new SlidingMenu(this);
		slidingMenu.setMode(SlidingMenu.LEFT);
		slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
		slidingMenu.setShadowWidthRes(R.dimen.shadow_width);
		slidingMenu.setShadowDrawable(R.drawable.shadow);
		slidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		slidingMenu.setFadeDegree(0.8f);
		slidingMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
		slidingMenu.setMenu(R.layout.layout_sliding);

		viewHolder = new ViewHolder();
		viewHolder.tv_startSearch = (TextView) slidingMenu.findViewById(R.id.tv_startSearch);
		viewHolder.tv_banList = (TextView) slidingMenu.findViewById(R.id.tv_banList);
		viewHolder.tv_cardSet = (TextView) slidingMenu.findViewById(R.id.tv_cardSet);
		viewHolder.tv_search = (TextView) slidingMenu.findViewById(R.id.tv_search);
		viewHolder.tv_reset = (TextView) slidingMenu.findViewById(R.id.tv_reset);
		viewHolder.et_name = (EditText) slidingMenu.findViewById(R.id.et_name);
		viewHolder.et_camp = (EditText) slidingMenu.findViewById(R.id.et_camp);
		viewHolder.et_rare = (EditText) slidingMenu.findViewById(R.id.et_rare);
		viewHolder.et_ban = (EditText) slidingMenu.findViewById(R.id.et_ban);
		viewHolder.et_type = (EditText) slidingMenu.findViewById(R.id.et_type);
		viewHolder.et_type2 = (EditText) slidingMenu.findViewById(R.id.et_type2);
		viewHolder.et_starNum = (EditText) slidingMenu.findViewById(R.id.et_starNum);
		viewHolder.et_attribute = (EditText) slidingMenu.findViewById(R.id.et_attribute);
		viewHolder.et_race = (EditText) slidingMenu.findViewById(R.id.et_race);
		viewHolder.et_atk = (EditText) slidingMenu.findViewById(R.id.et_atk);
		viewHolder.et_def = (EditText) slidingMenu.findViewById(R.id.et_def);
		viewHolder.layout_search = (LinearLayout) slidingMenu.findViewById(R.id.layout_search);
		viewHolder.layout_monster = (LinearLayout) slidingMenu.findViewById(R.id.layout_monster);

		viewHolder.tv_startSearch.setOnClickListener(this);
		viewHolder.tv_banList.setOnClickListener(this);
		viewHolder.tv_cardSet.setOnClickListener(this);
		viewHolder.et_camp.setOnClickListener(this);
		viewHolder.et_type.setOnClickListener(this);
		viewHolder.et_type2.setOnClickListener(this);
		viewHolder.tv_search.setOnClickListener(this);
		viewHolder.tv_reset.setOnClickListener(this);
		viewHolder.et_rare.setOnClickListener(this);
		viewHolder.et_ban.setOnClickListener(this);
		viewHolder.et_attribute.setOnClickListener(this);
		viewHolder.et_race.setOnClickListener(this);

	}

	public void initDialog()
	{
		// 卡片归属窗口初始化
		bCamp = new Builder(this).setTitle("卡片归属");
		adCamp = bCamp.create();
		lvCamp = new ListView(this);
		lvCamp.setAdapter(new ArrayAdapter<String>(MainActivity.this, R.layout.item_grid_text, U.CARDCAMP));
		lvCamp.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> gv, View v, int position, long arg3)
			{
				String camp = U.CARDCAMP[position];
				viewHolder.et_camp.setText(camp);
				adCamp.dismiss();
			}
		});
		adCamp.setView(lvCamp, 0, 0, 0, 0);

		// 卡片类型窗口初始化
		bType = new Builder(this).setTitle("卡片类型");
		adType = bType.create();
		gvType = new GridView(this);
		gvType.setNumColumns(2);
		gvType.setAdapter(new ArrayAdapter<String>(MainActivity.this, R.layout.item_grid_text, U.CARDTYPE));
		gvType.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> gv, View v, int position, long arg3)
			{
				String type = U.CARDTYPE[position];
				viewHolder.et_type.setText(type);
				if (type.contains("怪兽"))
				{
					viewHolder.layout_monster.setVisibility(View.VISIBLE);
					viewHolder.et_type2.setEnabled(true);
				} else
				{
					viewHolder.layout_monster.setVisibility(View.GONE);
					viewHolder.et_type2.setEnabled(false);
					viewHolder.et_type2.setText("不限");
				}
				adType.dismiss();
			}
		});
		adType.setView(gvType, 0, 0, 0, 0);

		// 卡片类型2窗口初始化
		bType2 = new Builder(this);
		adType2 = bType2.create();
		lvType2 = new ListView(this);
		lvType2.setAdapter(new ArrayAdapter<String>(this, R.layout.item_grid_text, U.CARDTYPE2));
		lvType2.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
			{
				String type2 = U.CARDTYPE2[position];
				viewHolder.et_type2.setText(type2);
				adType2.dismiss();
			}
		});
		adType2.setView(lvType2, 0, 0, 0, 0);

		// 罕见程度窗口初始化
		bRare = new Builder(this).setTitle("罕见程度");
		adRare = bRare.create();
		gvRare = new GridView(this);
		gvRare.setNumColumns(2);
		gvRare.setAdapter(new ArrayAdapter<String>(this, R.layout.item_grid_text, U.CARDRARE));
		gvRare.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
			{
				String rare = U.CARDRARE[position];
				viewHolder.et_rare.setText(rare);
				adRare.dismiss();
			}
		});
		adRare.setView(gvRare, 0, 0, 0, 0);

		// 禁限卡表窗口初始化
		bBan = new Builder(this);
		adBan = bBan.create();
		lvBan = new ListView(this);
		lvBan.setAdapter(new ArrayAdapter<String>(this, R.layout.item_grid_text, U.CARDBAN));
		lvBan.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
			{
				String ban = U.CARDBAN[position];
				viewHolder.et_ban.setText(ban);
				adBan.dismiss();
			}
		});
		adBan.setView(lvBan, 0, 0, 0, 0);

		// 卡片属性窗口初始化
		bAttribute = new Builder(this);
		adAttribute = bAttribute.create();
		lvAttribute = new ListView(this);
		lvAttribute.setAdapter(new ArrayAdapter<String>(this, R.layout.item_grid_text, U.CARDATTRIBUTE));
		lvAttribute.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
			{
				String attribute = U.CARDATTRIBUTE[position];
				viewHolder.et_attribute.setText(attribute);
				adAttribute.dismiss();
			}
		});
		adAttribute.setView(lvAttribute, 0, 0, 0, 0);

		// 卡片种族窗口初始化
		bRace = new Builder(this);
		adRace = bRace.create();
		gvRace = new GridView(this);
		gvRace.setNumColumns(2);
		gvRace.setAdapter(new ArrayAdapter<String>(this, R.layout.item_grid_text, U.CARDRACE));
		gvRace.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
			{
				String race = U.CARDRACE[position];
				viewHolder.et_race.setText(race);
				adRace.dismiss();
			}
		});
		adRace.setView(gvRace, 0, 0, 0, 0);

	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.tv_startSearch:
			if (viewHolder.layout_search.getVisibility() == View.GONE)
			{
				viewHolder.layout_search.setVisibility(View.VISIBLE);
			} else
			{
				viewHolder.layout_search.setVisibility(View.GONE);
			}
			break;
		case R.id.tv_banList:
			Intent intentBan = new Intent();
			intentBan.setClass(this, BanActivity.class);
			startActivity(intentBan);
			break;
		case R.id.tv_cardSet:
			Intent intentSet = new Intent();
			intentSet.setClass(this, CardSetActivity.class);
			startActivity(intentSet);
			break;
		case R.id.tv_search:
			cards = new ArrayList<CardEntity>();
			cardName = viewHolder.et_name.getText().toString();
			cardCamp = viewHolder.et_camp.getText().toString();
			cardRare = viewHolder.et_rare.getText().toString();
			cardBan = viewHolder.et_ban.getText().toString();
			cardType = viewHolder.et_type.getText().toString();
			cardType2 = viewHolder.et_type2.getText().toString();
			cardStarNum = viewHolder.et_starNum.getText().toString();
			cardAttribute = viewHolder.et_attribute.getText().toString();
			cardRace = viewHolder.et_race.getText().toString();
			cardAtk = viewHolder.et_atk.getText().toString();
			cardDef = viewHolder.et_def.getText().toString();
			for (CardEntity entity : U.results)
			{
				if (isSearched(entity))
					cards.add(entity);
			}
			mAdapter = new CardAdapter(this, cards);
			mlv_cards.setAdapter(mAdapter);
			mtv_count.setText("显示" + cards.size() + "张卡片");
			break;
		case R.id.tv_reset:
			viewHolder.et_name.setText("");
			viewHolder.et_camp.setText("不限");
			viewHolder.et_rare.setText("不限");
			viewHolder.et_ban.setText("不限");
			viewHolder.et_type.setText("不限");
			viewHolder.et_type2.setText("不限");
			viewHolder.et_type2.setEnabled(false);
			viewHolder.et_starNum.setText("");
			viewHolder.et_attribute.setText("不限");
			viewHolder.et_race.setText("不限");
			viewHolder.et_atk.setText("");
			viewHolder.et_def.setText("");
			break;
		case R.id.et_camp:
			adCamp.show();
			break;
		case R.id.et_type:
			adType.show();
			break;
		case R.id.et_type2:
			adType2.show();
			break;
		case R.id.et_rare:
			adRare.show();
			break;
		case R.id.et_ban:
			adBan.show();
			break;
		case R.id.et_race:
			adRace.show();
			break;
		case R.id.et_attribute:
			adAttribute.show();
			break;

		default:
			break;
		}
	}

	public boolean isSearched(CardEntity entity)
	{
		boolean flag = false;

		if (TextUtils.isEmpty(cardName))
			flag = true;
		else if (entity.getSCCardName().contains(cardName))
			flag = true;
		else
			return false;

		if (cardCamp.equals("不限"))
			flag = true;
		else if (entity.getCardCamp().equals(cardCamp))
			flag = true;
		else
			return false;

		if (cardRare.equals("不限"))
			flag = true;
		else if (entity.getSCCardRare().contains(cardRare))
			flag = true;
		else
			return false;

		if (cardBan.equals("不限"))
			flag = true;
		else if (entity.getSCCardBan().startsWith(cardBan))
			flag = true;
		else
			return false;

		if (cardType.equals("不限"))
			flag = true;
		else if (entity.getSCCardType().equals(cardType))
			flag = true;
		else
			return false;

		if (cardType.contains("怪兽"))
		{
			if (cardType2.equals("不限"))
				flag = true;
			else if (entity.getSCDCardType().contains(cardType2))
				flag = true;
			else
				return false;

			if (TextUtils.isEmpty(cardStarNum))
				flag = true;
			else if (U.isNum(cardStarNum))
			{
				double d = Double.parseDouble(cardStarNum);
				if (d == entity.getCardStarNum())
					flag = true;
				else
					return false;
			} else
				return false;

			if (cardAttribute.equals("不限"))
				flag = true;
			else if (entity.getSCCardAttribute().contains(cardAttribute))
				flag = true;
			else
				return false;

			if (cardRace.equals("不限"))
				flag = true;
			else if (entity.getSCCardRace().contains(cardRace))
				flag = true;
			else
				return false;

			if (TextUtils.isEmpty(cardAtk))
				flag = true;
			else if (U.isNum(cardAtk))
			{
				double d = Double.parseDouble(cardAtk);
				if (d == entity.getCardAtk())
					flag = true;
				else
					return false;
			} else
				return false;

			if (TextUtils.isEmpty(cardDef))
				flag = true;
			else if (U.isNum(cardDef))
			{
				double d = Double.parseDouble(cardDef);
				if (d == entity.getCardDef())
					flag = true;
				else
					return false;
			} else
				return false;
		}

		return flag;
	}

}


text:
"""Test the Z-Wave over MQTT config flow."""
from unittest.mock import patch

import pytest

from homeassistant import config_entries
from homeassistant.components.hassio.handler import HassioAPIError
from homeassistant.components.ozw.config_flow import TITLE
from homeassistant.components.ozw.const import DOMAIN

from tests.common import MockConfigEntry

ADDON_DISCOVERY_INFO = {
    "addon": "OpenZWave",
    "host": "host1",
    "port": 1234,
    "username": "name1",
    "password": "pass1",
}

@pytest.fixture(name="supervisor")
def mock_supervisor_fixture():
    """Mock Supervisor."""
    with patch("homeassistant.components.hassio.is_hassio", return_value=True):
        yield

@pytest.fixture(name="addon_info")
def mock_addon_info():
    """Mock Supervisor add-on info."""
    with patch("homeassistant.components.hassio.async_get_addon_info") as addon_info:
        addon_info.return_value = {}
        yield addon_info

@pytest.fixture(name="addon_running")
def mock_addon_running(addon_info):
    """Mock add-on already running."""
    addon_info.return_value["state"] = "started"
    return addon_info

@pytest.fixture(name="addon_installed")
def mock_addon_installed(addon_info):
    """Mock add-on already installed but not running."""
    addon_info.return_value["state"] = "stopped"
    addon_info.return_value["version"] = "1.0"
    return addon_info

@pytest.fixture(name="addon_options")
def mock_addon_options(addon_info):
    """Mock add-on options."""
    addon_info.return_value["options"] = {}
    return addon_info.return_value["options"]

@pytest.fixture(name="set_addon_options")
def mock_set_addon_options():
    """Mock set add-on options."""
    with patch(
        "homeassistant.components.hassio.async_set_addon_options"
    ) as set_options:
        yield set_options

@pytest.fixture(name="install_addon")
def mock_install_addon():
    """Mock install add-on."""
    with patch("homeassistant.components.hassio.async_install_addon") as install_addon:
        yield install_addon

@pytest.fixture(name="start_addon")
def mock_start_addon():
    """Mock start add-on."""
    with patch("homeassistant.components.hassio.async_start_addon") as start_addon:
        yield start_addon

async def test_user_not_supervisor_create_entry(hass, mqtt):
    """Test the user step creates an entry not on Supervisor."""

    with patch(
        "homeassistant.components.ozw.async_setup_entry",
        return_value=True,
    ) as mock_setup_entry:
        result = await hass.config_entries.flow.async_init(
            DOMAIN, context={"source": config_entries.SOURCE_USER}
        )
        await hass.async_block_till_done()

    assert result["type"] == "create_entry"
    assert result["title"] == TITLE
    assert result["data"] == {
        "usb_path": None,
        "network_key": None,
        "use_addon": False,
        "integration_created_addon": False,
    }
    assert len(mock_setup_entry.mock_calls) == 1

async def test_mqtt_not_setup(hass):
    """Test that mqtt is required."""
    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER}
    )
    assert result["type"] == "abort"
    assert result["reason"] == "mqtt_required"

async def test_one_instance_allowed(hass):
    """Test that only one instance is allowed."""
    entry = MockConfigEntry(domain=DOMAIN, data={}, title=TITLE)
    entry.add_to_hass(hass)

    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER}
    )
    assert result["type"] == "abort"
    assert result["reason"] == "single_instance_allowed"

async def test_not_addon(hass, supervisor, mqtt):
    """Test opting out of add-on on Supervisor."""

    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER}
    )

    with patch(
        "homeassistant.components.ozw.async_setup_entry",
        return_value=True,
    ) as mock_setup_entry:
        result = await hass.config_entries.flow.async_configure(
            result["flow_id"], {"use_addon": False}
        )
        await hass.async_block_till_done()

    assert result["type"] == "create_entry"
    assert result["title"] == TITLE
    assert result["data"] == {
        "usb_path": None,
        "network_key": None,
        "use_addon": False,
        "integration_created_addon": False,
    }
    assert len(mock_setup_entry.mock_calls) == 1

async def test_addon_running(hass, supervisor, addon_running, addon_options):
    """Test add-on already running on Supervisor."""
    addon_options["device"] = "/test"
    addon_options["network_key"] = "abc123"

    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER}
    )

    with patch(
        "homeassistant.components.ozw.async_setup_entry",
        return_value=True,
    ) as mock_setup_entry:
        result = await hass.config_entries.flow.async_configure(
            result["flow_id"], {"use_addon": True}
        )
        await hass.async_block_till_done()

    assert result["type"] == "create_entry"
    assert result["title"] == TITLE
    assert result["data"] == {
        "usb_path": "/test",
        "network_key": "abc123",
        "use_addon": True,
        "integration_created_addon": False,
    }
    assert len(mock_setup_entry.mock_calls) == 1

async def test_addon_info_failure(hass, supervisor, addon_info):
    """Test add-on info failure."""
    addon_info.side_effect = HassioAPIError()

    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER}
    )

    result = await hass.config_entries.flow.async_configure(
        result["flow_id"], {"use_addon": True}
    )

    assert result["type"] == "abort"
    assert result["reason"] == "addon_info_failed"

async def test_addon_installed(
    hass, supervisor, addon_installed, addon_options, set_addon_options, start_addon
):
    """Test add-on already installed but not running on Supervisor."""

    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER}
    )
    result = await hass.config_entries.flow.async_configure(
        result["flow_id"], {"use_addon": True}
    )

    with patch(
        "homeassistant.components.ozw.async_setup_entry",
        return_value=True,
    ) as mock_setup_entry:
        result = await hass.config_entries.flow.async_configure(
            result["flow_id"], {"usb_path": "/test", "network_key": "abc123"}
        )
        await hass.async_block_till_done()

    assert result["type"] == "create_entry"
    assert result["title"] == TITLE
    assert result["data"] == {
        "usb_path": "/test",
        "network_key": "abc123",
        "use_addon": True,
        "integration_created_addon": False,
    }
    assert len(mock_setup_entry.mock_calls) == 1

async def test_set_addon_config_failure(
    hass, supervisor, addon_installed, addon_options, set_addon_options
):
    """Test add-on set config failure."""
    set_addon_options.side_effect = HassioAPIError()

    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER}
    )
    result = await hass.config_entries.flow.async_configure(
        result["flow_id"], {"use_addon": True}
    )

    result = await hass.config_entries.flow.async_configure(
        result["flow_id"], {"usb_path": "/test", "network_key": "abc123"}
    )

    assert result["type"] == "abort"
    assert result["reason"] == "addon_set_config_failed"

async def test_start_addon_failure(
    hass, supervisor, addon_installed, addon_options, set_addon_options, start_addon
):
    """Test add-on start failure."""
    start_addon.side_effect = HassioAPIError()

    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER}
    )
    result = await hass.config_entries.flow.async_configure(
        result["flow_id"], {"use_addon": True}
    )

    result = await hass.config_entries.flow.async_configure(
        result["flow_id"], {"usb_path": "/test", "network_key": "abc123"}
    )

    assert result["type"] == "form"
    assert result["errors"] == {"base": "addon_start_failed"}

async def test_addon_not_installed(
    hass,
    supervisor,
    addon_installed,
    install_addon,
    addon_options,
    set_addon_options,
    start_addon,
):
    """Test add-on not installed."""
    addon_installed.return_value["version"] = None

    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER}
    )
    result = await hass.config_entries.flow.async_configure(
        result["flow_id"], {"use_addon": True}
    )

    assert result["type"] == "progress"

    # Make sure the flow continues when the progress task is done.
    await hass.async_block_till_done()

    result = await hass.config_entries.flow.async_configure(result["flow_id"])

    assert result["type"] == "form"
    assert result["step_id"] == "start_addon"

    with patch(
        "homeassistant.components.ozw.async_setup_entry",
        return_value=True,
    ) as mock_setup_entry:
        result = await hass.config_entries.flow.async_configure(
            result["flow_id"], {"usb_path": "/test", "network_key": "abc123"}
        )
        await hass.async_block_till_done()

    assert result["type"] == "create_entry"
    assert result["title"] == TITLE
    assert result["data"] == {
        "usb_path": "/test",
        "network_key": "abc123",
        "use_addon": True,
        "integration_created_addon": True,
    }
    assert len(mock_setup_entry.mock_calls) == 1

async def test_install_addon_failure(hass, supervisor, addon_installed, install_addon):
    """Test add-on install failure."""
    addon_installed.return_value["version"] = None
    install_addon.side_effect = HassioAPIError()

    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER}
    )
    result = await hass.config_entries.flow.async_configure(
        result["flow_id"], {"use_addon": True}
    )

    assert result["type"] == "progress"

    # Make sure the flow continues when the progress task is done.
    await hass.async_block_till_done()

    result = await hass.config_entries.flow.async_configure(result["flow_id"])

    assert result["type"] == "abort"
    assert result["reason"] == "addon_install_failed"

async def test_supervisor_discovery(hass, supervisor, addon_running, addon_options):
    """Test flow started from Supervisor discovery."""

    addon_options["device"] = "/test"
    addon_options["network_key"] = "abc123"

    result = await hass.config_entries.flow.async_init(
        DOMAIN,
        context={"source": config_entries.SOURCE_HASSIO},
        data=ADDON_DISCOVERY_INFO,
    )

    with patch(
        "homeassistant.components.ozw.async_setup_entry",
        return_value=True,
    ) as mock_setup_entry:
        result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
        await hass.async_block_till_done()

    assert result["type"] == "create_entry"
    assert result["title"] == TITLE
    assert result["data"] == {
        "usb_path": "/test",
        "network_key": "abc123",
        "use_addon": True,
        "integration_created_addon": False,
    }
    assert len(mock_setup_entry.mock_calls) == 1

async def test_clean_discovery_on_user_create(
    hass, supervisor, addon_running, addon_options
):
    """Test discovery flow is cleaned up when a user flow is finished."""

    addon_options["device"] = "/test"
    addon_options["network_key"] = "abc123"

    result = await hass.config_entries.flow.async_init(
        DOMAIN,
        context={"source": config_entries.SOURCE_HASSIO},
        data=ADDON_DISCOVERY_INFO,
    )

    assert result["type"] == "form"

    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER}
    )

    with patch(
        "homeassistant.components.ozw.async_setup_entry",
        return_value=True,
    ) as mock_setup_entry:
        result = await hass.config_entries.flow.async_configure(
            result["flow_id"], {"use_addon": False}
        )
        await hass.async_block_till_done()

    assert len(hass.config_entries.flow.async_progress()) == 0
    assert result["type"] == "create_entry"
    assert result["title"] == TITLE
    assert result["data"] == {
        "usb_path": None,
        "network_key": None,
        "use_addon": False,
        "integration_created_addon": False,
    }
    assert len(mock_setup_entry.mock_calls) == 1

async def test_abort_discovery_with_user_flow(
    hass, supervisor, addon_running, addon_options
):
    """Test discovery flow is aborted if a user flow is in progress."""

    await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER}
    )

    result = await hass.config_entries.flow.async_init(
        DOMAIN,
        context={"source": config_entries.SOURCE_HASSIO},
        data=ADDON_DISCOVERY_INFO,
    )

    assert result["type"] == "abort"
    assert result["reason"] == "already_in_progress"
    assert len(hass.config_entries.flow.async_progress()) == 1

async def test_abort_discovery_with_existing_entry(
    hass, supervisor, addon_running, addon_options
):
    """Test discovery flow is aborted if an entry already exists."""

    entry = MockConfigEntry(domain=DOMAIN, data={}, title=TITLE, unique_id=DOMAIN)
    entry.add_to_hass(hass)

    result = await hass.config_entries.flow.async_init(
        DOMAIN,
        context={"source": config_entries.SOURCE_HASSIO},
        data=ADDON_DISCOVERY_INFO,
    )

    assert result["type"] == "abort"
    assert result["reason"] == "already_configured"

async def test_discovery_addon_not_running(
    hass, supervisor, addon_installed, addon_options, set_addon_options, start_addon
):
    """Test discovery with add-on already installed but not running."""
    addon_options["device"] = None

    result = await hass.config_entries.flow.async_init(
        DOMAIN,
        context={"source": config_entries.SOURCE_HASSIO},
        data=ADDON_DISCOVERY_INFO,
    )

    assert result["step_id"] == "hassio_confirm"
    assert result["type"] == "form"

    result = await hass.config_entries.flow.async_configure(result["flow_id"], {})

    assert result["step_id"] == "start_addon"
    assert result["type"] == "form"

async def test_discovery_addon_not_installed(
    hass, supervisor, addon_installed, install_addon, addon_options
):
    """Test discovery with add-on not installed."""
    addon_installed.return_value["version"] = None

    result = await hass.config_entries.flow.async_init(
        DOMAIN,
        context={"source": config_entries.SOURCE_HASSIO},
        data=ADDON_DISCOVERY_INFO,
    )

    assert result["step_id"] == "hassio_confirm"
    assert result["type"] == "form"

    result = await hass.config_entries.flow.async_configure(result["flow_id"], {})

    assert result["step_id"] == "install_addon"
    assert result["type"] == "progress"

    await hass.async_block_till_done()

    result = await hass.config_entries.flow.async_configure(result["flow_id"])

    assert result["type"] == "form"
    assert result["step_id"] == "start_addon"


text:
package app.model;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

/**
 * The persistent class for the aluno database table.
 *
 */
@Entity
@Table(name = "aluno", schema = "futurodb")
@NamedQueries({ @NamedQuery(name = "Aluno.findAll", query = "SELECT a FROM Aluno a"),
		@NamedQuery(name = "Aluno.findLastRegistrationNumber", query = "SELECT MAX(a.matricula) as last FROM Aluno a"),
		@NamedQuery(name = "Aluno.findByRegistrationNumber", query = "SELECT a FROM Aluno a WHERE a.matricula LIKE :wantedNumber"),
		@NamedQuery(name = "Aluno.findByStatus", query = "SELECT a FROM Aluno a WHERE a.status LIKE :wantedStatus"),
		@NamedQuery(name = "Aluno.findByTurmaId", query = "SELECT a FROM Aluno a, Turma t WHERE t.id = :turmaId AND a MEMBER OF t.alunos AND a.status LIKE 'ATIVO'") })
public class Aluno implements Serializable {
	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(insertable = false)
	private Long id;

	@Temporal(TemporalType.DATE)
	private Date dataEgresso;

	@Temporal(TemporalType.DATE)
	private Date dataIngresso;

	private String matricula;

	private String status;

	private int tipoCotaIngresso;

	@OneToOne(cascade = CascadeType.ALL)
	private Pessoa pessoa;

	// bi-directional many-to-one association to Turma
	@ManyToOne
	private Turma turma;

	public Aluno() {
	}

	public Long getId() {
		return this.id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Date getDataEgresso() {
		return this.dataEgresso;
	}

	public void setDataEgresso(Date dataEgresso) {
		this.dataEgresso = dataEgresso;
	}

	public Date getDataIngresso() {
		return this.dataIngresso;
	}

	public void setDataIngresso(Date dataIngresso) {
		this.dataIngresso = dataIngresso;
	}

	public String getMatricula() {
		return this.matricula;
	}

	public void setMatricula(String matricula) {
		this.matricula = matricula;
	}

	public String getStatus() {
		return this.status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public int getTipoCotaIngresso() {
		return this.tipoCotaIngresso;
	}

	public void setTipoCotaIngresso(int tipoCotaIngresso) {
		this.tipoCotaIngresso = tipoCotaIngresso;
	}

	public Pessoa getPessoa() {
		return this.pessoa;
	}

	public void setPessoa(Pessoa pessoa) {
		this.pessoa = pessoa;
	}

	public Turma getTurma() {
		return this.turma;
	}

	public void setTurma(Turma turma) {
		this.turma = turma;
	}

	@Override
	public Aluno clone() {
		Aluno alunoClone = new Aluno();
		alunoClone.setId(id);
		alunoClone.setDataEgresso(dataEgresso);
		alunoClone.setDataIngresso(dataIngresso);
		alunoClone.setMatricula(matricula);
		alunoClone.setTipoCotaIngresso(tipoCotaIngresso);
		if (turma != null) {
			alunoClone.setTurma(turma);
		}
		alunoClone.setPessoa(pessoa);
		alunoClone.setStatus(status);

		return alunoClone;

	}

	public void restaurar(Aluno aluno) {
		this.id = aluno.getId();
		this.dataEgresso = aluno.getDataEgresso();
		this.dataIngresso = aluno.getDataIngresso();
		this.matricula = aluno.getMatricula();
		this.tipoCotaIngresso = aluno.getTipoCotaIngresso();
		this.turma = aluno.getTurma();
		this.pessoa = aluno.getPessoa();
		this.status = aluno.getStatus();
	}

	@Override
	public String toString() {
		return "Aluno[id=" + id + ", dataIgresso=" + dataIngresso + ", dataEgresso=" + dataEgresso + ", matricula="
				+ matricula + ", tipoCotaIngresso=" + tipoCotaIngresso + ", status=" + status + "]";
	}

}


text:
package com.alipay.api.response;

import com.alipay.api.internal.mapping.ApiField;

import com.alipay.api.AlipayResponse;

/**
 * ALIPAY API: alipay.open.public.group.crowd.query response.
 *
 * @author auto create
 * @since 1.0, 2017-11-10 15:32:41
 */
public class AlipayOpenPublicGroupCrowdQueryResponse extends AlipayResponse {

	private static final long serialVersionUID = 1293651218958453531L;

	/**
	 * 分组圈出的人群数量
	 */
	@ApiField("count")
	private String count;

	public void setCount(String count) {
		this.count = count;
	}
	public String getCount( ) {
		return this.count;
	}

}


text:
id: 587d7dbe367417b2b2512bb9
title: Use @for to Create a Sass Loop
challengeType: 0
forumTopicId: 301462
---

## Description

The @for directive adds styles in a loop, very similar to a for loop in JavaScript.
@for is used in two ways: "start through end" or "start to end". The main difference is that the "start to end" excludes the end number as part of the count, and "start through end" includes the end number as part of the count.
Here's a start through end example:

```scss
@for $i from 1 through 12 {
  .col-#{$i} { width: 100%/12 * $i; }
}
```

The #{$i} part is the syntax to combine a variable (i) with text to make a string. When the Sass file is converted to CSS, it looks like this:

```scss
.col-1 {
  width: 8.33333%;
}

.col-2 {
  width: 16.66667%;
}

...

.col-12 {
  width: 100%;
}
```

This is a powerful way to create a grid layout. Now you have twelve options for column widths available as CSS classes.

## Instructions

Write a @for directive that takes a variable $j that goes from 1 to 6.
It should create 5 classes called .text-1 to .text-5 where each has a font-size set to 10px multiplied by the index.

## Tests

```yml
tests:
  - text: Your code should use the <code>@for</code> directive.
    testString: assert(code.match(/@for /g));
  - text: Your <code>.text-1</code> class should have a <code>font-size</code> of 10px.
    testString: assert($('.text-1').css('font-size') == '10px');
  - text: Your <code>.text-2</code> class should have a <code>font-size</code> of 20px.
    testString: assert($('.text-2').css('font-size') == '20px');
  - text: Your <code>.text-3</code> class should have a <code>font-size</code> of 30px.
    testString: assert($('.text-3').css('font-size') == '30px');
  - text: Your <code>.text-4</code> class should have a <code>font-size</code> of 40px.
    testString: assert($('.text-4').css('font-size') == '40px');
  - text: Your <code>.text-5</code> class should have a <code>font-size</code> of 50px.
    testString: assert($('.text-5').css('font-size') == '50px');

```

## Challenge Seed

```html
<style type='text/sass'>

</style>

<p class="text-1">Hello</p>
<p class="text-2">Hello</p>
<p class="text-3">Hello</p>
<p class="text-4">Hello</p>
<p class="text-5">Hello</p>
```

## Solution

```html
<style type='text/sass'>

@for $i from 1 through 5 {
  .text-#{$i} { font-size: 10px * $i; }
}

</style>

<p class="text-1">Hello</p>
<p class="text-2">Hello</p>
<p class="text-3">Hello</p>
<p class="text-4">Hello</p>
<p class="text-5">Hello</p>
```

```html
<style type='text/sass'>

@for $i from 1 to 6 {
  .text-#{$i} { font-size: 10px * $i; }
}

</style>

<p class="text-1">Hello</p>
<p class="text-2">Hello</p>
<p class="text-3">Hello</p>
<p class="text-4">Hello</p>
<p class="text-5">Hello</p>
```


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="fill_parent"
	android:layout_height="wrap_content">
	<TextView android:text="Irregular verbs (43)" android:id="@+id/stack_item_name"
		android:layout_width="wrap_content" android:layout_height="wrap_content"
		android:textSize="25sp" />
	<TextView android:text="Set of most common spanish irregular verbs"
		android:id="@+id/stack_item_description" android:layout_width="fill_parent"
		android:layout_height="wrap_content" android:maxLines="2"/>

</LinearLayout>


text:
using Accelereval
using Base.Test

import Accelereval: parse_vardecl, parse_funhead, parse_rhs

# parse variables

@test_throws parse_vardecl(:a)   # no type annotation

@test parse_vardecl(:(a::Float64)) == variable(:a, Float64, 0)
@test_throws parse_vardecl(:(a::FloatingPoint))   # non-recognized type

@test parse_vardecl(:(x::Vector{Int})) == variable(:x, Int, 1)
@test parse_vardecl(:(x::Matrix{Int})) == variable(:x, Int, 2)
@test_throws parse_vardecl(:(a::Vector))   # no annotation of element type
@test_throws parse_vardecl(:(a::Matrix{Number}))   # non-recognized element type

# parse function header

(fname, vars) = parse_funhead(:(myf(x::Float64, y::Matrix{Int})))
@test isa(fname, Symbol) && fname == :myf
@test length(vars) == 2
@test vars[1] == variable(:x, Float64, 0)
@test vars[2] == variable(:y, Int, 2)

### parse rhs

_x = variable(:x, Float64, 1)
_y = variable(:y, Float64, 1)
_a = variable(:a, Float64, 0)
_b = variable(:b, Float64, 0)

vmap = (Symbol=>Variable)[:x=>_x, :y=>_y, :a=>_a, :b=>_b]

# variables

@test parse_rhs(vmap, :x) == variable(:x, Float64, 1)
@test_throws parse_rhs(vmap, :abc)

# function calls

@test parse_rhs(vmap, :(abs(x))) == mapexpr(SAbs, _x)
@test parse_rhs(vmap, :(x - y)) == mapexpr(SSubtract, _x, _y)


text:
<!doctype html>

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

	<link rel="stylesheet" href="css/reset.css">
	<link rel="stylesheet" href="css/style.css">

	<title>1. Competitive Analysis | Progress</title>

			< Back to Homepage

			< Timeline

Phase 1. Competitive Analysis | Progress

Asset Manager Launch

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iusto, optio, dolorum provident rerum aut hic quasi placeat iure tempora laudantium ipsa ad debitis unde? Iste voluptatibus minus veritatis qui ut.

				Read more
				July 18

Competitive Analysis Complete

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iusto, optio, dolorum provident rerum aut hic quasi placeat iure tempora laudantium ipsa ad debitis unde?

				Read more
				July 3

Title of section 3

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Excepturi, obcaecati, quisquam id molestias eaque asperiores voluptatibus cupiditate error assumenda delectus odit similique earum voluptatem doloremque dolorem ipsam quae rerum quis. Odit, itaque, deserunt corporis vero ipsum nisi eius odio natus ullam provident pariatur temporibus quia eos repellat consequuntur perferendis enim amet quae quasi repudiandae sed quod veniam dolore possimus rem voluptatum eveniet eligendi quis fugiat aliquam sunt similique aut adipisci.

				Read more
				Jun 24

Title of section 4

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iusto, optio, dolorum provident rerum aut hic quasi placeat iure tempora laudantium ipsa ad debitis unde? Iste voluptatibus minus veritatis qui ut.

				Read more
				Jun 14

Title of section 5

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iusto, optio, dolorum provident rerum.

				Read more
				May 28

Account Won!

This is when we started the project.

				May 14


text:
<?php

require_once('Catalog.php');

// A shopping cart item.
class ShoppingCartItem {

    private $itemID;
    private $itemAmount;

    public function __construct($id, $amount) {

        $this->itemID = $id;
        $this->itemAmount = $amount;

    }

	public function getId() {
		return $this->itemID;
    }
	public function getAmount() {
		return $this->itemAmount;
    }
    public function setAmount($amount) {
        $this->itemAmount = $amount;
    }

    public function getPrice() {
        $catalog = new Catalog();
        $prod = $catalog->getProductByID($this->itemID);
        return $prod->getPrice() * $this->itemAmount;
    }

    public function getName() {
        $catalog = new Catalog();
        $prod = $catalog->getProductByID($this->itemID);
        return $prod->getName();
    }

}


text:
package com.techfit.mdofbehavior.slidingdel;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.techfit.mdofbehavior.R;

public class ActivitySlidingDelete extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sliding_delete);
    }
}


text:
'use strict';

var shippo = require('./testUtils').getSpyableShippo();
var expect = require('chai').expect;

var BASE_PATH = shippo.get('basePath') + 'customs/'

describe('Customs Declaration Resource', function() {

  describe('retrieve', function() {

    it('Sends the correct request', function() {

      shippo.customsdeclaration.retrieve('CustomsItemIdFoo123');
      expect(shippo.LAST_REQUEST).to.deep.equal({
        method: 'GET',
        url: BASE_PATH + 'declarations/CustomsItemIdFoo123',
        data: {}
      });

    });

  });

  describe('list', function() {

    it('Sends the correct request', function() {

      shippo.customsdeclaration.list();
      expect(shippo.LAST_REQUEST).to.deep.equal({
        method: 'GET',
        url: BASE_PATH + 'declarations/',
        data: {}
      });

    });

  });

  describe('create', function() {

    it('Sends the correct request', function() {

      var payload = {
        "exporter_reference": "Exporter Reference",
        "importer_reference": "Importer Reference",
        "contents_type": "MERCHANDISE",
        "contents_explanation": "T-Shirt purchase",
        "invoice": "#123123",
        "license": "License",
        "certificate": "Certificate",
        "notes": "Notes",
        "eel_pfc": "NOEEI_30_37_a",
        "aes_itn": "X20180426506889",
        "non_delivery_option": "ABANDON",
        "certify": true,
        "certify_signer": "Laura Behrens Wu",
        "incoterm": "DDP",
        "items": [
          "0c1a723687164307bb2175972fbcd9ef"
        ],
        "invoiced_charges": {
          "currency": "USD",
          "total_shipping": "1.23",
          "total_taxes": "4.56",
          "total_duties": "78.90",
          "other_fees": "9.87"
        },
        "metadata": "Order ID #123123"
      };

      shippo.customsdeclaration.create(payload);
      expect(shippo.LAST_REQUEST).to.deep.equal({
        method: 'POST',
        url: BASE_PATH + 'declarations/',
        data: payload
      });

    });

  });

});


text:
using System;
using System.IO;
using System.Text;

/**************************************************
 *
 * BijouUtils
 *
 *************************************************/
public class BijouUtils  {

	public static string BuildRootPath(int level) {
		string result = string.Empty;
		if (Bijou.Index) {
			result = FileUtils.BuildRelativePath(level);
		} else {
			result = Bijou.WebRoot;
		}
		return result;
	}

	public static void BuildLink(StringBuilder stream, string currentPath, DirectoryInfo di) {
		string stripped = StripPrefix(di.Name, '.');
		string displayName = ParseDisplayName(stripped);
		string strippedPath = StripPrefix(currentPath);

		if (Bijou.Index) {
			string root = FileUtils.BuildRelativePath(Bijou.Level);
			stream.AppendFormat("{2}", root, strippedPath, displayName);
		} else if (Bijou.WebRoot == "") {
			stream.AppendFormat("{1}", strippedPath, displayName);
		} else {
			stream.AppendFormat("{2}", Bijou.WebRoot, strippedPath, displayName);
		}
	}

	public static string StripPrefix(string contentPath) {
		StringBuilder result = new StringBuilder("/");
		contentPath = contentPath.Replace("./content", "");
		string[] tokens = contentPath.Split('/');
		foreach (string item in tokens) {
			if (!string.IsNullOrEmpty(item)) {
				result.AppendFormat("{0}/", StripPrefix(item, '.'));
			}
		}
		// result.Append("/");

 		if (Bijou.Debug) Console.WriteLine("StripPath " + result);

		return result.ToString();
	}

	public static string StripPrefix(string text, char separator) {
		string result = text;
		if (!string.IsNullOrEmpty(text)) {
			string[] tokens = text.Split(separator);
			if (tokens.Length >= 2) {
				result = tokens[1];
			}
		}
		return result;
	}

	public static string ParseDisplayName(string text) {
		string result = text;

		if (!string.IsNullOrEmpty(text)) {
			StringBuilder sb = new StringBuilder();
			foreach(char c in text) {
				if (char.IsUpper(c) && (sb.Length > 0)) sb.Append(" ");
				sb.Append(c);
			}
			result = sb.ToString();
		}
		return result;
	}

	public static string ParsePageTitle(string filename) {
		string result = filename;
		if (!string.IsNullOrEmpty(filename)) {
			string[] tokens = filename.Split('/');
			if (tokens.Length >= 2) {
				result = tokens[tokens.Length-2];
			}
		}
		if (result == "site") result = "";
		return ParseDisplayName(result);
	}

	public static bool IsNavigation(string folder) {
		return folder.Contains(".");
	}

	public static bool IsInvisible(string folder) {
		return folder.StartsWith("0.");
	}

}