text:
package org.apache.jena.arq.querybuilder;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

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

import org.apache.jena.graph.Graph;
import org.apache.jena.graph.Node;
import org.apache.jena.graph.NodeFactory;
import org.apache.jena.graph.Triple;
import org.apache.jena.graph.impl.CollectionGraph;
import org.apache.jena.rdf.model.Literal;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.sparql.core.Quad;
import org.apache.jena.sparql.core.Var;
import org.apache.jena.sparql.modify.request.UpdateDataDelete;
import org.apache.jena.sparql.modify.request.UpdateDataInsert;
import org.apache.jena.sparql.modify.request.UpdateModify;
import org.apache.jena.sparql.path.P_Link;
import org.apache.jena.sparql.path.Path;
import org.apache.jena.sparql.syntax.Element;
import org.apache.jena.sparql.syntax.ElementGroup;
import org.apache.jena.sparql.syntax.ElementPathBlock;
import org.apache.jena.update.Update;
import org.apache.jena.update.UpdateAction;
import org.apache.jena.vocabulary.DC_11;
import org.junit.Test;

public class UpdateBuilderTest {

    private Node g = NodeFactory.createURI("http://example.com/graph");
    private Node s = NodeFactory.createURI("http://example.com/subject");
    private Node p = NodeFactory.createURI("http://example.com/predicate");
    private Node o = NodeFactory.createURI("http://example.com/object");

    @Test
    public void testInsert_SPO() {
        UpdateBuilder builder = new UpdateBuilder();
        builder.addInsert(s, p, o);
        Update update = builder.build();
        assertTrue(update instanceof UpdateDataInsert);
        UpdateDataInsert udi = (UpdateDataInsert) update;
        List<Quad> quads = udi.getQuads();
        assertEquals(1, quads.size());
        Quad q = quads.get(0);
        assertEquals(Quad.defaultGraphNodeGenerated, q.getGraph());
        assertEquals(s, q.getSubject());
        assertEquals(p, q.getPredicate());
        assertEquals(o, q.getObject());
    }

    @Test
    public void testInsert_Triple() {
        Triple t = Triple.create(s, p, o);
        UpdateBuilder builder = new UpdateBuilder();
        builder.addInsert(t);
        Update update = builder.build();
        assertTrue(update instanceof UpdateDataInsert);
        UpdateDataInsert udi = (UpdateDataInsert) update;
        List<Quad> quads = udi.getQuads();
        assertEquals(1, quads.size());
        Quad q = quads.get(0);
        assertEquals(Quad.defaultGraphNodeGenerated, q.getGraph());
        assertEquals(s, q.getSubject());
        assertEquals(p, q.getPredicate());
        assertEquals(o, q.getObject());
    }

    @Test
    public void testInsert_NodeTriple() {
        Triple t = Triple.create(s, p, o);
        UpdateBuilder builder = new UpdateBuilder();
        builder.addInsert(g, t);
        Update update = builder.build();
        assertTrue(update instanceof UpdateDataInsert);
        UpdateDataInsert udi = (UpdateDataInsert) update;
        List<Quad> quads = udi.getQuads();
        assertEquals(1, quads.size());
        Quad q = quads.get(0);
        assertEquals(g, q.getGraph());
        assertEquals(s, q.getSubject());
        assertEquals(p, q.getPredicate());
        assertEquals(o, q.getObject());
    }

    @Test
    public void testInsert_GSPO() {

        UpdateBuilder builder = new UpdateBuilder();
        builder.addInsert(g, s, p, o);
        Update update = builder.build();
        assertTrue(update instanceof UpdateDataInsert);
        UpdateDataInsert udi = (UpdateDataInsert) update;
        List<Quad> quads = udi.getQuads();
        assertEquals(1, quads.size());
        Quad q = quads.get(0);
        assertEquals(g, q.getGraph());
        assertEquals(s, q.getSubject());
        assertEquals(p, q.getPredicate());
        assertEquals(o, q.getObject());
    }

    @Test
    public void testInsert_Quad() {
        UpdateBuilder builder = new UpdateBuilder();
        builder.addInsert(new Quad(g, s, p, o));
        Update update = builder.build();
        assertTrue(update instanceof UpdateDataInsert);
        UpdateDataInsert udi = (UpdateDataInsert) update;
        List<Quad> quads = udi.getQuads();
        assertEquals(1, quads.size());
        Quad q = quads.get(0);
        assertEquals(g, q.getGraph());
        assertEquals(s, q.getSubject());
        assertEquals(p, q.getPredicate());
        assertEquals(o, q.getObject());
    }

    @Test
    public void testInsert_QuadCollection() {
        UpdateBuilder builder = new UpdateBuilder();
        Collection<Quad> quads = new ArrayList<Quad>();

        quads.add(new Quad(g, s, p, o));

        Node g2 = NodeFactory.createURI("http://example.com/graph2");
        Node s2 = NodeFactory.createURI("http://example.com/subject2");
        Node p2 = NodeFactory.createURI("http://example.com/predicate2");
        Node o2 = NodeFactory.createURI("http://example.com/object2");

        quads.add(new Quad(g2, s2, p2, o2));

        builder.addInsertQuads(quads);
        Update update = builder.build();
        assertTrue(update instanceof UpdateDataInsert);
        UpdateDataInsert udi = (UpdateDataInsert) update;
        List<Quad> quads2 = udi.getQuads();
        assertEquals(2, quads2.size());
        Quad q = quads2.get(0);
        assertEquals(g, q.getGraph());
        assertEquals(s, q.getSubject());
        assertEquals(p, q.getPredicate());
        assertEquals(o, q.getObject());

        q = quads2.get(1);
        assertEquals(g2, q.getGraph());
        assertEquals(s2, q.getSubject());
        assertEquals(p2, q.getPredicate());
        assertEquals(o2, q.getObject());
    }

    @Test
    public void testInsertValueReplacement() {
        Var v = Var.alloc("v");
        UpdateBuilder builder = new UpdateBuilder();
        builder.addInsert(v, p, o);
        builder.setVar(v, s);
        Update update = builder.build();
        assertTrue(update instanceof UpdateDataInsert);
        UpdateDataInsert udi = (UpdateDataInsert) update;
        List<Quad> quads = udi.getQuads();
        assertEquals(1, quads.size());
        Quad q = quads.get(0);
        assertEquals(Quad.defaultGraphNodeGenerated, q.getGraph());
        assertEquals(s, q.getSubject());
        assertEquals(p, q.getPredicate());
        assertEquals(o, q.getObject());
    }

    @Test
    public void testDelete_SPO() {
        UpdateBuilder builder = new UpdateBuilder();
        builder.addDelete(s, p, o);
        Update update = builder.build();
        assertTrue(update instanceof UpdateDataDelete);
        UpdateDataDelete udd = (UpdateDataDelete) update;
        List<Quad> quads = udd.getQuads();
        assertEquals(1, quads.size());
        Quad q = quads.get(0);
        assertEquals(Quad.defaultGraphNodeGenerated, q.getGraph());
        assertEquals(s, q.getSubject());
        assertEquals(p, q.getPredicate());
        assertEquals(o, q.getObject());
    }

    @Test
    public void testDelete_Triple() {
        Triple t = Triple.create(s, p, o);
        UpdateBuilder builder = new UpdateBuilder();
        builder.addDelete(t);
        Update update = builder.build();
        assertTrue(update instanceof UpdateDataDelete);
        UpdateDataDelete udd = (UpdateDataDelete) update;
        List<Quad> quads = udd.getQuads();
        assertEquals(1, quads.size());
        Quad q = quads.get(0);
        assertEquals(Quad.defaultGraphNodeGenerated, q.getGraph());
        assertEquals(s, q.getSubject());
        assertEquals(p, q.getPredicate());
        assertEquals(o, q.getObject());
    }

    @Test
    public void testDelete_NodeTriple() {
        Triple t = Triple.create(s, p, o);
        UpdateBuilder builder = new UpdateBuilder();
        builder.addDelete(g, t);
        Update update = builder.build();
        assertTrue(update instanceof UpdateDataDelete);
        UpdateDataDelete udd = (UpdateDataDelete) update;
        List<Quad> quads = udd.getQuads();
        assertEquals(1, quads.size());
        Quad q = quads.get(0);
        assertEquals(g, q.getGraph());
        assertEquals(s, q.getSubject());
        assertEquals(p, q.getPredicate());
        assertEquals(o, q.getObject());
    }

    @Test
    public void testDelete_GSPO() {

        UpdateBuilder builder = new UpdateBuilder();
        builder.addDelete(g, s, p, o);
        Update update = builder.build();
        assertTrue(update instanceof UpdateDataDelete);
        UpdateDataDelete udd = (UpdateDataDelete) update;
        List<Quad> quads = udd.getQuads();
        assertEquals(1, quads.size());
        Quad q = quads.get(0);
        assertEquals(g, q.getGraph());
        assertEquals(s, q.getSubject());
        assertEquals(p, q.getPredicate());
        assertEquals(o, q.getObject());
    }

    @Test
    public void testDelete_Quad() {

        UpdateBuilder builder = new UpdateBuilder();
        builder.addDelete(new Quad(g, s, p, o));
        Update update = builder.build();
        assertTrue(update instanceof UpdateDataDelete);
        UpdateDataDelete udd = (UpdateDataDelete) update;
        List<Quad> quads = udd.getQuads();
        assertEquals(1, quads.size());
        Quad q = quads.get(0);
        assertEquals(g, q.getGraph());
        assertEquals(s, q.getSubject());
        assertEquals(p, q.getPredicate());
        assertEquals(o, q.getObject());
    }

    @Test
    public void testDelete_QuadCollection() {
        UpdateBuilder builder = new UpdateBuilder();
        Collection<Quad> quads = new ArrayList<Quad>();

        quads.add(new Quad(g, s, p, o));

        Node g2 = NodeFactory.createURI("http://example.com/graph2");
        Node s2 = NodeFactory.createURI("http://example.com/subject2");
        Node p2 = NodeFactory.createURI("http://example.com/predicate2");
        Node o2 = NodeFactory.createURI("http://example.com/object2");

        quads.add(new Quad(g2, s2, p2, o2));

        builder.addDeleteQuads(quads);
        Update update = builder.build();
        assertTrue(update instanceof UpdateDataDelete);
        UpdateDataDelete udd = (UpdateDataDelete) update;
        List<Quad> quads2 = udd.getQuads();
        assertEquals(2, quads2.size());
        Quad q = quads2.get(0);
        assertEquals(g, q.getGraph());
        assertEquals(s, q.getSubject());
        assertEquals(p, q.getPredicate());
        assertEquals(o, q.getObject());

        q = quads2.get(1);
        assertEquals(g2, q.getGraph());
        assertEquals(s2, q.getSubject());
        assertEquals(p2, q.getPredicate());
        assertEquals(o2, q.getObject());
    }

    @Test
    public void testDeleteValueReplacement() {
        Var v = Var.alloc("v");
        UpdateBuilder builder = new UpdateBuilder();
        builder.addDelete(v, p, o);
        builder.setVar(v, s);
        Update update = builder.build();
        assertTrue(update instanceof UpdateDataDelete);
        UpdateDataDelete udd = (UpdateDataDelete) update;
        List<Quad> quads = udd.getQuads();
        assertEquals(1, quads.size());
        Quad q = quads.get(0);
        assertEquals(Quad.defaultGraphNodeGenerated, q.getGraph());
        assertEquals(s, q.getSubject());
        assertEquals(p, q.getPredicate());
        assertEquals(o, q.getObject());
    }

    @Test
    public void testInsertAndDelete() {
        UpdateBuilder builder = new UpdateBuilder();
        builder.addInsert(new Quad(g, s, p, o));
        builder.addDelete(Triple.create(s, p, o));
        builder.addWhere(null, p, "foo");
        Update update = builder.build();
        assertTrue(update instanceof UpdateModify);
        UpdateModify um = (UpdateModify) update;
        List<Quad> quads = um.getInsertQuads();
        assertEquals(1, quads.size());
        Quad q = quads.get(0);
        assertEquals(g, q.getGraph());
        assertEquals(s, q.getSubject());
        assertEquals(p, q.getPredicate());
        assertEquals(o, q.getObject());

        quads = um.getDeleteQuads();
        assertEquals(1, quads.size());
        q = quads.get(0);
        assertEquals(Quad.defaultGraphNodeGenerated, q.getGraph());
        assertEquals(s, q.getSubject());
        assertEquals(p, q.getPredicate());
        assertEquals(o, q.getObject());

        Element e = um.getWherePattern();
        assertTrue(e instanceof ElementGroup);
        ElementGroup eg = (ElementGroup) e;
        assertEquals(1, eg.getElements().size());
        ElementPathBlock epb = (ElementPathBlock) eg.getElements().get(0);
        Triple t = epb.getPattern().get(0).asTriple();
        assertEquals(Node.ANY, t.getSubject());
        assertEquals(p, t.getPredicate());
        assertEquals(builder.makeNode("foo"), t.getObject());
    }

    @Test
    public void testInsertAndDeleteWithVarReplacement() {
        UpdateBuilder builder = new UpdateBuilder();
        Var v = Var.alloc("v");

        builder.addInsert(new Quad(g, s, v, o));
        builder.addDelete(Triple.create(s, v, o));
        builder.addWhere(null, v, "foo");
        builder.setVar(v, p);
        Update update = builder.build();
        assertTrue(update instanceof UpdateModify);
        UpdateModify um = (UpdateModify) update;
        List<Quad> quads = um.getInsertQuads();
        assertEquals(1, quads.size());
        Quad q = quads.get(0);
        assertEquals(g, q.getGraph());
        assertEquals(s, q.getSubject());
        assertEquals(p, q.getPredicate());
        assertEquals(o, q.getObject());

        quads = um.getDeleteQuads();
        assertEquals(1, quads.size());
        q = quads.get(0);
        assertEquals(Quad.defaultGraphNodeGenerated, q.getGraph());
        assertEquals(s, q.getSubject());
        assertEquals(p, q.getPredicate());
        assertEquals(o, q.getObject());

        Element e = um.getWherePattern();
        assertTrue(e instanceof ElementGroup);
        ElementGroup eg = (ElementGroup) e;
        assertEquals(1, eg.getElements().size());
        ElementPathBlock epb = (ElementPathBlock) eg.getElements().get(0);
        Triple t = epb.getPattern().get(0).asTriple();
        assertEquals(Node.ANY, t.getSubject());
        assertEquals(p, t.getPredicate());
        assertEquals(builder.makeNode("foo"), t.getObject());
    }

    @Test
    public void testInsertAndDeleteWithVariableNodeReplacement() {
        UpdateBuilder builder = new UpdateBuilder();
        Node v = NodeFactory.createVariable("v");

        builder.addInsert(new Quad(g, s, v, o));
        builder.addDelete(Triple.create(s, v, o));
        builder.addWhere(null, v, "foo");
        builder.setVar(v, p);
        Update update = builder.build();
        assertTrue(update instanceof UpdateModify);
        UpdateModify um = (UpdateModify) update;
        List<Quad> quads = um.getInsertQuads();
        assertEquals(1, quads.size());
        Quad q = quads.get(0);
        assertEquals(g, q.getGraph());
        assertEquals(s, q.getSubject());
        assertEquals(p, q.getPredicate());
        assertEquals(o, q.getObject());

        quads = um.getDeleteQuads();
        assertEquals(1, quads.size());
        q = quads.get(0);
        assertEquals(Quad.defaultGraphNodeGenerated, q.getGraph());
        assertEquals(s, q.getSubject());
        assertEquals(p, q.getPredicate());
        assertEquals(o, q.getObject());

        Element e = um.getWherePattern();
        assertTrue(e instanceof ElementGroup);
        ElementGroup eg = (ElementGroup) e;
        assertEquals(1, eg.getElements().size());
        ElementPathBlock epb = (ElementPathBlock) eg.getElements().get(0);
        Triple t = epb.getPattern().get(0).asTriple();
        assertEquals(Node.ANY, t.getSubject());
        assertEquals(p, t.getPredicate());
        assertEquals(builder.makeNode("foo"), t.getObject());
    }

    @Test
    public void testInsertAndDeleteWithVariableNode() {
        UpdateBuilder builder = new UpdateBuilder();
        Node v = NodeFactory.createVariable("v");

        builder.addInsert(new Quad(g, s, v, o));
        builder.addDelete(Triple.create(s, v, o));
        builder.addWhere(null, v, "foo");

        Update update = builder.build();
        assertTrue(update instanceof UpdateModify);
        UpdateModify um = (UpdateModify) update;
        List<Quad> quads = um.getInsertQuads();
        assertEquals(1, quads.size());
        Quad q = quads.get(0);
        assertEquals(g, q.getGraph());
        assertEquals(s, q.getSubject());
        assertEquals(v, q.getPredicate());
        assertEquals(o, q.getObject());
        assertTrue(Var.isVar(q.getPredicate()));

        quads = um.getDeleteQuads();
        assertEquals(1, quads.size());
        q = quads.get(0);
        assertEquals(Quad.defaultGraphNodeGenerated, q.getGraph());
        assertEquals(s, q.getSubject());
        assertEquals(v, q.getPredicate());
        assertEquals(o, q.getObject());
        assertTrue(Var.isVar(q.getPredicate()));

        Element e = um.getWherePattern();
        assertTrue(e instanceof ElementGroup);
        ElementGroup eg = (ElementGroup) e;
        assertEquals(1, eg.getElements().size());
        ElementPathBlock epb = (ElementPathBlock) eg.getElements().get(0);
        Triple t = epb.getPattern().get(0).asTriple();
        assertEquals(Node.ANY, t.getSubject());
        assertEquals(v, t.getPredicate());
        assertEquals(builder.makeNode("foo"), t.getObject());
        assertTrue(Var.isVar(t.getPredicate()));
    }
    // testsbased on the examples

    /*
     * 	Example 1: Adding some triples to a graph

    This snippet describes two RDF triples to be inserted into the default graph of the Graph Store.

    PREFIX dc: <http://purl.org/dc/elements/1.1/>
    INSERT DATA
    {
      <http://example/book1> dc:title "A new book" ;
                             dc:creator "A.N.Other" .
    }

    Data before:

    # Default graph
    @prefix dc: <http://purl.org/dc/elements/1.1/> .
    @prefix ns: <http://example.org/ns#> .

    <http://example/book1> ns:price 42 .

    Data after:

    # Default graph
    @prefix dc: <http://purl.org/dc/elements/1.1/> .
    @prefix ns: <http://example.org/ns#> .

    <http://example/book1> ns:price 42 .
    <http://example/book1> dc:title "A new book" .
    <http://example/book1> dc:creator "A.N.Other" .

     */
    @Test
    public void example1() {
        Node n = NodeFactory.createURI("http://example/book1");
        Node priceN = NodeFactory.createURI("http://example.org/ns#price");
        Node priceV = NodeFactory.createLiteral("42");
        UpdateBuilder builder = new UpdateBuilder().addPrefix("dc", DC_11.NS).addInsert(n, DC_11.title, "A new book")
                .addInsert(n, DC_11.creator, "A.N.Other");

        List<Triple> triples = new ArrayList<Triple>();
        triples.add(Triple.create(n, priceN, priceV));
        Graph g = new CollectionGraph(triples);
        Model m = ModelFactory.createModelForGraph(g);
        m.setNsPrefix("dc", DC_11.NS);
        m.setNsPrefix("ns", "http://example.org/ns#");

        UpdateAction.execute(builder.build(), m);

        Resource r = ResourceFactory.createResource(n.getURI());
        Property rPriceP = ResourceFactory.createProperty(priceN.getURI());
        Literal rPriceV = ResourceFactory.createPlainLiteral("42");
        assertTrue(m.contains(r, rPriceP, rPriceV));
        assertTrue(m.contains(r, DC_11.title, "A new book"));
        assertTrue(m.contains(r, DC_11.creator, "A.N.Other"));
        assertEquals(3, triples.size());

    }

    @Test
    public void testPathInWhereClause() {
        Node p = NodeFactory.createURI("http://example.com/p");
        Path path = new P_Link(p);

        // JENA-1739 fails here
        new UpdateBuilder().addDelete("?s", "<x>", "?p").addWhere("?s", path, "?p").build();
    }

    @Test
    public void testPathInOptionalClause() {
        Node p = NodeFactory.createURI("http://example.com/p");
        Path path = new P_Link(p);

        // JENA-1739 fails here
        new UpdateBuilder().addDelete("?s", "<x>", "?p").addOptional("?s", path, "?p").build();
    }
}


text:
<?php
namespace Migration;

use Doctrine\DBAL\Platforms\AbstractPlatform;
use Migration\Exception as MigrationException;
use Migration\ExtensionInterface;

class PlatformFactory implements ExtensionInterface
{

    /**
      *  @var string[] list of doctine platform classes and internal extension classes
      *
      *  If you define a platform for example `MongoDB` then must be defined inside the
      *  Migration\\Components\\Migration\Doctrine\\Platforms namespace and added to the
      *  list below. The user can then override this platform using the
      *  Migration\\Components\\Extension\\Doctine\\Platforms\\ inside the project folder
      *  and registering the extension in bootstrap.
      *
      *  A user can add platforms  not found here from  the extension namespace using the resister
      *  methods
      */
    protected static $platform = array(
        'db2'           => 'Doctrine\\DBAL\\Platforms\\DB2Platform',
        'mysql'         => 'Doctrine\\DBAL\\Platforms\\MySqlPlatform',
        'oracle'        => 'Doctrine\\DBAL\\Platforms\\OraclePlatform',
        'postgresql'    => 'Doctrine\\DBAL\\Platforms\\PostgreSqlPlatform',
        'sqlite'        => 'Doctrine\\DBAL\\Platforms\\SqlitePlatform',
        'sqlserver2005' => 'Doctrine\\DBAL\\Platforms\\SQLServer2005Platform',
        'sqlserver2008' => 'Doctrine\\DBAL\\Platforms\\SQLServer2008Platform',
        'sqlserver'     => 'Doctrine\\DBAL\\Platforms\\SQLServerPlatform',
    );

    public static function registerExtension($index,$namespace)
    {
        $index = strtolower($index);
        return self::$platform[$index] = $namespace;
    }

    public static function registerExtensions(array $extension)
    {
        foreach($extension as $key => $ns) {
            self::registerExtension($key,$ns);
        }
    }

      /**
      *  Map a driver to a platform
      */
    protected static $driver_to_platform = array(
        'pdo_sqlsrv' => 'sqlserver2008',
        'pdo_sqlite' => 'sqlite',
        'pdo_pgsql'  => 'postgresql',
        'pdo_oracle' => 'oracle',
        'pdo_mysql'  => 'mysql',
        'pdo_ibm'    => 'db2',
        'oci8'       => 'oracle',
        'mysqli'     => 'mysql',
        'ibm_db2'    => 'db2'
    );

    public static function registerDriverMap($driver,$platform)
    {
        $index = strtolower($index);
        return self::$platform[$index] = $namespace;
    }

    public static function registerDriverMaps(array $drivers)
    {
        foreach($extension as $driver => $platform) {
            self::registerExtension($driver,$platform);
        }
    }

    //  ----------------------------------------------------------------------------

    /**
      *  Resolve a platform class
      *
      *  @access public
      *  @return Doctrine\DBAL\Platforms\AbstractPlatform
      */
    public function create($platform)
    {
        $platform = strtolower($platform);

        # check default list
        if(isset(self::$platform[$platform]) === false) {
            throw new MigrationException('Platform not found at::'.$platform);
        }

        # assign platform the full namespace
        $platform = self::$platform[$platform];

        return new $platform();

    }

     //  ----------------------------------------------------------------------------

    /**
      *  Resolve a platform class, from a doctrine driver
      *
      *  @access public
      *  @return Doctrine\DBAL\Platforms\AbstractPlatform
      */
    public function createFromDriver($driver)
    {
        # check default list
        if(isset(self::$driver_to_platform[$driver]) === false) {
            throw new MigrationException('Driver not found at::'.$driver);
        }

        # assign platform the full namespace
        $platform = self::$driver_to_platform[$driver];

        return self::create($platform);

    }

}
/* End of File */

redpajama_set_name: RedPajamaGithub


text:
package me.chris.MoneyManager.Commands;

import org.bukkit.entity.Player;

public class CommandHelp
{
	public static void help(Player p)
	{
		p.sendMessage("§5================§c [ Money Manager Help ] §5================");
		p.sendMessage("§c/mm §e- States the general info.");
		p.sendMessage("§c/mm help <command> §e- Brings up the help menu. ");
		p.sendMessage("§c/mm list §7<group> §e- Lists payments for a group or all. ");
		p.sendMessage("§c/mm reload §e- Reloads config files. ");
		p.sendMessage("§c/mm pay §7<group> §e- Pays wages. ");
		p.sendMessage("§c/mm tax §7<group> §e- Takes taxes. ");
		p.sendMessage("§c/mm set §7[group] a:[amount] §e- Sets the payment/tax for a specific group. ");
		p.sendMessage("§c/mm set §7[group] t:[type] §e- Sets the type of payment/tax (Flat_Rate Or Percent). ");
		p.sendMessage("§c/mm sync §7[PermsGroup] [MMGroup] §e- Syncs a permission group's members over to a MM group. ");
		p.sendMessage("§c/mm add §7[group] [player1,player2...] §e- Adds players to a group. ");
		p.sendMessage("§c/mm remove §7[group] [player1,player2...] §e- Removes players from group. ");
		p.sendMessage("§c/mm create §7[group] [pay/tax] [amount] [type] [player1,player2...] §e- Creates a new group. ");
		p.sendMessage("§c/mm delete §7[group] §e- Deletes a group and everything in it.  ");
		p.sendMessage("§cNotes:");
		p.sendMessage("§b§o  [] = Manditory Command. <> = Optional.");
		p.sendMessage("§b§o  Commands are explained in detail with §7/mm help <command>");
		p.sendMessage("§b§o  The SYNC command only works with PermissionsBukkit!");
		p.sendMessage("§5=====================================================");
	}

	public static void help(Player p, String command)
	{
		command = command.toLowerCase();
		if (command.equals("help"))
		{
			p.sendMessage("§5================§c [ Money Manager Help ] §5================");
			p.sendMessage("§eCommand: §c/mm help <command>");
			p.sendMessage("§eExample Usage:");
			p.sendMessage("  §2/mm help");
			p.sendMessage("  §2/mm help create");
			p.sendMessage("  §2/mm help set");
			p.sendMessage("§eExplanation:");
			p.sendMessage("§2  In the first example, the command will just list all the commands that the plugin has to offer. " + "However, on the second and third examples, the optional <command> argument is used. On these examples, the command " + "will return more detailed info on the create command and the set command.");
			p.sendMessage("§5=====================================================");
		}
		else if (command.equals("list"))
		{
			p.sendMessage("§5================§c [ Money Manager Help ] §5================");
			p.sendMessage("§eCommand: §c/mm list <group>");
			p.sendMessage("§eExample Usage:");
			p.sendMessage("  §2/mm list");
			p.sendMessage("  §2/mm list ExampleGroupName");
			p.sendMessage("  §2/mm list AnotherGroup");
			p.sendMessage("§eExplanation:");
			p.sendMessage("§2  The list command has two different ways you can use it. You can list all the groups by leaving the <group> argument " + "blank, and you can also name a group and get more detailed information on that specific group. In examples 2 and 3, the command " + "would return detaled information on the groups ExampleGroupName and AnotherGroup.");
			p.sendMessage("§5=====================================================");
		}
		else if (command.equals("reload"))
		{
			p.sendMessage("§5================§c [ Money Manager Help ] §5================");
			p.sendMessage("§eCommand: §c/mm reload");
			p.sendMessage("§eExample Usage:");
			p.sendMessage("  §2/mm reload");
			p.sendMessage("§eExplanation:");
			p.sendMessage("§2  Reload command is used when you make edits to the plugin\'s config.yml file. After you finish you edits, you can " + "use this command and the plugin will re-parse the config.yml file and intake all the changes you made.");
			p.sendMessage("§5=====================================================");
		}
		else if (command.equals("pay"))
		{
			p.sendMessage("§5================§c [ Money Manager Help ] §5================");
			p.sendMessage("§eCommand: §c/mm pay <group>");
			p.sendMessage("§eExample Usage:");
			p.sendMessage("  §2/mm pay");
			p.sendMessage("  §2/mm pay ExampleGroupName");
			p.sendMessage("  §2/mm pay AnotherGroup");
			p.sendMessage("§eExplanation:");
			p.sendMessage("§2  The pay command is one of the main commands of the plugin and the main purpose to the plugin: To pay players. " + "Using this command without a <group> argument will take all the players in all the groups in the PaymentGroups section " + "of the config.yml and pay them with their respective payment. Using the command with the <group> argument (as shown in " + "examples 2 and 3) will only pay the members of that group that is named.");
			p.sendMessage("§5=====================================================");
		}
		else if (command.equals("tax"))
		{
			p.sendMessage("§5================§c [ Money Manager Help ] §5================");
			p.sendMessage("§eCommand: §c/mm tax <group>");
			p.sendMessage("§eExample Usage:");
			p.sendMessage("  §2/mm tax");
			p.sendMessage("  §2/mm tax ExampleGroupName");
			p.sendMessage("  §2/mm tax AnotherGroup");
			p.sendMessage("§eExplanation:");
			p.sendMessage("§2  The tax command is one of the main commands of the plugin and also one of the main purposes of the plugin: To tax players. " + "Using this command without a <group> argument will take all the players in all the groups in the TaxGroups section " + "of the config.yml and tax them with their respective taxes.  Using the command with the <group> argument (as shown in " + "examples 2 and 3) will only tax the members of that group that is named");
			p.sendMessage("§5=====================================================");
		}
		else if (command.equals("set"))
		{
			p.sendMessage("§5================§c [ Money Manager Help ] §5================");
			p.sendMessage("§eCommand: §c/mm set [group] a:[amount]");
			p.sendMessage("§e         §c/mm set [group] t:[type]");
			p.sendMessage("§eExample Usage:");
			p.sendMessage("  §2/mm set ExampleGroupName a:100");
			p.sendMessage("  §2/mm set ExampleGroupName t:Flat_Rate");
			p.sendMessage("  §2/mm set AnotherGroup a:20");
			p.sendMessage("  §2/mm set AnotherGroup t:Percent");
			p.sendMessage("§eExplanation:");
			p.sendMessage("§2  This is one of the more complicated commands in the plugin. There are two basic variations of this: a and t. " + "a and t are for setting the amount and type variables (respectively) in the config.yml. You put in the Group you want to change " + "the amount or type value, and then you use either a: base or t: base. amount can be any number, but type has to be either " + "\"Flat_Rate\" or \"Percent\".");
			p.sendMessage("§5=====================================================");
		}
		else if (command.equals("sync"))
		{
			p.sendMessage("§5================§c [ Money Manager Help ] §5================");
			p.sendMessage("§eCommand: §c/mm sync [PermsGroup] [MMGroup]");
			p.sendMessage("§eExample Usage:");
			p.sendMessage("  §2/mm sync AdminPermsGroup AdminPayGroup");
			p.sendMessage("  §2/mm sync DonorGroup DonorPayGroup");
			p.sendMessage("  §2/mm sync Members MemberTaxGroup");
			p.sendMessage("§eExplanation:");
			p.sendMessage("§2  This command is designed to sync the members of a permission group with the members of a MoneyManager group... It actually overwrites any member in a MoneyManager group with those in the PermsGroup. This command only works with PermissionsBukkit, but support for other perms plugin is forthcoming. ");
			p.sendMessage("§5=====================================================");
		}
		else if (command.equals("add"))
		{
			p.sendMessage("§5================§c [ Money Manager Help ] §5================");
			p.sendMessage("§eCommand: §c/mm add [group] [player1,player2,player3,player4...]");
			p.sendMessage("§eExample Usage:");
			p.sendMessage("  §2/mm add ExampleGroupName Hotshot2162,Petmagnet13,Kayaloha");
			p.sendMessage("  §2/mm add ExampleGroupName Joecia82");
			p.sendMessage("  §2/mm add AnotherGroup JeremiahBye,MrsBye");
			p.sendMessage("§eExplanation:");
			p.sendMessage("§2  With this command, you can add players to a group. You need to make sure not to put any spaces in the names " + "or else the command will not go through. Seperate each name with a comma (,). There is not limit to the nunber of names " + "you can put. ");
			p.sendMessage("§5=====================================================");
		}
		else if (command.equals("remove"))
		{
			p.sendMessage("§5================§c [ Money Manager Help ] §5================");
			p.sendMessage("§eCommand: §c/mm remove [group] [player1,player2,player3,player4...]");
			p.sendMessage("§eExample Usage:");
			p.sendMessage("  §2/mm remove ExampleGroupName Hotshot2162,Petmagnet13,Kayaloha");
			p.sendMessage("  §2/mm remove ExampleGroupName Joecia82");
			p.sendMessage("  §2/mm remove AnotherGroup JeremiahBye,MrsBye");
			p.sendMessage("§eExplanation:");
			p.sendMessage("§2  This command is just like the add command, except it removes players from a group. Remember to not put any spaces " + "in or between the names, just use commas. Any name that isnt found will be returned and will display in chat that it couldnt be " + "removed because it wasnt found. ");
			p.sendMessage("§5=====================================================");
		}
		else if (command.equals("create"))
		{
			p.sendMessage("§5================§c [ Money Manager Help ] §5================");
			p.sendMessage("§eCommand: §c/mm create [group] [amount] [type] [player1,player2,player3...]");
			p.sendMessage("§eExample Usage:");
			p.sendMessage("  §2/mm create ExampleGroup tax 20 Percent Hotshot2162,Petmagnet13,Kayaloha");
			p.sendMessage("  §2/mm remove GroupName pay 200 Flat_Rate Joecia82,Jayty90yo");
			p.sendMessage("  §2/mm remove AnotherGroup tax 300 Flat_Rate JeremiahBye,MrsBye");
			p.sendMessage("§eExplanation:");
			p.sendMessage("§2  This command is used for creating new groups. The first argument is the group name. The second argument is [pay/tax] " + "which is asking for you to specify if the new gorup in question will be a PaymentGroup or TaxGroup. The third argument is " + "the amount. The fourth argument puts the third into more perspective... In example one, the tax would be 20 percent of what the " + "player has. In example two the payment would be 200. In the third example, the tax would be 300. the last argument is the players, " + "make sure when listing players do not put spaces and use commas to seperate the names.");
			p.sendMessage("§5=====================================================");
		}
		else if (command.equals("delete"))
		{
			p.sendMessage("§5================§c [ Money Manager Help ] §5================");
			p.sendMessage("§eCommand: §c/mm delete [group]");
			p.sendMessage("§eExample Usage:");
			p.sendMessage("  §2/mm delete ExampleGroup");
			p.sendMessage("  §2/mm delete AnotherGroup");
			p.sendMessage("§eExplanation:");
			p.sendMessage("§2  This command is used to delete a group from config.yml. Name the group and it will be deleted. ");
			p.sendMessage("§5=====================================================");
		}
		else
		{
			p.sendMessage("§a[MoneyManager] §4Invalid Command.");
		}
	}
}


text:
/* Author: Troy Straszheim */

/*
 * Spinny spinner basic tests.

 these do NOT ACTUALLY TEST ANYTHING as it is diffcult to restart all
 of ros in a unit test, and there is no way to test (that I can see
 right now) that certain error messages are emitted, nor any way to
 specify that a test should fail or return an error.  So this is just
 a placeholder to be run manually, one test at a time (via
 --gtest_filter) when the next problem occurs.  Those that end with
 'fail' actually success, but they send a fatal error message that
 you're trying to spin from multiple threads.
*/

#include <gtest/gtest.h>
#include "ros/spinner.h"
#include "ros/init.h"
#include "ros/node_handle.h"
#include <boost/thread.hpp>

using namespace ros;

int argc_;
char** argv_;

void fire_shutdown(const ros::WallTimerEvent&) {
  ROS_INFO("Asking for shutdown");
  ros::shutdown();
}

#define DOIT()                                                  \
  ros::init(argc_, argv_, "test_spinners");                     \
  NodeHandle nh;                                                \
  ros::WallTimer t = nh.createWallTimer(ros::WallDuration(2.0), \
                                        &fire_shutdown);        \

TEST(Spinners, spin)
{
  DOIT();
  ros::spin();
}

TEST(Spinners, spinfail)
{
  DOIT();
  boost::thread th(boost::bind(&ros::spin));
  ros::spin();
}

TEST(Spinners, single)
{
  DOIT();
  SingleThreadedSpinner s;
  ros::spin(s);
}

TEST(Spinners, singlefail)
{
  DOIT();
  boost::thread th(boost::bind(&ros::spin));
  SingleThreadedSpinner s;
  ros::spin(s);
}

TEST(Spinners, singlefail2)
{
  DOIT();
  SingleThreadedSpinner s;
  boost::thread th(boost::bind(&ros::spin, s));
  ros::spin(s);
}

TEST(Spinners, multi)
{
  DOIT();
  MultiThreadedSpinner s;
  ros::spin(s);
}

TEST(Spinners, multifail)
{
  DOIT();
  boost::thread th(boost::bind(&ros::spin));
  MultiThreadedSpinner s;
  ros::spin(s);
}

TEST(Spinners, multifail2)
{
  DOIT();
  MultiThreadedSpinner s;
  boost::thread th(boost::bind(&ros::spin, s));
  ros::spin(s);
}

TEST(Spinners, async)
{
  DOIT();
  AsyncSpinner s(2);
  s.start();
  ros::waitForShutdown();
}

TEST(Spinners, asyncfail)
{
  DOIT();
  boost::thread th(boost::bind(&ros::spin));
  AsyncSpinner s(2);
  s.start();
  ros::waitForShutdown();
}

int
main(int argc, char** argv)
{
  testing::InitGoogleTest(&argc, argv);
  argc_ = argc;
  argv_ = argv;
  return RUN_ALL_TESTS();
}


text:
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace Intro
{
	[XamlCompilation(XamlCompilationOptions.Compile)]
	public partial class Example12 : ContentPage
	{
		public Example12 ()
		{
			InitializeComponent ();
		}
	}
}


text:
from __future__ import unicode_literals
import atexit
import os
import shutil
import sys
import django

def main(package="mezzanine"):
    """
    This is the main test function called via ``python setup.py test``.
    It's responsible for hacking the ``project_template`` dir into
    an actual project to test against.
    """

    from mezzanine.utils.importing import path_for_import

    os.environ["DJANGO_SETTINGS_MODULE"] = "project_template.test_settings"
    package_path = path_for_import(package)
    project_path = os.path.join(package_path, "project_template")

    local_settings_path = os.path.join(project_path, "local_settings.py")
    test_settings_path = os.path.join(project_path, "test_settings.py")

    sys.path.insert(0, package_path)
    sys.path.insert(0, project_path)
    if not os.path.exists(test_settings_path):
        shutil.copy(local_settings_path + ".template", test_settings_path)
        with open(test_settings_path, "r") as f:
            local_settings = f.read()
        with open(test_settings_path, "w") as f:
            test_reqs_str = """
from project_template import settings
globals().update(settings.__dict__)
if "mezzanine.accounts" not in settings.INSTALLED_APPS:
    INSTALLED_APPS = list(settings.INSTALLED_APPS) + ["mezzanine.accounts"]
"""
            if django.VERSION >= (1, 7):
                test_reqs_str += "import django\ndjango.setup()"
            f.write(test_reqs_str + local_settings)
        atexit.register(lambda: os.remove(test_settings_path))

    from django.core.management.commands import test
    sys.exit(test.Command().execute(verbosity=1))

if __name__ == "__main__":
    main()


text:
import System.IO

main = do
--  hSetBuffering stdout LineBuffering
  putStrLn "hello"
  putStrLn "world"
--  hFlush stdout


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>27.9. traceback — Print or retrieve a stack traceback — Python v3.2.3 documentation</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python v3.2.3 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python v3.2.3 documentation" href="../index.html" />
    <link rel="up" title="27. Python Runtime Services" href="python.html" />
    <link rel="next" title="27.10. __future__ — Future statement definitions" href="__future__.html" />
    <link rel="prev" title="27.8. atexit — Exit handlers" href="atexit.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />

Navigation

          index

          modules |

          next |

          previous |

Python v3.2.3 documentation »

The Python Standard Library »

27. Python Runtime Services »

27.9. <tt class="xref py py-mod docutils literal">traceback</tt> — Print or retrieve a stack traceback¶

This module provides a standard interface to extract, format and print stack
traces of Python programs.  It exactly mimics the behavior of the Python
interpreter when it prints a stack trace.  This is useful when you want to print
stack traces under program control, such as in a “wrapper” around the
interpreter.

The module uses traceback objects — this is the object type that is stored in
the <tt class="xref py py-data docutils literal">sys.last_traceback</tt> variable and returned as the third item from
<tt class="xref py py-func docutils literal">sys.exc_info()</tt>.

The module defines the following functions:

<tt class="descclassname">traceback.</tt><tt class="descname">print_tb</tt><big>(</big>traceback, limit=None, file=None<big>)</big>¶

Print up to limit stack trace entries from traceback.  If limit is omitted
or <tt class="xref docutils literal">None</tt>, all entries are printed. If file is omitted or <tt class="xref docutils literal">None</tt>, the
output goes to <tt class="docutils literal">sys.stderr</tt>; otherwise it should be an open file or file-like
object to receive the output.

<tt class="descclassname">traceback.</tt><tt class="descname">print_exception</tt><big>(</big>type, value, traceback, limit=None, file=None, chain=True<big>)</big>¶

Print exception information and up to limit stack trace entries from
traceback to file. This differs from <tt class="xref py py-func docutils literal">print_tb()</tt> in the following
ways:

if traceback is not <tt class="xref docutils literal">None</tt>, it prints a header <tt class="docutils literal">Traceback (most recent
call last):</tt>

it prints the exception type and value after the stack trace

if type is <tt class="xref py py-exc docutils literal">SyntaxError</tt> and value has the appropriate format, it
prints the line where the syntax error occurred with a caret indicating the
approximate position of the error.

If chain is true (the default), then chained exceptions (the
<tt class="xref py py-attr docutils literal">__cause__</tt> or <tt class="xref py py-attr docutils literal">__context__</tt> attributes of the exception) will be
printed as well, like the interpreter itself does when printing an unhandled
exception.

<tt class="descclassname">traceback.</tt><tt class="descname">print_exc</tt><big>(</big>limit=None, file=None, chain=True<big>)</big>¶

This is a shorthand for <tt class="docutils literal">print_exception(*sys.exc_info())</tt>.

<tt class="descclassname">traceback.</tt><tt class="descname">print_last</tt><big>(</big>limit=None, file=None, chain=True<big>)</big>¶

This is a shorthand for <tt class="docutils literal">print_exception(sys.last_type, sys.last_value,
sys.last_traceback, limit, file)</tt>.  In general it will work only after
an exception has reached an interactive prompt (see <tt class="xref py py-data docutils literal">sys.last_type</tt>).

<tt class="descclassname">traceback.</tt><tt class="descname">print_stack</tt><big>(</big>f=None, limit=None, file=None<big>)</big>¶

This function prints a stack trace from its invocation point.  The optional f
argument can be used to specify an alternate stack frame to start.  The optional
limit and file arguments have the same meaning as for
<tt class="xref py py-func docutils literal">print_exception()</tt>.

<tt class="descclassname">traceback.</tt><tt class="descname">extract_tb</tt><big>(</big>traceback, limit=None<big>)</big>¶

Return a list of up to limit “pre-processed” stack trace entries extracted
from the traceback object traceback.  It is useful for alternate formatting of
stack traces.  If limit is omitted or <tt class="xref docutils literal">None</tt>, all entries are extracted.  A
“pre-processed” stack trace entry is a quadruple (filename, line number,
function name, text) representing the information that is usually printed
for a stack trace.  The text is a string with leading and trailing whitespace
stripped; if the source is not available it is <tt class="xref docutils literal">None</tt>.

<tt class="descclassname">traceback.</tt><tt class="descname">extract_stack</tt><big>(</big>f=None, limit=None<big>)</big>¶

Extract the raw traceback from the current stack frame.  The return value has
the same format as for <tt class="xref py py-func docutils literal">extract_tb()</tt>.  The optional f and limit
arguments have the same meaning as for <tt class="xref py py-func docutils literal">print_stack()</tt>.

<tt class="descclassname">traceback.</tt><tt class="descname">format_list</tt><big>(</big>list<big>)</big>¶

Given a list of tuples as returned by <tt class="xref py py-func docutils literal">extract_tb()</tt> or
<tt class="xref py py-func docutils literal">extract_stack()</tt>, return a list of strings ready for printing.  Each string
in the resulting list corresponds to the item with the same index in the
argument list.  Each string ends in a newline; the strings may contain internal
newlines as well, for those items whose source text line is not <tt class="xref docutils literal">None</tt>.

<tt class="descclassname">traceback.</tt><tt class="descname">format_exception_only</tt><big>(</big>type, value<big>)</big>¶

Format the exception part of a traceback.  The arguments are the exception type
and value such as given by <tt class="docutils literal">sys.last_type</tt> and <tt class="docutils literal">sys.last_value</tt>.  The return
value is a list of strings, each ending in a newline.  Normally, the list
contains a single string; however, for <tt class="xref py py-exc docutils literal">SyntaxError</tt> exceptions, it
contains several lines that (when printed) display detailed information about
where the syntax error occurred.  The message indicating which exception
occurred is the always last string in the list.

<tt class="descclassname">traceback.</tt><tt class="descname">format_exception</tt><big>(</big>type, value, tb, limit=None, chain=True<big>)</big>¶

Format a stack trace and the exception information.  The arguments  have the
same meaning as the corresponding arguments to <tt class="xref py py-func docutils literal">print_exception()</tt>.  The
return value is a list of strings, each ending in a newline and some containing
internal newlines.  When these lines are concatenated and printed, exactly the
same text is printed as does <tt class="xref py py-func docutils literal">print_exception()</tt>.

<tt class="descclassname">traceback.</tt><tt class="descname">format_exc</tt><big>(</big>limit=None, chain=True<big>)</big>¶

This is like <tt class="docutils literal">print_exc(limit)</tt> but returns a string instead of printing to a
file.

<tt class="descclassname">traceback.</tt><tt class="descname">format_tb</tt><big>(</big>tb, limit=None<big>)</big>¶

A shorthand for <tt class="docutils literal">format_list(extract_tb(tb, limit))</tt>.

<tt class="descclassname">traceback.</tt><tt class="descname">format_stack</tt><big>(</big>f=None, limit=None<big>)</big>¶

A shorthand for <tt class="docutils literal">format_list(extract_stack(f, limit))</tt>.

27.9.1. Traceback Examples¶

This simple example implements a basic read-eval-print loop, similar to (but
less useful than) the standard Python interactive interpreter loop.  For a more
complete implementation of the interpreter loop, refer to the <tt class="xref py py-mod docutils literal">code</tt>
module.

import sys, traceback

def run_user_code(envdir):
    source = input(">>> ")
    try:
        exec(source, envdir)
    except:
        print("Exception in user code:")
        print("-"*60)
        traceback.print_exc(file=sys.stdout)
        print("-"*60)

envdir = {}
while True:
    run_user_code(envdir)

The following example demonstrates the different ways to print and format the
exception and traceback:

import sys, traceback

def lumberjack():
    bright_side_of_death()

def bright_side_of_death():
    return tuple()[0]

try:
    lumberjack()
except IndexError:
    exc_type, exc_value, exc_traceback = sys.exc_info()
    print("*** print_tb:")
    traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
    print("*** print_exception:")
    traceback.print_exception(exc_type, exc_value, exc_traceback,
                              limit=2, file=sys.stdout)
    print("*** print_exc:")
    traceback.print_exc()
    print("*** format_exc, first and last line:")
    formatted_lines = traceback.format_exc().splitlines()
    print(formatted_lines[0])
    print(formatted_lines[-1])
    print("*** format_exception:")
    print(repr(traceback.format_exception(exc_type, exc_value,
                                          exc_traceback)))
    print("*** extract_tb:")
    print(repr(traceback.extract_tb(exc_traceback)))
    print("*** format_tb:")
    print(repr(traceback.format_tb(exc_traceback)))
    print("*** tb_lineno:", exc_traceback.tb_lineno)

The output for the example would look similar to this:

*** print_tb:
  File "<doctest...>", line 10, in <module>
    lumberjack()
*** print_exception:
Traceback (most recent call last):
  File "<doctest...>", line 10, in <module>
    lumberjack()
  File "<doctest...>", line 4, in lumberjack
    bright_side_of_death()
IndexError: tuple index out of range
*** print_exc:
Traceback (most recent call last):
  File "<doctest...>", line 10, in <module>
    lumberjack()
  File "<doctest...>", line 4, in lumberjack
    bright_side_of_death()
IndexError: tuple index out of range
*** format_exc, first and last line:
Traceback (most recent call last):
IndexError: tuple index out of range
*** format_exception:
['Traceback (most recent call last):\n',
 '  File "<doctest...>", line 10, in <module>\n    lumberjack()\n',
 '  File "<doctest...>", line 4, in lumberjack\n    bright_side_of_death()\n',
 '  File "<doctest...>", line 7, in bright_side_of_death\n    return tuple()[0]\n',
 'IndexError: tuple index out of range\n']
*** extract_tb:
[('<doctest...>', 10, '<module>', 'lumberjack()'),
 ('<doctest...>', 4, 'lumberjack', 'bright_side_of_death()'),
 ('<doctest...>', 7, 'bright_side_of_death', 'return tuple()[0]')]
*** format_tb:
['  File "<doctest...>", line 10, in <module>\n    lumberjack()\n',
 '  File "<doctest...>", line 4, in lumberjack\n    bright_side_of_death()\n',
 '  File "<doctest...>", line 7, in bright_side_of_death\n    return tuple()[0]\n']
*** tb_lineno: 10

The following example shows the different ways to print and format the stack:

>>> import traceback
>>> def another_function():
...     lumberstack()
...
>>> def lumberstack():
...     traceback.print_stack()
...     print(repr(traceback.extract_stack()))
...     print(repr(traceback.format_stack()))
...
>>> another_function()
  File "<doctest>", line 10, in <module>
    another_function()
  File "<doctest>", line 3, in another_function
    lumberstack()
  File "<doctest>", line 6, in lumberstack
    traceback.print_stack()
[('<doctest>', 10, '<module>', 'another_function()'),
 ('<doctest>', 3, 'another_function', 'lumberstack()'),
 ('<doctest>', 7, 'lumberstack', 'print(repr(traceback.extract_stack()))')]
['  File "<doctest>", line 10, in <module>\n    another_function()\n',
 '  File "<doctest>", line 3, in another_function\n    lumberstack()\n',
 '  File "<doctest>", line 8, in lumberstack\n    print(repr(traceback.format_stack()))\n']

This last example demonstrates the final few formatting functions:

>>> import traceback
>>> traceback.format_list([('spam.py', 3, '<module>', 'spam.eggs()'),
...                        ('eggs.py', 42, 'eggs', 'return "bacon"')])
['  File "spam.py", line 3, in <module>\n    spam.eggs()\n',
 '  File "eggs.py", line 42, in eggs\n    return "bacon"\n']
>>> an_error = IndexError('tuple index out of range')
>>> traceback.format_exception_only(type(an_error), an_error)
['IndexError: tuple index out of range\n']

Table Of Contents

27.9. <tt class="docutils literal">traceback</tt> — Print or retrieve a stack traceback

27.9.1. Traceback Examples

Previous topic

27.8. <tt class="docutils literal docutils literal docutils literal">atexit</tt> — Exit handlers

Next topic

27.10. <tt class="docutils literal docutils literal docutils literal">__future__</tt> — Future statement definitions

This Page

Report a Bug

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" size="18" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          modules |

          next |

          previous |

Python v3.2.3 documentation »

The Python Standard Library »

27. Python Runtime Services »

    © Copyright 1990-2012, Python Software Foundation.

    The Python Software Foundation is a non-profit corporation.
    Please donate.

    Last updated on Apr 11, 2012.
    Found a bug?

    Created using Sphinx 1.0.7.


text:
/*global module,require*/

(function(module, require) {
    "use strict";

    var express = require('express');
    var router = express.Router();

    /* GET home page. */
    router.get('/', function (req, res, next) {
        res.json('index', {title: 'Express'});
    });

    module.exports = router;

})(module, require);


text:
/* AxisScale.ts
 * ================
 *
 * @project Our World In Data
 * @author  Jaiden Mispy
 * @created 2017-02-11
 */

import {scaleLog, scaleLinear, ScaleLinear, ScaleLogarithmic} from 'd3-scale'
import {map, extend} from './Util'
import {observable, computed, toJS} from 'mobx'

export type ScaleType = 'linear' | 'log'

export interface AxisConfig {
    scaleType: ScaleType,
    scaleTypeOptions: ScaleType[],
    tickFormat: (v: number) => string,
    domain: [number, number],
    label: string
}

export default class AxisScale {
    @observable scaleType: ScaleType
    @observable.struct scaleTypeOptions: ScaleType[]
    @observable tickFormat: (v: number) => string
    @observable.struct domain: [number, number]
    @observable.struct range: [number, number]
    @observable hideFractionalTicks: boolean
    @observable hideGridlines: boolean

    constructor({ scaleType = 'linear',
                  scaleTypeOptions = ['linear'],
                  tickFormat = (d => d.toString()),
                  domain = [0, 0],
                  range = [0, 0],
                  hideFractionalTicks = false,
                  hideGridlines = false }:
                { scaleType?: ScaleType, scaleTypeOptions?: ScaleType[],
                  tickFormat?: (v: number) => string, domain: [number, number], range?: [number, number],
                  hideFractionalTicks?: boolean, hideGridlines?: boolean }) {
        this.scaleType = scaleType
        this.scaleTypeOptions = scaleTypeOptions
        this.tickFormat = tickFormat
        this.domain = domain
        this.range = range
        this.hideFractionalTicks = hideFractionalTicks
        this.hideGridlines = hideGridlines
    }

    @computed get d3_scaleConstructor(): any {
        return this.scaleType === 'log' ? scaleLog : scaleLinear
    }

    @computed get d3_scale(): ScaleLinear<number, number> | ScaleLogarithmic<number, number> {
        return this.d3_scaleConstructor().domain(this.domain).range(this.range)
    }

    @computed get rangeSize() {
        return Math.abs(this.range[1]-this.range[0])
    }

    @computed get rangeMax() {
        return Math.max(this.range[1], this.range[0])
    }

    @computed get rangeMin() {
        return Math.min(this.range[1], this.range[0])
    }

    getTickValues(): number[] {
        const {scaleType, domain, d3_scale} = this

        let ticks: number[] = []
        if (scaleType === 'log') {
            let minPower10 = Math.ceil(Math.log(domain[0]) / Math.log(10))
            if (!isFinite(minPower10)) minPower10 = 0
            let maxPower10 = Math.floor(Math.log(domain[1]) / Math.log(10))
            if (maxPower10 <= minPower10) maxPower10 += 1

            for (let i = minPower10; i <= maxPower10; i++) {
                ticks.push(Math.pow(10, i))
            }
        } else {
            ticks = d3_scale.ticks(6)
        }

        if (this.hideFractionalTicks)
            ticks = ticks.filter(t => t % 1 === 0)

        return ticks
    }

    getFormattedTicks(): string[] {
        return map(this.getTickValues(), this.tickFormat)
    }

    place(value: number) {
        if (!this.range) {
            console.error("Can't place value on scale without a defined output range")
            return value
        } else if (this.scaleType === 'log' && value <= 0) {
            console.error("Can't have values <= 0 on a log scale")
            return value
        }
        return parseFloat(this.d3_scale(value).toFixed(1))
    }

    extend(props: any) {
        return new AxisScale(extend(toJS(this), props))
    }
}


text:
A mobile-friendly web application that helps you workout! Based on your availability and workout preferences, you will receive texts that encourage quick workout sessions that can be done without any equiptment or change of apparel. If you complete a session just send a text back saying "yes", "yay!" or "bananas" and we will monitor your progress which is available immediately and at all times on our website.

 Quick 30 second workouts throughout the day can be un onabtrusive way to stay
 in shape!

### Dev Guide

For now, don't develop on it, still a bit hacky... (hackathons...)


text:
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include "levelType.h"

using namespace std;

void drawWinScreen(){
	for (int i = 0; i < 25; i++){
		cout << endl;
	}

	cout << "Congratulate! You are winner!" << endl;
}

void drawLossScreen(){
	cout << endl << "You lose! Good day, sir." << endl;
}

void gameLoop(levelType level){
	char userInput;
	while(true){

		// winOrLose - 0 means game isn't finished, 1 means win, 2 means loss
		int winOrLose = 0;

		level.drawMap();

		cin >> userInput;
		if (userInput == 'q')
			break;
		else
			winOrLose = level.iterateMap(userInput);
		cout << endl << endl;

		if (winOrLose == 1){
			level.drawMap();
			drawWinScreen();
			break;
		}
		else if (winOrLose == 2){
			level.drawMap();
			drawLossScreen();
			break;
		}
	}
}

int main(){
	bool userCont = true;
	string levelName = "";
	bool  restart = false;
	while (userCont){
		if (!restart){
			cout << "Enter the filename for the level you want to load: ";
			cin >> levelName;
		}

		ifstream levelFile;
		levelFile.open(levelName.c_str());

		if (!levelFile.is_open()){
			cout << "Level not found. Make sure you typed it correctly, ";
			cout << "and that it is in the game's directory." << endl << endl;
			continue;
		}
		levelType level(levelFile);

		levelFile.close();

		gameLoop(level);

		char cUserCont;
		cout << endl << "Would you like to continue, quit, or restart? "
				<< "(c/q/r): ";
		cin >> cUserCont;

		if (cUserCont == 'c' || cUserCont == 'C')
			userCont = true;
		else if (cUserCont == 'r' || cUserCont == 'R'){
			restart = true;
			userCont = true;
		}
		else
			userCont = false;
	}

	return 0;
}


text: Efficient Programming with Components Course by Alex Stepanov


text:
package eventoscientificos.model;

/**
 * Representa uma instância de Instituicao de Afiliacao através do nome.
 *
 * @author G01
 */
public class InstituicaoAfiliacao {

    /**
     * Nome da instituicao de afiliacao.
     */
    private String nome;

    /**
     * Constrói uma instância de uma instituição de afiliação recebendo o nome.
     *
     * @param nome  Nome da instituição de afiliação.
     */
    public InstituicaoAfiliacao(String nome) {
        setNomeInstituicaoAfiliacao(nome);
    }

    /**
     * Devolve o nome da instituicao de afiliacao.
     *
     * @return Nome da instituicao de afiliacao.
     */
    public String getNomeInstituicaoAfiliacao() {
        return this.nome;
    }

     /**
     * Modifica o nome da instituição de afiliação.
     *
     * @param nome Novo nome da instituição de afiliação.
     */
    public void setNomeInstituicaoAfiliacao(String nome) {
        if(nome.trim().isEmpty()) {
            throw new IllegalArgumentException("O nome da instituição de "
                    + "afiliação não pode estar vazio");
        }
        this.nome = nome;
    }

    /**
     * Verifica se o nome da instituição de afiliação
     * @return Verdadeiro
     */
    public boolean validarInstituicaoAfiliacao() {
        return true;
    }

    /**
     * Devolve a descrição textual da instituiçao de afiliação no formato: nome.
     *
     * @return Caracteristicas da instituição de afiliação.
     */
    @Override
    public String toString() {
        return String.format("%s", this.getNomeInstituicaoAfiliacao());
    }

}


text:
package software.egger;

import org.junit.Test;

import java.util.concurrent.*;

public class br_combining_completable_futures {

    CountDownLatch done = new CountDownLatch(1);

    @Test
    public void combineMultipleFutures() throws ExecutionException, InterruptedException {

        CompletableFuture.supplyAsync(() -> 10L).thenAccept(System.out::println).thenRun(done::countDown);
        System.out.println("---");
        done.await();

        // ..Async methods run the subsequent method in a new thread pool.
        done = new CountDownLatch(1);
        CompletableFuture.supplyAsync(() -> 10L).thenAcceptAsync(System.out::println).thenRun(done::countDown);
        System.out.println("---");
        done.await();

        done = new CountDownLatch(1);
        // passing results from one task to the other
        CompletableFuture.supplyAsync(() -> 10L).thenApply(x -> x * 2).thenAccept(System.out::println).thenRun(done::countDown);
        System.out.println("---");
        done.await();

        done = new CountDownLatch(1);
        CompletableFuture.supplyAsync(() -> 10L).thenRun(() -> System.out.println("TEST")).thenRun(done::countDown);
        System.out.println("---");
        done.await();

        done = new CountDownLatch(1);
        CompletableFuture.supplyAsync(() -> 10L)
                .thenCombine(CompletableFuture.supplyAsync(() -> 15L), (r1, r2) -> r1 + r2)
                .thenAccept(System.out::println)
                .thenRun(done::countDown);
        System.out.println("---");
        done.await();

        // What about exceptions?
        done = new CountDownLatch(1);
        CompletableFuture.supplyAsync(() -> 10L).thenApply(x -> {
            throw new NullPointerException(("BANG"));
        }).handle((r, e) -> {
            if (e != null)
                return e.getMessage();
            return r.toString();
        }).thenAccept(System.out::println)
                .thenRun(done::countDown);
        System.out.println("---");
        done.await();

        done = new CountDownLatch(1);
        CompletableFuture.allOf(
                CompletableFuture.supplyAsync(() -> 10L),
                CompletableFuture.supplyAsync(() -> 20L)
        ).thenRun(() -> System.out.println("Hallo")).thenRun(done::countDown);
        System.out.println("---");
        done.await();

        done = new CountDownLatch(1);
        CompletableFuture.supplyAsync(() -> 10L)
                .applyToEither(CompletableFuture.supplyAsync(() -> 20L),
                        x -> x * 5) // 10 * 5 or 20 * 5 which ever completes first
                .thenAccept(System.out::println)
                .thenRun(done::countDown);
        System.out.println("---");
        done.await();

    }
}


text:
<!doctype html>

    <meta charset="utf-8">

    <title>YeAPF Developer aid</title>
    <meta name="description" content="0.8.51 Develop">
    <meta name="author" content="Copyright (C) 2004-2016 Esteban Daniel Dortta - dortta@yahoo.com">

    <link rel="stylesheet" href="#(sessionCWD)/yDevelop.css?v=1.0">
    <link rel="stylesheet" href="#(sessionCWD)/skin-foundation/foundation-icons.css?v=1.0">

          <select onchange="javascript:yDevelopMenu(this)" id='yds_options'>
            <option value='dbConnection'>Banco de dados</option>
            <option value='dbTables'>Tabelas</option>
            <option value='dbMenu'>Menu / Eventos</option>
          </select>

Home

Reload

A fazer

Planejamento

Modelagem

Voltar

                [ . =>  ]
              Halted!

              <input type=text name='parentEvent' class=input title="Event's parent" size=13> / <input type=text name='newLabel' class=input title='Label for user interface' size=13>:<input type=text name='newS' class=input title='Subject' size=13> <button class=button id=eventDsgnButton>Save</button>

              <form onsubmit='{return false;}' name='todo_Form' id='todo_Form'>

A fazer:

                <input type=text id='todoItem' size=60> <input type=button onclick='javascript:ytodoSaveForm(this)' value='Salvar'>
                <input type='hidden' id='id'>

              </form>


text:
"""A more advanced Reducer, using Python iterators and generators."""

from itertools import groupby
from operator import itemgetter
import sys

A = 10
B = 35

def read_mapper_output(file, separator='\t'):
    for line in file:
        yield line.rstrip().split(separator, 1)

def main(separator='\t'):
    # input comes from STDIN (standard input)
    data = read_mapper_output(sys.stdin, separator=separator)
    # groupby groups multiple word-count pairs by word,
    # and creates an iterator that returns consecutive keys and their group:
    #   current_word - string containing a word (the key)
    #   group - iterator yielding all ["<current_word>", "<count>"] items
    for current_word, group in groupby(data, itemgetter(0)):
        try:
            total_count = sum(int(count) for current_word, count in group)
            if A <= total_count <= B:
                print("%s%s%d" % (current_word, separator, total_count))
        except ValueError:
            # count was not a number, so silently discard this item
            pass

if __name__ == "__main__":
    main()


text:
class ofApp: public ofBaseApp
{
public:
    void setup() override;
    void draw() override;

    void keyPressed(int key) override;

    int myA; // This variable has "class" scope.
    int myC = 0; // This variable has "class" scope.

    int myVariable = 99; // This variable has "class" scope.

};


text:
struct LightingData
{
    HOST_AND_DEVICE LightingData() {}

    uint32_t dirLightCount;
    CUDA::DirectionalLight* dirLights;

    uint8_t indirectBounceCount;
    float indirectIntensity;
};


text:
using Victor.Model;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Victor.Graphics
{
    public class ImageTexture
    {
        private List<Texture2D> _texture;
        private Texture2D _couleur;
        private List<string> _assetName;
        private List<Vector2> _position;
        private List<Rectangle> _rectangle;
        private string _name;
        private int _idQuestion;

        #region Get/Set
        public int IdQuestion
        {
            get
            {
                return _idQuestion;
            }
            set
            {
                _idQuestion = value;
            }
        }

        public List<Vector2> Position
        {
            get
            {
                return _position;
            }
            set
            {
                _position = value;
            }
        }

        public List<Rectangle> Rectangle
        {
            get
            {
                return _rectangle;
            }
            set
            {
                _rectangle = value;
            }
        }
        public List<Texture2D> Texture
        {
            get
            {
                return _texture;
            }
            set
            {
                _texture = value;
            }
        }

        public string Name
        {
            get
            {
                return _name;
            }
        }

        public Color[] TextureData
        {
            get
            {

                Color[] textureData = new Color[_texture.ElementAt(0).Width * _texture.ElementAt(0).Height];
                _texture.ElementAt(0).GetData(textureData);
                return textureData;
            }
        }

        #endregion

        public ImageTexture()
        {
            _name = "Defaut";
            _assetName = new List<string>();
            _position = new List<Vector2>();
            _rectangle = new List<Rectangle>();

        }

        public ImageTexture(int idQuestion, string name, List<string> assetName, List<Vector2> position, List<int> longueur, List<int> hauteur)
        {
            _idQuestion = idQuestion;
            _name = name;
            _assetName = assetName;
            _position = position;
            _rectangle = new List<Rectangle>();
            int i = 0;
            foreach (var positionTmp in _position)
            {

                _rectangle.Add(new Rectangle((int)positionTmp.X, (int)positionTmp.Y, longueur.ElementAt(i), hauteur.ElementAt(i)));
                i++;
            }
        }

        public ImageTexture(int idQuestion, string name, string assetName, Vector2 position, int longueur, int hauteur)
        {
            _idQuestion = idQuestion;
            _name = name;
            _assetName = new List<string>();
            _assetName.Add(assetName);
            _position = new List<Vector2>();
            _position.Add(position);
            _rectangle = new List<Rectangle>();
            _rectangle.Add(new Rectangle((int)position.X, (int)position.Y, longueur, hauteur));

        }

        //public bool Collision(Victor victor)
        //{
        //    if (!Session.verification_item(Name))
        //        foreach (var rectangle in _rectangle)
        //        {
        //            foreach (var rectangleVictor in victor.Rectangle)
        //            {
        //                if (rectangle.Intersects(rectangleVictor))
        //                    return true;
        //            }

        //        }
        //    return false;

        //}

        //public bool CollisionParPixel(Victor victor)
        //{
        //    int top = Math.Max(Rectangle.ElementAt(0).Top, victor.Rectangle.Top);
        //    int bottom = Math.Min(Rectangle.ElementAt(0).Bottom, victor.Rectangle.Bottom);
        //    int left = Math.Max(Rectangle.ElementAt(0).Left, victor.Rectangle.Left);
        //    int right = Math.Min(Rectangle.ElementAt(0).Right, victor.Rectangle.Right);

        //    float imageRatioHauteur = (float)(_texture.ElementAt(0).Height / Rectangle.ElementAt(0).Height) * _texture.ElementAt(0).Width;
        //    float imageRatioLargeur = (float)(_texture.ElementAt(0).Width / Rectangle.ElementAt(0).Width);

        //    int debutSprite = (victor.Texture.Width / (victor.MaxIndex + 1)) * victor.CurrentIndex;
        //    float victorRatioHauteur = (float)(victor.Texture.Height / victor.Rectangle.Height) * victor.Texture.Width;
        //    float victorRatioLargeur = (float)((float)(victor.Texture.Width / (victor.MaxIndex + 1)) / victor.Rectangle.Width);

        //    for (int y = bottom - 1; y >= top; y -= 1)
        //    {
        //        for (int x = left; x < right; x += 1)
        //        {
        //            Color currentColor = TextureData[(int)((x - Rectangle.ElementAt(0).X) * imageRatioLargeur) + (int)((y - Rectangle.ElementAt(0).Y) * imageRatioHauteur)];
        //            Color imageColor = victor.TextureData[debutSprite + (int)((x - victor.Rectangle.X) * victorRatioLargeur) + (int)((y - victor.Rectangle.Y) * victorRatioHauteur)];

        //            if (currentColor.A != 0 && imageColor.A != 0)
        //                return true;

        //        }

        //    }
        //    return false;
        //}

        public void AjoutTexture(string texture, Vector2 position, int longueur, int hauteur, ContentManager Content)
        {
            _assetName.Add(texture);
            //_texture.Add(Content.Load<Texture2D>(texture));
            _position.Add(position);
            _rectangle.Add(new Rectangle((int)position.X, (int)position.Y, longueur, hauteur));
        }

        public void LoadContent(ContentManager Content)
        {
            _texture = new List<Texture2D>();
            foreach (var textureTmp in _assetName)
            {
                _texture.Add(Content.Load<Texture2D>(@textureTmp));

            }
            if (!Session.verification_item(Name))
                _couleur = Content.Load<Texture2D>(_assetName.ElementAt(0) + "2");

        }

        public void Deplacement(Vector2 direction)
        {
            List<Rectangle> tmpRectangle = new List<Rectangle>();
            foreach (var image in _rectangle)
            {
                tmpRectangle.Add(new Rectangle(image.X + (int)direction.X, image.Y + (int)direction.Y, image.Width, image.Height));

            }
            _rectangle = tmpRectangle;

            List<Vector2> tmpRectangle2 = new List<Vector2>();
            foreach (var position in _position)
            {
                tmpRectangle2.Add(new Vector2(position.X + (int)direction.X, position.Y + (int)direction.Y));

            }
            _position = tmpRectangle2;

        }

        public void Replacement(Vector2 endroit)
        {
            List<Rectangle> tmpRectangle = new List<Rectangle>();
            foreach (var image in _rectangle)
            {
                tmpRectangle.Add(new Rectangle((int)endroit.X, (int)endroit.Y, image.Width, image.Height));

            }
            _rectangle = tmpRectangle;

        }

        public void Draw(SpriteBatch spriteBatch)
        {
            int i = 0;
            foreach (var textureTmp in _texture)
            {
                if (!Session.verification_item(Name))
                    spriteBatch.Draw(_couleur, _rectangle.ElementAt(i), Color.White);
                else
                    spriteBatch.Draw(textureTmp, _rectangle.ElementAt(i), Color.White);
                i++;
            }
        }

        public void DrawRotation(SpriteBatch spriteBatch, float rotation, Vector2 pointRef)
        {
            int i = 0;
            foreach (var textureTmp in _texture)
            {
                if (!Session.verification_item(Name))
                    spriteBatch.Draw(_couleur, _rectangle.ElementAt(i), null, Color.White, rotation, pointRef, SpriteEffects.None, 0);
                else
                    spriteBatch.Draw(textureTmp, _rectangle.ElementAt(i), null, Color.White, rotation, pointRef, SpriteEffects.None, 0);

                i++;
            }
        }

        public String testTransparence()
        {
            int top = Rectangle.ElementAt(0).Top;
            int bottom = Rectangle.ElementAt(0).Bottom;
            int left = Rectangle.ElementAt(0).Left;
            int right = Rectangle.ElementAt(0).Right;
            String result = "";
            String a;
            for (int y = top; y <= bottom; y += 4)
            {
                for (int x = left; x <= right; x += 2)
                {
                    Color currentColor = TextureData[(int)((x - Rectangle.ElementAt(0).X) * (float)(_texture.ElementAt(0).Width / Rectangle.ElementAt(0).Width)) + (int)((y - Rectangle.ElementAt(0).Y) * (float)(_texture.ElementAt(0).Height / Rectangle.ElementAt(0).Height)) * _texture.ElementAt(0).Width];
                    if (currentColor.A != 0)
                        a = "0";
                    else
                        a = ".";

                    result = result + a;
                }
                result = result + "\n ";

            }
            return result;
        }
    }
}


text:
import {
	fetchTagAction,
	fetchIssueByFilter,
	fetchUpdateIssueTag,
	fetchUpdateIssueNote,
	fetchIssueByOwnTag,
	fetchComments
} from '../service/service'
//TAG
export const REQUEST_TAG = 'REQUEST_TAG';
export const RECEIVE_TAG = 'RECEIVE_TAG';
export const INVAILD_TAG = 'INVAILD_TAG';
export const REQUESTTAG_FAILD = 'REQUESTTAG_FAILD';
export const UPDATE_TAGTABLE = 'UPDATE_TAGTABLE';
export const UPDATE_TAGSTATE = 'UPDATE_TAGSTATE';
export const UPDATE_SHOWINGISSUESTAG = 'UPDATE_SHOWINGISSUESTAG';

//ISSUE
export const INVALIDATE_ISSUE = 'INVALIDATE_ISSUE'
export const REQUEST_ISSUE_FAILD = 'REQUEST_ISSUE_FAILD'
export const REQUEST_ISSUE = 'REQUEST_ISSUE';
export const RECEIVE_ISSUE = 'RECEIVE_ISSUE';
//ISSUE TAG
export const REQUEST_ISSUETAG_FAILD = 'REQUEST_ISSUETAG_FAILD'
export const REQUEST_ISSUETAG = 'REQUEST_ISSUETAG';
export const RECEIVE_ISSUETAG = 'RECEIVE_ISSUETAG';
export const UPDATE_ISSUETAG = 'UPDATE_ISSUETAG';
//ISSUE NOTE
export const UPDATE_ISSUENOTE = 'UPDATE_ISSUENOTE';
//ISSUE COMMENTS
export const REQUEST_COMMENTS_FAILD = 'REQUEST_COMMENTS_FAILD';
export const REQUEST_COMMENTS = 'REQUEST_COMMENTS';
export const RECEIVE_COMMENTS = 'RECEIVE_COMMENTS';

const requestComments = (value) => ({
	type: REQUEST_COMMENTS,
	value
});

const requestCommentsFaild = (value) => ({
	type: REQUEST_COMMENTS_FAILD,
	value
});

const receiveComments = (value) => ({
	type: RECEIVE_COMMENTS,
	value
});

export const fetchCommentsByNumber = ({ access_token, repos, number }) => {
	return dispatch => {
		dispatch(requestComments(number))
		return fetchComments(access_token, repos, number).then((comments) => {
			dispatch(receiveComments({ comments: comments, number: number }))
		}).catch((error) => {
			dispatch(requestCommentsFaild(error))
		})
	}
}

export function invalidateIssue(value) {
	return {
		type: INVALIDATE_ISSUE,
		value
	}
}
const requestIssue = (value) => ({
	type: REQUEST_ISSUE,
	value
});

const requestIssueFaild = (value) => ({
	type: REQUEST_ISSUE_FAILD,
	value
});

export  const receiveIssue = (value) => ({
	type: RECEIVE_ISSUE,
	value
});
const fetchIssue = ({ access_token, filter, repos, userID, repoID }) => {
	return dispatch => {
		dispatch(requestIssue())
		return fetchIssueByFilter(access_token, filter, repos, userID, repoID).then((issue) => {
			dispatch(receiveIssue(issue))
		}).catch((error) => {
			dispatch(requestIssueFaild(error))
		})
	}
}
//FETCH ISSUE BY TAG
const fetchIssueByOwnTagID = ({ access_token, filter, repos, userID, repoID, tagID }) => {
	return dispatch => {
		dispatch(requestIssue());
		return fetchIssueByOwnTag(access_token, filter, repos, userID, repoID, tagID).then((issue) => {
			dispatch(receiveIssue(issue));
		}).catch((error) => {
			dispatch(requestIssueFaild(error))
		})
	}
}
//fetch issue or not
const shouldFetchIssue = (state) => {
	const issue = state.issue
	if (!issue) {
		return true
	}
	if (issue.isFetching) {
		return false
	}
	return issue.didInvalidate
}

//if needed,fetch issue
export const fetchIssueIfNeeded = (fetchBody, forceUpdate) => {
	return (dispatch, getState) => {
		if (forceUpdate) {
			if (fetchBody.tagID) {
				return dispatch(fetchIssueByOwnTagID(fetchBody))
			} else {
				return dispatch(fetchIssue(fetchBody))
			}

		} else if (shouldFetchIssue(getState())) {
			if (fetchBody.tagID) {
				return dispatch(fetchIssueByOwnTagID(fetchBody))
			} else {
				return dispatch(fetchIssue(fetchBody))
			}
		}
	}
}

// TAG
export const invaildTag = (value) => ({
	type: INVAILD_TAG,
	value
});

const requestTag = (value) => ({
	type: REQUEST_TAG,
	value
});

const requestTagFaild = (value) => ({
	type: REQUESTTAG_FAILD,
	value
});

const receiveTag = (value) => ({
	type: RECEIVE_TAG,
	value
});
const updateTagTable = (value) => ({
	type: UPDATE_TAGTABLE,
	value
});

export const updateTagState = (value) => ({
	type: UPDATE_TAGSTATE,
	value
});

const updateShowingIssuesTag = (value) => ({
	type: UPDATE_SHOWINGISSUESTAG,
	value
});

const shouldFetchTag = (state) => {
	let tag = state.tag;

	if (!tag) {
		return true
	}
	if (tag.isFetching) {
		return false
	}
	return tag.invaildtag;
}

export const fetchTag = ({ type, value }) => {//{ userID, repoID, tagID, name, color, selected }
	return (dispatch, getState) => {
		if (type === 'fetch') {
			if (shouldFetchTag(getState())) {
				dispatch(requestTag())
				return fetchTagAction({ type, value })
					.then((res) => res.json())
					.then((response) => {
						dispatch(receiveTag());
						dispatch(updateTagTable({ type, value: response }));
					});
			}
		} else {
			return fetchTagAction({ type, value }).then((response) => {
				if (response.ok) {
					dispatch(receiveTag());
					dispatch(updateTagTable({ type, value }));
					setTimeout(function () {
						dispatch(updateShowingIssuesTag({ type, value }));
					}.bind(this), 100);

				} else {
					dispatch(requestTagFaild(error))
				}

			}).catch((error) => {
				dispatch(requestTagFaild(error))
			})
		}
	}
}

export const handleTagTableClick = (e) => {
	return dispatch => {
		let vaildNode = null, value;
		let classNames = e.target.className;
		if (classNames.indexOf('tag-remove') > -1 || classNames.indexOf('glyphicon-remove') > -1) {
			vaildNode = classNames.indexOf('tag-remove') > -1 ? e.target : e.target.parentElement;
			vaildNode = vaildNode.parentElement.parentElement;
			value = JSON.parse(vaildNode.dataset.value);
			dispatch(fetchTag({ type: 'remove', value: value }));
		} else if (classNames.indexOf('tag-edit') > -1 || classNames.indexOf('glyphicon-pencil') > -1) {
			vaildNode = classNames.indexOf('tag-edit') > -1 ? e.target : e.target.parentElement;
			vaildNode = vaildNode.parentElement.parentElement;
			value = vaildNode.dataset.value;
			dispatch(fetchTag({ type: 'edit', value: value }));
		} else if (classNames.indexOf('tag-label') > -1 || classNames.indexOf('tag-label-span') > -1) {
			if (classNames.indexOf('tag-label-span') > -1) {
				vaildNode = e.target.parentElement.parentElement.parentElement;
			} else {
				vaildNode = e.target.parentElement.parentElement;
			}
			value = JSON.parse(vaildNode.dataset.value);
			dispatch(updateTagState(value.tagID));
		}
	}
}

//issue tag
const requestIssueTag = (value) => ({
	type: REQUEST_ISSUETAG,
	value
});

const requestIssueTagFaild = (value) => ({
	type: REQUEST_ISSUETAG_FAILD,
	value
});

const receiveIssueTag = (value) => ({
	type: RECEIVE_ISSUETAG,
	value
});

export const updateIssueTag = (value) => ({
	type: UPDATE_ISSUETAG,
	value
});

export const fetchUpdateIssueTagAction = ({ userID, repoID, number, tagIDs }) => {
	return dispatch => {
		dispatch(requestIssueTag());
		return fetchUpdateIssueTag(userID, repoID, number, tagIDs).then((res) => {
			dispatch(receiveIssueTag());
			return res;
		}).catch((error) => {
			dispatch(requestIssueTagFaild(error))
		})
	}
}
export const updatIssueNote = (value) => ({
	type: UPDATE_ISSUENOTE,
	value
});
export const fetchUpdateIssueNoteAction = ({ userID, repoID, number, note }) => {
	return dispatch => {
		return fetchUpdateIssueNote(userID, repoID, number, note).then((res) => {
			if (!res.ok) {
				alert('Update issue note for issue: ' + number + ' error!');
			}

		})
	}
}


text:
package com.postmen.javasdk.model;

import java.util.List;

import com.google.api.client.util.Key;

public class Label {
	@Key
	private String id;
	@Key
	private String status;
	@Key("created_at")
	private String createdAt;
	@Key("updated_at")
	private String updatedAt;
	@Key("tracking_numbers")
	private List<String> trackingNumbers;
	@Key
	private Files files;
	@Key
	private RateInfo rateInfo;

	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getStatus() {
		return status;
	}
	public void setStatus(String status) {
		this.status = status;
	}
	public List<String> getTrackingNumbers() {
		return trackingNumbers;
	}
	public void setTrackingNumbers(List<String> trackingNumbers) {
		this.trackingNumbers = trackingNumbers;
	}
	public Files getFiles() {
		return files;
	}
	public void setFiles(Files files) {
		this.files = files;
	}
	public RateInfo getRate() {
		return rateInfo;
	}
	public void setRate(RateInfo rateInfo) {
		this.rateInfo = rateInfo;
	}
	public String getCreatedAt() {
		return createdAt;
	}
	public void setCreatedAt(String createdAt) {
		this.createdAt = createdAt;
	}
	public String getUpdatedAt() {
		return updatedAt;
	}
	public void setUpdatedAt(String updatedAt) {
		this.updatedAt = updatedAt;
	}

}


text:
package com.sdw.soft.demo.archaius;

import com.google.common.io.Closeables;
import com.netflix.config.WatchedConfigurationSource;
import com.netflix.config.WatchedUpdateListener;
import com.netflix.config.WatchedUpdateResult;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent.Type;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.zookeeper.KeeperException.NoNodeException;
import org.apache.zookeeper.KeeperException.NodeExistsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Closeable;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Implementation of the dynamic {@link WatchedConfigurationSource} for ZooKeeper using Curator.
 *
 * This implementation requires the path to the ZK root parent node that contains
 * the hierarchy of configuration properties.
 * An example is /<my-app>/config
 *
 * Properties are direct ZK child nodes of the root parent ZK node.
 * An example ZK child property node is /<my-app>/config/com.fluxcapacitor.my.property
 *
 * The value is stored in the ZK child property node and can be updated at any time.
 * All servers will receive a ZK Watcher callback and automatically update their value
 * similar to other dynamic configuration sources (ie. DynamoDB, etc.)
 *
 * @author cfregly
 */
public class ZooKeeperConfigurationSource implements WatchedConfigurationSource, Closeable {
    private static final Logger logger = LoggerFactory.getLogger(ZooKeeperConfigurationSource.class);

    private final CuratorFramework client;
    private final String configRootPath;
    private final PathChildrenCache pathChildrenCache;

    private final Charset charset = Charset.forName("UTF-8");

    private List<WatchedUpdateListener> listeners = new CopyOnWriteArrayList<WatchedUpdateListener>();

    /**
     * Creates the pathChildrenCache using the CuratorFramework client and ZK root path node for the config
     *
     * @param Curator client
     * @param path to ZK root parent node for the rest of the configuration properties (ie. /<my-app>/config)
     */
    public ZooKeeperConfigurationSource(CuratorFramework client, String configRootPath) {
        this.client = client;
        this.configRootPath = configRootPath;
        this.pathChildrenCache = new PathChildrenCache(client, configRootPath, true);
    }

    /**
     * Adds a listener to the pathChildrenCache, initializes the cache, then starts the cache-management background thread
     *
     * @throws Exception
     */
    public void start() throws Exception {
        // create the watcher for future configuration updatess
        pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
            public void childEvent(CuratorFramework aClient, PathChildrenCacheEvent event)
                    throws Exception {
                Type eventType = event.getType();
                ChildData data = event.getData();

                String path = null;
                if (data != null) {
                    path = data.getPath();

                    // scrub configRootPath out of the key name
                    String key = removeRootPath(path);

                    byte[] value = data.getData();
                    String stringValue = new String(value, charset);

                    logger.debug("received update to pathName [{}], eventType [{}]", path, eventType);
                    logger.debug("key [{}], and value [{}]", key, stringValue);

                    // fire event to all listeners
                    Map<String, Object> added = null;
                    Map<String, Object> changed = null;
                    Map<String, Object> deleted = null;
                    if (eventType == Type.CHILD_ADDED) {
                        added = new HashMap<String, Object>(1);
                        added.put(key, stringValue);
                    } else if (eventType == Type.CHILD_UPDATED) {
                        changed = new HashMap<String, Object>(1);
                        changed.put(key, stringValue);
                    } else if (eventType == Type.CHILD_REMOVED) {
                        deleted = new HashMap<String, Object>(1);
                        deleted.put(key, stringValue);
                    }

                    WatchedUpdateResult result = WatchedUpdateResult.createIncremental(added,
                            changed, deleted);

                    fireEvent(result);
                }
            }
        });

        // passing true to trigger an initial rebuild upon starting.  (blocking call)
        pathChildrenCache.start(true);
    }

    @Override
    public Map<String, Object> getCurrentData() throws Exception {
        logger.debug("getCurrentData() retrieving current data.");

        List<ChildData> children = pathChildrenCache.getCurrentData();
        Map<String, Object> all = new HashMap<String, Object>(children.size());
        for (ChildData child : children) {
            String path = child.getPath();
            String key = removeRootPath(path);
            byte[] value = child.getData();

            all.put(key, new String(value, charset));
        }

        logger.debug("getCurrentData() retrieved [{}] config elements.", children.size());

        return all;
    }

    @Override
    public void addUpdateListener(WatchedUpdateListener l) {
        if (l != null) {
            listeners.add(l);
        }
    }

    @Override
    public void removeUpdateListener(WatchedUpdateListener l) {
        if (l != null) {
            listeners.remove(l);
        }
    }

    protected void fireEvent(WatchedUpdateResult result) {
        for (WatchedUpdateListener l : listeners) {
            try {
                l.updateConfiguration(result);
            } catch (Throwable ex) {
                logger.error("Error in invoking WatchedUpdateListener", ex);
            }
        }
    }

    /**
     * This is used to convert a configuration nodePath into a key
     *
     * @param nodePath
     *
     * @return key (nodePath less the config root path)
     */
    private String removeRootPath(String nodePath) {
        return nodePath.replace(configRootPath + "/", "");
    }

    //@VisibleForTesting
    synchronized void setZkProperty(String key, String value) throws Exception {
        final String path = configRootPath + "/" + key;

        byte[] data = value.getBytes(charset);

        try {
            // attempt to create (intentionally doing this instead of checkExists())
            client.create().creatingParentsIfNeeded().forPath(path, data);
        } catch (NodeExistsException exc) {
            // key already exists - update the data instead
            client.setData().forPath(path, data);
        }
    }

    //@VisibleForTesting
    synchronized String getZkProperty(String key) throws Exception {
        final String path = configRootPath + "/" + key;

        byte[] bytes = client.getData().forPath(path);

        return new String(bytes, charset);
    }

    //@VisibleForTesting
    synchronized void deleteZkProperty(String key) throws Exception {
        final String path = configRootPath + "/" + key;

        try {
            client.delete().forPath(path);
        } catch (NoNodeException exc) {
            // Node doesn't exist - NoOp
            logger.warn("Node doesn't exist", exc);
        }
    }

    public void close() {
        try {
            Closeables.close(pathChildrenCache, true);
        } catch (IOException exc) {
            logger.error("IOException should not have been thrown.", exc);
        }
    }
}


text:
#ifndef _ASSET_PTR_H_
#define _ASSET_PTR_H_

#ifndef _ASSET_MANAGER_H_
#include "assetManager.h"
#endif

//-----------------------------------------------------------------------------

class AssetPtrCallback
{
    friend class AssetManager;

protected:
    virtual void onAssetRefreshed( AssetPtrBase* pAssetPtrBase ) = 0;
};

//-----------------------------------------------------------------------------

class AssetPtrBase
{
public:
    AssetPtrBase() {};
    virtual ~AssetPtrBase()
    {
        // Un-register any notifications.
        unregisterRefreshNotify();
    };

    /// Referencing.
    virtual void clear( void ) = 0;
    virtual void setAssetId( const char* pAssetId ) = 0;
    virtual StringTableEntry getAssetId( void ) const = 0;
    virtual StringTableEntry getAssetType( void ) const = 0;
    virtual bool isAssetId( const char* pAssetId ) const = 0;

    /// Validity.
    virtual bool isNull( void ) const = 0;
    virtual bool notNull( void ) const = 0;

    /// Notification.
    inline void registerRefreshNotify( AssetPtrCallback* pCallback )
    {
        // Sanity!
        AssertFatal( AssetDatabase.isProperlyAdded(), "AssetPtrBase::registerRefreshNotify() - Cannot register an asset pointer with the asset system." );

        // register refresh notify.
        AssetDatabase.registerAssetPtrRefreshNotify( this, pCallback );
    }

    void unregisterRefreshNotify( void )
    {
        // Un-register the refresh notify if the asset system is available.
        if ( AssetDatabase.isProperlyAdded() )
            AssetDatabase.unregisterAssetPtrRefreshNotify( this );
    }
};

//-----------------------------------------------------------------------------

template<typename T> class AssetPtr : public AssetPtrBase
{
private:
    SimObjectPtr<T> mpAsset;

public:
    AssetPtr() {}
    AssetPtr( const char* pAssetId )
    {
        // Finish if this is an invalid asset Id.
        if ( pAssetId == NULL || *pAssetId == 0 )
            return;

        // Acquire asset.
        mpAsset = AssetDatabase.acquireAsset<T>( pAssetId );
    }
    AssetPtr( const AssetPtr<T>& assetPtr )
    {
        // Does the asset pointer have an asset?
        if ( assetPtr.notNull() )
        {
            // Yes, so acquire the asset.
            mpAsset = AssetDatabase.acquireAsset<T>( assetPtr->getAssetId() );
        }
    }
    virtual ~AssetPtr()
    {
        // Do we have an asset?
        if ( notNull() )
        {
            // Yes, so release it.
            AssetDatabase.releaseAsset( mpAsset->getAssetId() );
        }
    }

    /// Assignment.
    AssetPtr<T>& operator=( const char* pAssetId )
    {
        // Do we have an asset?
        if ( notNull() )
        {
            // Yes, so finish if the asset Id is already assigned.
            if ( isAssetId( pAssetId ) )
                return *this;

            // No, so release it.
            AssetDatabase.releaseAsset( mpAsset->getAssetId() );
        }

        // Is the asset Id at least okay to attempt to acquire the asset?
        if ( pAssetId != NULL && *pAssetId != 0 )
        {
            // Yes, so acquire the asset.
            mpAsset = AssetDatabase.acquireAsset<T>( pAssetId );
        }
        else
        {
            // No, so remove reference.
            mpAsset = NULL;
        }

        // Return Reference.
        return *this;
    }

    AssetPtr<T>& operator=( const AssetPtr<T>& assetPtr )
    {
        // Set asset pointer.
        *this = assetPtr->getAssetId();

        // Return Reference.
        return *this;
    }

    /// Referencing.
    virtual void clear( void )
    {
        // Do we have an asset?
        if ( notNull() )
        {
            // Yes, so release it.
            AssetDatabase.releaseAsset( mpAsset->getAssetId() );
        }

        // Reset the asset reference.
        mpAsset = NULL;
    }

    T* operator->( void ) const { return mpAsset; }
    T& operator*( void ) const { return *mpAsset; }
    operator T*( void ) const { return mpAsset; }
    virtual void setAssetId( const char* pAssetId ) { *this = pAssetId; }
    virtual StringTableEntry getAssetId( void ) const { return isNull() ? StringTable->EmptyString : mpAsset->getAssetId(); }
    virtual StringTableEntry getAssetType( void ) const { return isNull() ? StringTable->EmptyString : mpAsset->getClassName(); }
    virtual bool isAssetId( const char* pAssetId ) const { return pAssetId == NULL ? isNull() : getAssetId() == StringTable->insert(pAssetId); }

    /// Validity.
    virtual bool isNull( void ) const { return mpAsset.isNull(); }
    virtual bool notNull( void ) const { return !mpAsset.isNull(); }
};

#endif // _ASSET_PTR_H_