text:
package org.apache.jackrabbit.core.persistence.pool;

import org.apache.jackrabbit.core.persistence.PMContext;
import org.apache.jackrabbit.core.util.db.ConnectionHelper;
import org.apache.jackrabbit.core.util.db.DerbyConnectionHelper;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

/**
 * Extends the {@link BundleDbPersistenceManager} by derby specific code.
 *

 * Configuration:

 *

 *
<param name="{@link #setBundleCacheSize(String) bundleCacheSize}" value="8"/>
 *
<param name="{@link #setConsistencyCheck(String) consistencyCheck}" value="false"/>
 *
<param name="{@link #setMinBlobSize(String) minBlobSize}" value="16384"/>
 *
<param name="{@link #setDriver(String) driver}" value="org.apache.derby.jdbc.EmbeddedDriver"/>
 *
<param name="{@link #setUrl(String) url}" value="jdbc:derby:${wsp.home}/db/itemState;create=true"/>
 *
<param name="{@link #setUser(String) user}" value=""/>
 *
<param name="{@link #setPassword(String) password}" value=""/>
 *
<param name="{@link #setSchema(String) schema}" value="derby"/>
 *
<param name="{@link #setSchemaObjectPrefix(String) schemaObjectPrefix}" value=""/>
 *
<param name="{@link #setErrorHandling(String) errorHandling}" value=""/>
 *
 *
<param name="{@link #setDerbyStorageInitialPages(String) derbyStorageInitialPages}" value="16"/>
 *
<param name="{@link #setDerbyStorageMinimumRecordSize(String) derbyStorageMinimumRecordSize}" value="256"/>
 *
<param name="{@link #setDerbyStoragePageCacheSize(String) derbyStoragePageCacheSize}" value="1024"/>
 *
<param name="{@link #setDerbyStoragePageReservedSpace(String) derbyStoragePageReservedSpace}" value="20"/>
 *
<param name="{@link #setDerbyStoragePageSize(String) derbyStoragePageSize}" value="16384"/>
 *

 */
public class DerbyPersistenceManager extends BundleDbPersistenceManager {

    /** name of the embedded driver */
    public static final String DERBY_EMBEDDED_DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";

    /** @see #setDerbyStorageInitialPages(String) */
    private int derbyStorageInitialPages = 16;

    /** @see #setDerbyStorageMinimumRecordSize(String) */
    private int derbyStorageMinimumRecordSize = 512;

    /** @see #setDerbyStoragePageCacheSize(String) */
    private int derbyStoragePageCacheSize = 1024;

    /** @see #setDerbyStoragePageReservedSpace(String) */
    private int derbyStoragePageReservedSpace = 20;

    /** @see #setDerbyStoragePageSize(String) */
    private int derbyStoragePageSize = 16384;

    /**
     * @see #setDerbyStorageInitialPages
     * @return the initial pages property
     */
    public String getDerbyStorageInitialPages() {
        return String.valueOf(derbyStorageInitialPages);
    }

    /**
     * The on-disk size of a Derby table grows by one page at a time until eight
     * pages of user data (or nine pages of total disk use, one is used for
     * overhead) have been allocated. Then it will grow by eight pages at a time
     * if possible.
     *

     * A Derby table or index can be created with a number of pages already
     * pre-allocated. To do so, specify the property prior to the CREATE TABLE
     * or CREATE INDEX statement.
     *

     * Define the number of user pages the table or index is to be created with.
     * The purpose of this property is to preallocate a table or index of
     * reasonable size if the user expects that a large amount of data will be
     * inserted into the table or index. A table or index that has the
     * pre-allocated pages will enjoy a small performance improvement over a
     * table or index that has no pre-allocated pages when the data are loaded.
     *

     * The total desired size of the table or index should be
     *

     * (1+derby.storage.initialPages) * derby.storage.pageSize bytes.
     *

     * When you create a table or an index after setting this property, Derby
     * attempts to preallocate the requested number of user pages. However, the
     * operations do not fail even if they are unable to preallocate the
     * requested number of pages, as long as they allocate at least one page.
     *

     * Default is 16
     *
     * @param derbyStorageInitialPages the number of initial pages
     */
    public void setDerbyStorageInitialPages(String derbyStorageInitialPages) {
        this.derbyStorageInitialPages =
                Integer.decode(derbyStorageInitialPages).intValue();
    }

    /**
     * @see #setDerbyStorageMinimumRecordSize
     * @return the minimum record size
     */
    public String getDerbyStorageMinimumRecordSize() {
        return String.valueOf(derbyStorageMinimumRecordSize);
    }

    /**
     * Indicates the minimum user row size in bytes for on-disk database pages
     * for tables when you are creating a table. This property ensures that
     * there is enough room for a row to grow on a page when updated without
     * having to overflow. This is generally most useful for VARCHAR and
     * VARCHAR FOR BIT DATA data types and for tables that are updated a lot,
     * in which the rows start small and grow due to updates. Reserving the
     * space at the time of insertion minimizes row overflow due to updates,
     * but it can result in wasted space. Set the property prior to issuing the
     * CREATE TABLE statement.
     *

     * Default is 256
     *
     * @param derbyStorageMinimumRecordSize the minimum record size
     */
    public void setDerbyStorageMinimumRecordSize(String derbyStorageMinimumRecordSize) {
        this.derbyStorageMinimumRecordSize =
                Integer.decode(derbyStorageMinimumRecordSize).intValue();
    }

    /**
     * @see #setDerbyStoragePageCacheSize
     * @return the page cache size
     */
    public String getDerbyStoragePageCacheSize() {
        return String.valueOf(derbyStoragePageCacheSize);
    }

    /**
     * Defines the size, in number of pages, of the database's data page cache
     * (data pages kept in memory). The actual amount of memory the page cache
     * will use depends on the following:
     *

     *
 the size of the cache (configured with {@link #setDerbyStoragePageCacheSize})
     *
 the size of the pages (configured with {@link #setDerbyStoragePageSize})
     *
 overhead (varies with JVMs)
     *

     * When increasing the size of the page cache, you typically have to allow
     * more memory for the Java heap when starting the embedding application
     * (taking into consideration, of course, the memory needs of the embedding
     * application as well). For example, using the default page size of 4K, a
     * page cache size of 2000 pages will require at least 8 MB of memory (and
     * probably more, given the overhead).
     *

     * The minimum value is 40 pages. If you specify a lower value, Derby uses
     * the default value.
     *

     * Default is 1024 (which gives about 16mb memory usage given
     * the default of 16384 as page size).
     *
     * @param derbyStoragePageCacheSize the page cache size
     */
    public void setDerbyStoragePageCacheSize(String derbyStoragePageCacheSize) {
        this.derbyStoragePageCacheSize =
                Integer.decode(derbyStoragePageCacheSize).intValue();
    }

    /**
     * @see #setDerbyStoragePageReservedSpace
     * @return the page reserved space
     */
    public String getDerbyStoragePageReservedSpace() {
        return String.valueOf(derbyStoragePageReservedSpace);
    }

    /**
     * Defines the percentage of space reserved for updates on an on-disk
     * database page for tables only (not indexes); indicates the percentage of
     * space to keep free on a page when inserting. Leaving reserved space on a
     * page can minimize row overflow (and the associated performance hit)
     * during updates. Once a page has been filled up to the reserved-space
     * threshold, no new rows are allowed on the page. This reserved space is
     * used only for rows that increase in size when updated, not for new
     * inserts. Set this property prior to issuing the CREATE TABLE statement.
     *

     * Regardless of the value of derby.storage.pageReservedSpace, an empty page
     * always accepts at least one row.
     *

     * Default is 20%
     *
     * @param derbyStoragePageReservedSpace the page reserved space
     */
    public void setDerbyStoragePageReservedSpace(String derbyStoragePageReservedSpace) {
        this.derbyStoragePageReservedSpace =
                Integer.decode(derbyStoragePageReservedSpace).intValue();
    }

    /**
     * @see #setDerbyStoragePageSize
     * @return the page size
     */
    public String getDerbyStoragePageSize() {
        return String.valueOf(derbyStoragePageSize);
    }

    /**
     * Defines the page size, in bytes, for on-disk database pages for tables or
     * indexes used during table or index creation. Page size can only be one
     * the following values: 4096, 8192, 16384, or 32768. Set this property
     * prior to issuing the CREATE TABLE or CREATE INDEX statement. This value
     * will be used for the lifetime of the newly created conglomerates.
     *

     * Default is 16384
     *
     * @param derbyStoragePageSize the storage page size
     */
    public void setDerbyStoragePageSize(String derbyStoragePageSize) {
        this.derbyStoragePageSize = Integer.decode(derbyStoragePageSize).intValue();
    }

    /**
     * {@inheritDoc}
     */
    public void init(PMContext context) throws Exception {
        // init default values
        if (getDriver() == null) {
            setDriver(DERBY_EMBEDDED_DRIVER);
        }
        if (getDatabaseType() == null) {
            setDatabaseType("derby");
        }
        if (getUrl() == null) {
            setUrl("jdbc:derby:" + context.getHomeDir().getPath() + "/db/itemState;create=true");
        }
        if (getSchemaObjectPrefix() == null) {
            setSchemaObjectPrefix("");
        }
        super.init(context);
        // set properties
        if (DERBY_EMBEDDED_DRIVER.equals(getDriver())) {
            conHelper.exec("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY "
                    + "('derby.storage.initialPages', '" + derbyStorageInitialPages + "')");
            conHelper.exec("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY "
                    + "('derby.storage.minimumRecordSize', '" + derbyStorageMinimumRecordSize + "')");
            conHelper.exec("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY "
                    + "('derby.storage.pageCacheSize', '" + derbyStoragePageCacheSize + "')");
            conHelper.exec("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY "
                    + "('derby.storage.pageReservedSpace', '" + derbyStoragePageReservedSpace + "')");
            conHelper.exec("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY " + "('derby.storage.pageSize', '"
                    + derbyStoragePageSize + "')");
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected ConnectionHelper createConnectionHelper(DataSource dataSrc) {
        return new DerbyConnectionHelper(dataSrc, blockOnConnectionLoss);
    }

    /**
     * {@inheritDoc}
     *
     * Since Derby cannot handle binary indexes, we use long-long keys.
     *
     * @return {@link BundleDbPersistenceManager#SM_LONGLONG_KEYS}
     */
    public int getStorageModel() {
        return BundleDbPersistenceManager.SM_LONGLONG_KEYS;
    }

    /**
     * Closes the given connection by shutting down the embedded Derby
     * database.
     *
     * @throws SQLException if an error occurs
     * @see DatabasePersistenceManager#closeConnection(Connection)
     */
    public void close() throws Exception {
        super.close();
        ((DerbyConnectionHelper) conHelper).shutDown(getDriver());
    }

}

redpajama_set_name: RedPajamaGithub


text:
<template name="List_Semesters_Widget">

SEMESTERS ({{ count }})

      {{> Admin_Datamodel_Pagination_Widget showItemCount=getItemCount showIndex=getItemIndex collection=getCollection }}
      {{#each semester in semesters}}
        {{> Admin_DataModel_Accordion name=(name semester) descriptionPairs=(descriptionPairs semester) id=semester._id updateID=updateID deleteDisabled=(deleteDisabled semester) retired=(retired semester)}}
      {{/each}}

</template>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

// this is useful in so many places that I'm putting it in the root namespace
static class JoinStringExtensions
{
    //
    // Summary:
    //     Concatenates the members of a constructed System.Collections.Generic.IEnumerable<T>
    //     collection of type System.String, using the specified separator between each
    //     member.
    //
    // Parameters:
    //   separator:
    //     The string to use as a separator.
    //
    //   values:
    //     A collection that contains the strings to concatenate.
    //
    // Returns:
    //     A string that consists of the members of values delimited by the separator
    //     string.
    //
    // Exceptions:
    //   System.ArgumentNullException:
    //     values is null.
    public static string JoinString(this IEnumerable<string> @this, string separator) { return string.Join(separator, @this); }

    //
    // Summary:
    //     Concatenates the members of a string collection, using the specified separator
    //     between each member.
    //
    // Parameters:
    //   separator:
    //     The string to use as a separator.
    //
    //   values:
    //     A collection that contains the objects to concatenate.
    //
    // Type parameters:
    //   T:
    //     The type of the members of values.
    //
    // Returns:
    //     A string that consists of the members of values delimited by the separator
    //     string.
    //
    // Exceptions:
    //   System.ArgumentNullException:
    //     values is null.
    public static string JoinString<T>(this IEnumerable<T> @this, string separator) { return string.Join(separator, @this); }

    //
    // Summary:
    //     Concatenates the elements of an object array, using the specified separator
    //     between each element.
    //
    // Parameters:
    //   separator:
    //     The string to use as a separator.
    //
    //   values:
    //     An array that contains the elements to concatenate.
    //
    // Returns:
    //     A string that consists of the elements of values delimited by the separator
    //     string.
    //
    // Exceptions:
    //   System.ArgumentNullException:
    //     values is null.
    public static string JoinString(this object[] @this, string separator) { return string.Join(separator, @this); }

    //
    // Summary:
    //     Concatenates all the elements of a string array, using the specified separator
    //     between each element.
    //
    // Parameters:
    //   separator:
    //     The string to use as a separator.
    //
    //   value:
    //     An array that contains the elements to concatenate.
    //
    // Returns:
    //     A string that consists of the elements in value delimited by the separator
    //     string.
    //
    // Exceptions:
    //   System.ArgumentNullException:
    //     value is null.
    public static string JoinString(this string[] @this, string separator) { return string.Join(separator, @this); }
}


text:
package org.hibernate.examples.mapping.compositeId.manytoone;

import lombok.Getter;
import org.hibernate.examples.model.AbstractValueObject;
import org.hibernate.examples.utils.HashTool;
import org.hibernate.examples.utils.ToStringHelper;

import javax.persistence.Embeddable;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

/**
 * org.hibernate.examples.mapping.compositeId.manytoone.OrderDetailIdentifier
 *
 * @author 배성혁 sunghyouk.bae@gmail.com
 * @since 2013. 11. 29. 오후 5:06
 */
@Embeddable
@Getter
public class OrderDetailIdentifier extends AbstractValueObject {

    protected OrderDetailIdentifier() {}

    public OrderDetailIdentifier(Order order, Product product) {
        assert (order != null);
        assert (product != null);

        this.order = order;
        this.product = product;
    }

    @ManyToOne
    @JoinColumn(name = "orderId")
    private Order order;

    @ManyToOne
    @JoinColumn(name = "productId")
    private Product product;

    @Override
    public int hashCode() {
        return HashTool.compute(order, product);
    }

    @Override
    public ToStringHelper buildStringHelper() {
        return super.buildStringHelper()
                    .add("orderId", order.getId())
                    .add("productId", product.getId());
    }

    private static final long serialVersionUID = -7914201856753998776L;
}


text:
import Graph from "../src/graph";
import {
    Edge,
    EdgePoint,
    Location,
    Path,
    SimpleEdge,
    SimpleNode,
} from "../src/types";
import * as TestGraphs from "./testGraphs";

describe("constructor", () => {
    it("should fail if node ID is repeated", () => {
        const nodes: SimpleNode[] = [
            { id: 0, location: { x: 0, y: 0 } },
            { id: 0, location: { x: 0, y: 1 } },
        ];
        expect(() => Graph.create(nodes, [])).toThrowError(/0/);
    });

    it("should fail if edge ID is repeated", () => {
        const nodes: SimpleNode[] = [
            { id: 0, location: { x: 0, y: 0 } },
            { id: 1, location: { x: 0, y: 1 } },
            { id: 2, location: { x: 1, y: 0 } },
        ];
        const edges: SimpleEdge[] = [
            { id: 0, startNodeId: 0, endNodeId: 1 },
            { id: 0, startNodeId: 1, endNodeId: 2 },
        ];
        expect(() => Graph.create(nodes, edges)).toThrowError(/0/);
    });

    it("should fail if edge references nonexistent node", () => {
        const nodes: SimpleNode[] = [
            { id: 0, location: { x: 0, y: 0 } },
            { id: 1, location: { x: 0, y: 1 } },
        ];
        const edges: SimpleEdge[] = [{ id: 0, startNodeId: 0, endNodeId: 2 }];
        expect(() => Graph.create(nodes, edges)).toThrowError(/2/);
    });
});

describe("getAllNodes()", () => {
    it("should return nothing on an empty graph", () => {
        const graph = Graph.create([], []);
        expect(graph.getAllNodes()).toEqual([]);
    });

    it("should return a node with no edges if it is entire graph", () => {
        const node = TestGraphs.getSingleNode().getAllNodes()[0];
        expect(node.id).toEqual(0);
        expect(node.location).toEqual({ x: 0, y: 0 });
        expect(node.edgeIds).toEqual([]);
    });

    it("should return nodes with edge between them on such a graph", () => {
        const nodes = TestGraphs.getTwoNodes().getAllNodes();
        expect(nodes.length).toEqual(2);
        const [nodeA, nodeB] = nodes;
        expect(nodeA.id).toEqual("A");
        expect(nodeB.id).toEqual("B");
        expect(nodeA.edgeIds).toEqual(["AB"]);
        expect(nodeB.edgeIds).toEqual(["AB"]);
    });
});

describe("getNode()", () => {
    it("should return the requested node", () => {
        const node = TestGraphs.getSingleNode().getNode(0);
        expect(node.id).toEqual(0);
    });

    it("should return undefined if node does not exist", () => {
        expect(TestGraphs.getSingleNode().getNode(1)).toBeUndefined();
    });
});

describe("getAllEdges()", () => {
    it("should return nothing on an empty graph", () => {
        const graph = Graph.create([], []);
        expect(graph.getAllEdges()).toEqual([]);
    });

    it("should return the edge on a graph with a single edge", () => {
        const edges = TestGraphs.getTwoNodes().getAllEdges();
        const expected: Edge[] = [
            {
                id: "AB",
                startNodeId: "A",
                endNodeId: "B",
                innerLocations: [],
                length: 1,
                locations: [{ x: 0, y: 0 }, { x: 1, y: 0 }],
                locationDistances: [0, 1],
            },
        ];
        expect(edges).toEqual(expected);
    });
});

describe("getEdge()", () => {
    it("should return the requested edge", () => {
        const edge = TestGraphs.getTwoNodes().getEdge("AB");
        expect(edge.id).toEqual("AB");
    });

    it("should return undefined if edge does not exist", () => {
        expect(TestGraphs.getTwoNodes().getEdge(1)).toBeUndefined();
    });
});

describe("getEdgesOfNode()", () => {
    it("should return edges with node as their endpoint", () => {
        const edges = TestGraphs.getTriangle().getEdgesOfNode("A");
        const edgeIds = edges.map(edge => edge.id).sort();
        expect(edgeIds).toEqual(["AB", "CA"]);
    });

    it("should throw on nonexistent node ID", () => {
        expect(() => TestGraphs.getTriangle().getEdgesOfNode(-1)).toThrowError(
            /-1/,
        );
    });
});

describe("getEndpointsOfEdge()", () => {
    it("should return nodes at ends of edge", () => {
        const endpoints = TestGraphs.getTriangle().getEndpointsOfEdge("CA");
        expect(endpoints.map(node => node.id)).toEqual(["C", "A"]);
    });

    it("should throw on nonexistent edge ID", () => {
        expect(() =>
            TestGraphs.getTriangle().getEndpointsOfEdge(-1),
        ).toThrowError(/-1/);
    });
});

describe("getOtherEndpoint()", () => {
    it("should return the other endpoint of an edge", () => {
        const endpoint = TestGraphs.getTwoNodes().getOtherEndpoint("AB", "A");
        expect(endpoint.id).toEqual("B");
    });

    it("should throw on nonexistent edge ID", () => {
        expect(() =>
            TestGraphs.getTwoNodes().getOtherEndpoint("TD", "A"),
        ).toThrowError(/TD/);
    });

    it("should throw if node is not an endpoint of edge", () => {
        expect(() =>
            TestGraphs.getTriangle().getOtherEndpoint("AB", "C"),
        ).toThrowError(/endpoint/);
    });
});

describe("getNeighbors()", () => {
    it("should return the neighbors of a node", () => {
        const neighbors = TestGraphs.getTriangle().getNeighbors("A");
        expect(neighbors.map(node => node.id).sort()).toEqual(["B", "C"]);
    });

    it("should throw nonexistent node ID", () => {
        expect(() => TestGraphs.getTriangle().getNeighbors("TD")).toThrowError(
            /TD/,
        );
    });
});

describe("getLocation()", () => {
    it("should return the correct location on an edge with no inner points", () => {
        const nodes: SimpleNode[] = [
            { id: "A", location: { x: 10, y: 10 } },
            { id: "B", location: { x: 40, y: 50 } },
        ];
        const edges: SimpleEdge[] = [
            { id: "AB", startNodeId: "A", endNodeId: "B" },
        ];
        const graph = Graph.create(nodes, edges);
        const distances = [0, 10, 50];
        const expectedLocations: Location[] = [
            { x: 10, y: 10 },
            { x: 16, y: 18 },
            { x: 40, y: 50 },
        ];
        const actualLocations = distances.map(distance =>
            graph.getLocation({ edgeId: "AB", distance }),
        );
        expect(actualLocations).toEqual(expectedLocations);
    });

    it("should return the correct location on an edge with inner points", () => {
        // Path is a "stairwell" with two steps.
        const nodes: SimpleNode[] = [
            { id: "A", location: { x: 0, y: 0 } },
            { id: "B", location: { x: 2, y: 2 } },
        ];
        const edges: SimpleEdge[] = [
            {
                id: "AB",
                startNodeId: "A",
                endNodeId: "B",
                innerLocations: [
                    { x: 1, y: 0 },
                    { x: 1, y: 1 },
                    { x: 2, y: 1 },
                ],
            },
        ];
        const graph = Graph.create(nodes, edges);
        const distances = [0, 1, 2.5, 4];
        const expectedLocations: Location[] = [
            { x: 0, y: 0 },
            { x: 1, y: 0 },
            { x: 1.5, y: 1 },
            { x: 2, y: 2 },
        ];
        const actualLocations = distances.map(distance =>
            graph.getLocation({ edgeId: "AB", distance }),
        );
        expect(actualLocations).toEqual(expectedLocations);
    });

    it("should behave in double imprecision corner case", () => {
        // Fact: 2/3 + 1/3 === 1, but 1 - 2/3 - 1/3 !== 0 in floating point arithmatic.
        // This test checks that this does not cause trouble for us.
        const nodes: SimpleNode[] = [
            { id: "A", location: { x: 0, y: 0 } },
            { id: "B", location: { x: 2 / 3, y: 1 / 3 } },
        ];
        const edges: SimpleEdge[] = [
            {
                id: "AB",
                startNodeId: "A",
                endNodeId: "B",
                innerLocations: [{ x: 2 / 3, y: 0 }],
            },
        ];
        const graph = Graph.create(nodes, edges);
        const { length } = graph.getEdge("AB");
        expect(graph.getLocation({ edgeId: "AB", distance: length })).toEqual({
            x: 2 / 3,
            y: 1 / 3,
        });
    });

    it("should throw on nonexistent edgeId", () => {
        expect(() =>
            TestGraphs.getTriangle().getLocation({ edgeId: "TD", distance: 0 }),
        ).toThrowError(/TD/);
    });

    it("should return start on negative distance", () => {
        expect(
            TestGraphs.getTriangle().getLocation({
                edgeId: "AB",
                distance: -1,
            }),
        ).toEqual({ x: 0, y: 0 });
    });

    it("should return end on distance greater than edge length", () => {
        expect(
            TestGraphs.getTriangle().getLocation({
                edgeId: "AB",
                distance: 10,
            }),
        ).toEqual({ x: 1, y: 0 });
    });
});

describe("lengths and innerLocationDistances", () => {
    it("should be correct for edge with no inner locations", () => {
        const nodes: SimpleNode[] = [
            { id: "A", location: { x: 1, y: 1 } },
            { id: "B", location: { x: 4, y: -3 } },
        ];
        const edges: SimpleEdge[] = [
            { id: "AB", startNodeId: "A", endNodeId: "B" },
        ];
        const edge = Graph.create(nodes, edges).getEdge("AB");
        const expected: Edge = {
            id: "AB",
            startNodeId: "A",
            endNodeId: "B",
            innerLocations: [],
            length: 5,
            locations: [{ x: 1, y: 1 }, { x: 4, y: -3 }],
            locationDistances: [0, 5],
        };
        expect(edge).toEqual(expected);
    });

    it("should be correct for edge with inner locations", () => {
        const nodes: SimpleNode[] = [
            { id: "A", location: { x: 0, y: 0 } },
            { id: "B", location: { x: 0, y: 6 } },
        ];
        const edges: SimpleEdge[] = [
            {
                id: "AB",
                startNodeId: "A",
                endNodeId: "B",
                innerLocations: [{ x: 4, y: 3 }],
            },
        ];
        const edge = Graph.create(nodes, edges).getEdge("AB");
        const expected: Edge = {
            id: "AB",
            startNodeId: "A",
            endNodeId: "B",
            innerLocations: [{ x: 4, y: 3 }],
            length: 10,
            locations: [{ x: 0, y: 0 }, { x: 4, y: 3 }, { x: 0, y: 6 }],
            locationDistances: [0, 5, 10],
        };
        expect(edge).toEqual(expected);
    });
});

describe("coalesced()", () => {
    it("should return identical graph if nothing to coalesce", () => {
        const graph = TestGraphs.getTwoNodes();
        const coalesced = graph.coalesced();
        expectGraphsToBeEqual(coalesced, graph);
    });

    it("should coalesce segmented curve into single curve", () => {
        const graph = TestGraphs.getFourNodes().coalesced();
        const expectedNodes: SimpleNode[] = [
            { id: "A", location: { x: 0, y: 0 } },
            { id: "D", location: { x: 3, y: 0 } },
        ];
        const expectedEdges: SimpleEdge[] = [
            {
                id: "AB",
                startNodeId: "A",
                endNodeId: "D",
                innerLocations: [{ x: 1, y: 0 }, { x: 2, y: 0 }],
            },
        ];
        const expectedGraph = Graph.create(expectedNodes, expectedEdges);
        expectGraphsToBeEqual(graph, expectedGraph);
    });

    it("should coalesce segmented arms of three-armed star", () => {
        const nodes: SimpleNode[] = [
            { id: "center", location: { x: 0, y: 0 } },
            { id: "rightArmJoint", location: { x: 1, y: 0 } },
            { id: "rightArmEnd", location: { x: 2, y: 0 } },
            { id: "topArmJoint", location: { x: 0, y: 1 } },
            { id: "topArmEnd", location: { x: 0, y: 2 } },
            { id: "leftArmJoint", location: { x: -1, y: 0 } },
            { id: "leftArmEnd", location: { x: -2, y: 0 } },
        ];
        const edges: SimpleEdge[] = [
            {
                id: "rightArm1",
                startNodeId: "center",
                endNodeId: "rightArmJoint",
            },
            {
                id: "rightArm2",
                startNodeId: "rightArmJoint",
                endNodeId: "rightArmEnd",
            },
            { id: "topArm1", startNodeId: "center", endNodeId: "topArmJoint" },
            {
                id: "topArm2",
                startNodeId: "topArmJoint",
                endNodeId: "topArmEnd",
            },
            {
                id: "leftArm1",
                startNodeId: "center",
                endNodeId: "leftArmJoint",
            },
            {
                id: "leftArm2",
                startNodeId: "leftArmJoint",
                endNodeId: "leftArmEnd",
            },
        ];
        const expectedNodes: SimpleNode[] = [
            { id: "center", location: { x: 0, y: 0 } },
            { id: "rightArmEnd", location: { x: 2, y: 0 } },
            { id: "topArmEnd", location: { x: 0, y: 2 } },
            { id: "leftArmEnd", location: { x: -2, y: 0 } },
        ];
        const expectedEdges: SimpleEdge[] = [
            {
                id: "rightArm1",
                startNodeId: "center",
                endNodeId: "rightArmEnd",
                innerLocations: [{ x: 1, y: 0 }],
            },
            {
                id: "topArm1",
                startNodeId: "center",
                endNodeId: "topArmEnd",
                innerLocations: [{ x: 0, y: 1 }],
            },
            {
                id: "leftArm1",
                startNodeId: "center",
                endNodeId: "leftArmEnd",
                innerLocations: [{ x: -1, y: 0 }],
            },
        ];
        const graph = Graph.create(nodes, edges).coalesced();
        const expectedGraph = Graph.create(expectedNodes, expectedEdges);
        expectGraphsToBeEqual(graph, expectedGraph);
    });

    it("should preserve inner locations in correct order", () => {
        const nodes: SimpleNode[] = [
            { id: "A", location: { x: 0, y: 0 } },
            { id: "B", location: { x: 3, y: 0 } },
            { id: "C", location: { x: 3, y: 3 } },
        ];
        const edges: SimpleEdge[] = [
            {
                id: "AB",
                startNodeId: "A",
                endNodeId: "B",
                innerLocations: [{ x: 1, y: 0 }, { x: 2, y: 0 }],
            },
            {
                id: "CB",
                startNodeId: "C",
                endNodeId: "B",
                innerLocations: [{ x: 3, y: 2 }, { x: 3, y: 1 }],
            },
        ];
        const expectedNodes: SimpleNode[] = [
            { id: "A", location: { x: 0, y: 0 } },
            { id: "C", location: { x: 3, y: 3 } },
        ];
        const expectedEdges: SimpleEdge[] = [
            {
                id: "AB",
                startNodeId: "A",
                endNodeId: "C",
                innerLocations: [
                    { x: 1, y: 0 },
                    { x: 2, y: 0 },
                    { x: 3, y: 0 },
                    { x: 3, y: 1 },
                    { x: 3, y: 2 },
                ],
            },
        ];
        const graph = Graph.create(nodes, edges).coalesced();
        const expectedGraph = Graph.create(expectedNodes, expectedEdges);
        expectGraphsToBeEqual(graph, expectedGraph);
    });

    it("should handle an isolated cycle", () => {
        const expectedNodes: SimpleNode[] = [
            { id: "A", location: { x: 0, y: 0 } },
        ];
        const expectedEdges: SimpleEdge[] = [
            {
                id: "AB",
                startNodeId: "A",
                endNodeId: "A",
                innerLocations: [{ x: 1, y: 0 }, { x: 0, y: 1 }],
            },
        ];
        const graph = TestGraphs.getTriangle().coalesced();
        const expectedGraph = Graph.create(expectedNodes, expectedEdges);
        expectGraphsToBeEqual(graph, expectedGraph);
    });
});

describe("getConnectedComponents()", () => {
    it("should return the original graph if connected", () => {
        const graph = TestGraphs.getTwoNodes();
        const components = graph.getConnectedComponents();
        expect(components.length).toEqual(1);
        expectGraphsToBeEqual(components[0], graph);
    });

    it("should return multiple components if not connected", () => {
        const nodeA = { id: "A", location: { x: 0, y: 0 } };
        const nodeB = { id: "B", location: { x: 1, y: 0 } };
        const nodeO = { id: "O", location: { x: 0, y: 1 } };
        const nodeX = { id: "X", location: { x: 2, y: 0 } };
        const nodeY = { id: "Y", location: { x: 2, y: 1 } };

        const edgeAB = { id: "AB", startNodeId: "A", endNodeId: "B" };
        const edgeXY = { id: "XY", startNodeId: "X", endNodeId: "Y" };

        const nodes: SimpleNode[] = [nodeA, nodeB, nodeO, nodeX, nodeY];
        const edges: SimpleEdge[] = [edgeAB, edgeXY];
        const expectedNodes: SimpleNode[][] = [
            [nodeA, nodeB],
            [nodeO],
            [nodeX, nodeY],
        ];
        const expectedEdges: SimpleEdge[][] = [[edgeAB], [], [edgeXY]];
        const components = Graph.create(nodes, edges).getConnectedComponents();
        expect(components.length).toEqual(3);
        for (let i = 0; i < 3; i++) {
            const expectedComponent = Graph.create(
                expectedNodes[i],
                expectedEdges[i],
            );
            expectGraphsToBeEqual(components[i], expectedComponent);
        }
    });

    it("should work if cycles are present", () => {
        const graph = TestGraphs.getTriangle();
        const components = graph.getConnectedComponents();
        expect(components.length).toEqual(1);
        expectGraphsToBeEqual(components[0], graph);
    });
});

describe("getConnectedComponentsForNode()", () => {
    it("should return the original graph if connected", () => {
        const graph = TestGraphs.getTwoNodes();
        const component = graph.getConnectedComponentOfNode("A");
        expectGraphsToBeEqual(component, graph);
    });

    it("should return a single componenet if disconnected", () => {
        const nodeA = { id: "A", location: { x: 0, y: 0 } };
        const nodeB = { id: "B", location: { x: 1, y: 0 } };
        const nodeO = { id: "O", location: { x: 0, y: 1 } };
        const nodeX = { id: "X", location: { x: 2, y: 0 } };
        const nodeY = { id: "Y", location: { x: 2, y: 1 } };

        const edgeAB = { id: "AB", startNodeId: "A", endNodeId: "B" };
        const edgeXY = { id: "XY", startNodeId: "X", endNodeId: "Y" };

        const nodes: SimpleNode[] = [nodeA, nodeB, nodeO, nodeX, nodeY];
        const edges: SimpleEdge[] = [edgeAB, edgeXY];
        const expectedNodes: SimpleNode[] = [nodeA, nodeB];
        const expectedEdges: SimpleEdge[] = [edgeAB];
        const component = Graph.create(
            nodes,
            edges,
        ).getConnectedComponentOfNode("A");
        const expectedComponent = Graph.create(expectedNodes, expectedEdges);
        expectGraphsToBeEqual(component, expectedComponent);
    });

    it("should work if cycles are present", () => {
        const graph = TestGraphs.getTriangle();
        const component = graph.getConnectedComponentOfNode("A");
        expectGraphsToBeEqual(component, graph);
    });
});

describe("getShortestPath()", () => {
    const originalCanonicalize = (Graph as any).canonicalizePath;
    const canonicalizeSpy = jest.fn(originalCanonicalize);
    (Graph as any).canonicalizePath = canonicalizeSpy;

    afterAll(() => {
        (Graph as any).canonicalizePath = originalCanonicalize;
    });

    beforeEach(canonicalizeSpy.mockClear);

    afterEach(() => {
        expect(canonicalizeSpy).toHaveBeenCalled();
    });

    it("should return a trivial path when start and end are the same", () => {
        const graph = TestGraphs.getTwoNodes();
        const start: EdgePoint = { edgeId: "AB", distance: 0 };
        const end: EdgePoint = { edgeId: "AB", distance: 0 };
        const expectedPath: Path = {
            start,
            end: start,
            orientedEdges: [{ edge: graph.getEdge("AB"), isForward: true }],
            nodes: [],
            locations: [{ x: 0, y: 0 }],
            length: 0,
        };
        const path = graph.getShortestPath(start, end);
        expect(path).toEqual(expectedPath);
    });

    it("should return a path crossing over nodes", () => {
        const graph = TestGraphs.getFourNodes();
        const start: EdgePoint = { edgeId: "AB", distance: 0.5 };
        const end: EdgePoint = { edgeId: "CD", distance: 0.5 };
        const expectedPath: Path = {
            start,
            end,
            orientedEdges: [
                { edge: graph.getEdge("AB"), isForward: true },
                { edge: graph.getEdge("BC"), isForward: true },
                { edge: graph.getEdge("CD"), isForward: true },
            ],
            nodes: [graph.getNode("B"), graph.getNode("C")],
            locations: [
                { x: 0.5, y: 0 },
                { x: 1, y: 0 },
                { x: 2, y: 0 },
                { x: 2.5, y: 0 },
            ],
            length: 2,
        };
        const path = graph.getShortestPath(start, end);
        expect(path).toEqual(expectedPath);
    });

    it("should return a path crossing over nodes in reverse", () => {
        const graph = TestGraphs.getFourNodes();
        const start: EdgePoint = { edgeId: "CD", distance: 0.5 };
        const end: EdgePoint = { edgeId: "AB", distance: 0.5 };
        const expectedPath: Path = {
            start,
            end,
            orientedEdges: [
                { edge: graph.getEdge("CD"), isForward: false },
                { edge: graph.getEdge("BC"), isForward: false },
                { edge: graph.getEdge("AB"), isForward: false },
            ],
            nodes: [graph.getNode("C"), graph.getNode("B")],
            locations: [
                { x: 2.5, y: 0 },
                { x: 2, y: 0 },
                { x: 1, y: 0 },
                { x: 0.5, y: 0 },
            ],
            length: 2,
        };
        const path = graph.getShortestPath(start, end);
        expect(path).toEqual(expectedPath);
    });

    it("should return the shortest path in a triangle", () => {
        // A 15-20-25 right triangle.
        const nodes: SimpleNode[] = [
            { id: "A", location: { x: 0, y: 0 } },
            { id: "B", location: { x: 15, y: 0 } },
            { id: "C", location: { x: 0, y: 20 } },
        ];
        const edges: SimpleEdge[] = [
            { id: "AB", startNodeId: "A", endNodeId: "B" },
            { id: "BC", startNodeId: "B", endNodeId: "C" },
            { id: "CA", startNodeId: "C", endNodeId: "A" },
        ];
        const graph = Graph.create(nodes, edges);
        const start: EdgePoint = { edgeId: "CA", distance: 15 };
        const end: EdgePoint = { edgeId: "BC", distance: 5 };
        const expectedPath: Path = {
            start,
            end,
            orientedEdges: [
                { edge: graph.getEdge("CA"), isForward: true },
                { edge: graph.getEdge("AB"), isForward: true },
                { edge: graph.getEdge("BC"), isForward: true },
            ],
            nodes: [graph.getNode("A"), graph.getNode("B")],
            locations: [
                { x: 0, y: 5 },
                { x: 0, y: 0 },
                { x: 15, y: 0 },
                { x: 12, y: 4 },
            ],
            length: 25,
        };
        const path = graph.getShortestPath(start, end);
        expect(path).toEqual(expectedPath);
    });

    it("should return single edge path if start and end are on the same edge", () => {
        const graph = TestGraphs.getTwoNodes();
        const start: EdgePoint = { edgeId: "AB", distance: 0.25 };
        const end: EdgePoint = { edgeId: "AB", distance: 0.75 };
        const expectedPath: Path = {
            start,
            end,
            orientedEdges: [{ edge: graph.getEdge("AB"), isForward: true }],
            nodes: [],
            locations: [{ x: 0.25, y: 0 }, { x: 0.75, y: 0 }],
            length: 0.5,
        };
        const path = graph.getShortestPath(start, end);
        expect(path).toEqual(expectedPath);
    });

    it("should return single edge path if start and end are on the same edge in reverse", () => {
        // Same as last test but with start and end switched.
        const graph = TestGraphs.getTwoNodes();
        const start: EdgePoint = { edgeId: "AB", distance: 0.75 };
        const end: EdgePoint = { edgeId: "AB", distance: 0.25 };
        const expectedPath: Path = {
            start,
            end,
            orientedEdges: [{ edge: graph.getEdge("AB"), isForward: false }],
            nodes: [],
            locations: [{ x: 0.75, y: 0 }, { x: 0.25, y: 0 }],
            length: 0.5,
        };
        const path = graph.getShortestPath(start, end);
        expect(path).toEqual(expectedPath);
    });

    it("should work if start and end are on the same edge but shortest path goes through other edges", () => {
        const nodes: SimpleNode[] = [
            { id: "A", location: { x: 0, y: 0 } },
            { id: "B", location: { x: 1, y: 0 } },
        ];
        const edges: SimpleEdge[] = [
            {
                id: "longEdge",
                startNodeId: "A",
                endNodeId: "B",
                innerLocations: [{ x: 0, y: 1 }, { x: 1, y: 1 }],
            },
            {
                id: "shortEdge",
                startNodeId: "A",
                endNodeId: "B",
            },
        ];
        const graph = Graph.create(nodes, edges);
        const start = { edgeId: "longEdge", distance: 0.25 };
        const end = { edgeId: "longEdge", distance: 2.75 };
        const expectedPath: Path = {
            start,
            end,
            orientedEdges: [
                { edge: graph.getEdge("longEdge"), isForward: false },
                { edge: graph.getEdge("shortEdge"), isForward: true },
                { edge: graph.getEdge("longEdge"), isForward: false },
            ],
            nodes: [graph.getNode("A"), graph.getNode("B")],
            locations: [
                { x: 0, y: 0.25 },
                { x: 0, y: 0 },
                { x: 1, y: 0 },
                { x: 1, y: 0.25 },
            ],
            length: 1.5,
        };
        const path = graph.getShortestPath(start, end);
        expect(path).toEqual(expectedPath);
    });
});

describe("advanceAlongLocations()", () => {
    const locations: Location[] = [
        { x: 0, y: 0 },
        { x: 1, y: 0 },
        { x: 1, y: 1 },
    ];

    it("should return same locations if distance is zero", () => {
        const newLocations = Graph.advanceAlongLocations(locations, 0);
        expect(newLocations).toEqual(locations);
    });

    it("should advance along locations, dropping passed points", () => {
        const newLocations = Graph.advanceAlongLocations(locations, 1.5);
        const expected: Location[] = [{ x: 1, y: 0.5 }, { x: 1, y: 1 }];
        expect(newLocations).toEqual(expected);
    });

    it("should return just the endpoint if distance greater than total length", () => {
        const newLocations = Graph.advanceAlongLocations(locations, 4);
        const expected: Location[] = [{ x: 1, y: 1 }];
        expect(newLocations).toEqual(expected);
    });

    it("should throw on negative distance", () => {
        expect(() => Graph.advanceAlongLocations(locations, -1)).toThrowError(
            /negative/,
        );
    });
});

describe("advancePath()", () => {
    const graph = TestGraphs.getFourNodes();
    const path: Path = {
        start: { edgeId: "AB", distance: 0.5 },
        end: { edgeId: "CD", distance: 0.5 },
        orientedEdges: [
            { edge: graph.getEdge("AB"), isForward: true },
            { edge: graph.getEdge("BC"), isForward: true },
            { edge: graph.getEdge("CD"), isForward: true },
        ],
        nodes: [graph.getNode("B"), graph.getNode("C")],
        locations: [
            { x: 0.5, y: 0 },
            { x: 1, y: 0 },
            { x: 2, y: 0 },
            { x: 2.5, y: 0 },
        ],
        length: 2,
    };

    it("should return the same path if distance is zero", () => {
        const advanced = Graph.advanceAlongPath(path, 0);
        expect(advanced).toEqual(path);
    });

    it("should advance path, dropping nodes and edges", () => {
        const advanced = Graph.advanceAlongPath(path, 1.75);
        const expected: Path = {
            start: { edgeId: "CD", distance: 0.25 },
            end: { edgeId: "CD", distance: 0.5 },
            orientedEdges: [{ edge: graph.getEdge("CD"), isForward: true }],
            nodes: [],
            locations: [{ x: 2.25, y: 0 }, { x: 2.5, y: 0 }],
            length: 0.25,
        };
        expect(advanced).toEqual(expected);
    });

    it("should return a single-point path if distance is greater than length", () => {
        const advanced = Graph.advanceAlongPath(path, 3);
        const expected: Path = {
            start: { edgeId: "CD", distance: 0.5 },
            end: { edgeId: "CD", distance: 0.5 },
            orientedEdges: [{ edge: graph.getEdge("CD"), isForward: true }],
            nodes: [],
            locations: [{ x: 2.5, y: 0 }],
            length: 0,
        };
        expect(advanced).toEqual(expected);
    });

    it("should advance to the next edge if landing exactly on a node", () => {
        const advanced = Graph.advanceAlongPath(path, 1.5);
        const expected: Path = {
            start: { edgeId: "CD", distance: 0 },
            end: { edgeId: "CD", distance: 0.5 },
            orientedEdges: [{ edge: graph.getEdge("CD"), isForward: true }],
            nodes: [],
            locations: [{ x: 2, y: 0 }, { x: 2.5, y: 0 }],
            length: 0.5,
        };
        expect(advanced).toEqual(expected);
    });

    it("should throw on negative distance", () => {
        expect(() => Graph.advanceAlongPath(path, -1)).toThrowError(/negative/);
    });
});

describe("getClosestPoint()", () => {
    const angledSegment = (() => {
        const nodes: SimpleNode[] = [
            { id: "A", location: { x: 0, y: 0 } },
            { id: "B", location: { x: 12, y: 9 } },
        ];
        const edges: SimpleEdge[] = [
            { id: "AB", startNodeId: "A", endNodeId: "B" },
        ];
        return Graph.create(nodes, edges).withClosestPointMesh(0.25);
    })();

    it("should return a point at the requested location if it exists", () => {
        const closestPoint = angledSegment.getClosestPoint({ x: 4, y: 3 });
        const expected: EdgePoint = { edgeId: "AB", distance: 5 };
        expect(closestPoint).toEqual(expected);
    });

    it("should return the closest point in the middle of a segment", () => {
        const closestPoint = angledSegment.getClosestPoint({ x: 5, y: 10 });
        const expected: EdgePoint = { edgeId: "AB", distance: 10 };
        expect(closestPoint).toEqual(expected);
    });

    it("should return the closest point at the end of a segment", () => {
        const closestPoint = angledSegment.getClosestPoint({ x: 15, y: 15 });
        const expected: EdgePoint = { edgeId: "AB", distance: 15 };
        expect(closestPoint).toEqual(expected);
    });

    it("should return the closest point if exactly an endpoint of the segment", () => {
        const closestPoint1 = angledSegment.getClosestPoint({ x: 0, y: 0 });
        const expected1: EdgePoint = { edgeId: "AB", distance: 0 };
        expect(closestPoint1).toEqual(expected1);

        const closestPoint2 = angledSegment.getClosestPoint({ x: 12, y: 9 });
        const expected2: EdgePoint = { edgeId: "AB", distance: 15 };
        expect(closestPoint2).toEqual(expected2);
    });

    it("should return the closest point among multiple segments", () => {
        const graph = TestGraphs.getTriangle().withClosestPointMesh(0.25);
        const closestPoint = graph.getClosestPoint({ x: 0.125, y: 0.25 });
        const expected = { edgeId: "CA", distance: 0.75 };
        expect(closestPoint).toEqual(expected);
    });

    it("should work for edge with inner locations", () => {
        const nodes: SimpleNode[] = [
            { id: "A", location: { x: 0, y: 0 } },
            { id: "B", location: { x: 1, y: 0 } },
        ];
        const edges: SimpleEdge[] = [
            {
                id: "AB",
                startNodeId: "A",
                endNodeId: "B",
                innerLocations: [{ x: 0, y: 1 }, { x: 1, y: 1 }],
            },
        ];
        const graph = Graph.create(nodes, edges).withClosestPointMesh(0.25);
        const closestPoint = graph.getClosestPoint({ x: 0.25, y: 2 });
        const expected = { edgeId: "AB", distance: 1.25 };
        expect(closestPoint).toEqual(expected);
    });

    it("should work for an edge where start and end are the same location", () => {
        const nodes: SimpleNode[] = [
            { id: "A", location: { x: 0, y: 0 } },
            { id: "B", location: { x: 0, y: 0 } },
        ];
        const edges: SimpleEdge[] = [
            { id: "AB", startNodeId: "A", endNodeId: "B" },
        ];
        const graph = Graph.create(nodes, edges).withClosestPointMesh(0.25);
        const closestPoint = graph.getClosestPoint({ x: 1, y: 1 });
        const expected = { edgeId: "AB", distance: 0 };
        expect(closestPoint).toEqual(expected);
    });
});

describe("distance()", () => {
    it("should return zero given the same point twice", () => {
        const location: Location = { x: 1, y: 1 };
        expect(Graph.distance(location, location)).toEqual(0);
    });

    it("should return the distance between two points", () => {
        expect(Graph.distance({ x: 1, y: 1 }, { x: 4, y: 5 })).toEqual(5);
    });
});

function expectGraphsToBeEqual(actual: Graph, expected: Graph): void {
    expect(actual.getAllNodes()).toEqual(expected.getAllNodes());
    expect(actual.getAllEdges()).toEqual(expected.getAllEdges());
}

describe("canonicalizePath()", () => {
    // Expose private static method.
    const canonicalizePath: (path: Path) => Path = (Graph as any)
        .canonicalizePath;

    it("should leave ordinary path unchanged", () => {
        const graph = TestGraphs.getFourNodes();
        const path: Path = {
            start: { edgeId: "AB", distance: 0.5 },
            end: { edgeId: "CD", distance: 0.5 },
            nodes: [graph.getNode("B"), graph.getNode("C")],
            orientedEdges: [
                { edge: graph.getEdge("AB"), isForward: true },
                { edge: graph.getEdge("BC"), isForward: true },
                { edge: graph.getEdge("CD"), isForward: true },
            ],
            locations: [
                { x: 0.5, y: 0 },
                { x: 1, y: 0 },
                { x: 2, y: 0 },
                { x: 2.5, y: 0 },
            ],
            length: 2,
        };
        const canonPath = canonicalizePath(path);
        expect(canonPath).toEqual(path);
    });

    it("should remove starting zero length segment", () => {
        const graph = TestGraphs.getFourNodes();
        const path: Path = {
            start: { edgeId: "AB", distance: 1 },
            end: { edgeId: "CD", distance: 0.5 },
            nodes: [graph.getNode("B"), graph.getNode("C")],
            orientedEdges: [
                { edge: graph.getEdge("AB"), isForward: true },
                { edge: graph.getEdge("BC"), isForward: true },
                { edge: graph.getEdge("CD"), isForward: true },
            ],
            locations: [{ x: 1, y: 0 }, { x: 2, y: 0 }, { x: 2.5, y: 0 }],
            length: 1.5,
        };
        const expected: Path = {
            ...path,
            start: { edgeId: "BC", distance: 0 },
            nodes: [graph.getNode("C")],
            orientedEdges: [
                { edge: graph.getEdge("BC"), isForward: true },
                { edge: graph.getEdge("CD"), isForward: true },
            ],
        };
        const actual = canonicalizePath(path);
        expect(actual).toEqual(expected);
    });

    it("should remove ending zero length segment", () => {
        const graph = TestGraphs.getFourNodes();
        const path: Path = {
            start: { edgeId: "AB", distance: 0.5 },
            end: { edgeId: "CD", distance: 0 },
            nodes: [graph.getNode("B"), graph.getNode("C")],
            orientedEdges: [
                { edge: graph.getEdge("AB"), isForward: true },
                { edge: graph.getEdge("BC"), isForward: true },
                { edge: graph.getEdge("CD"), isForward: true },
            ],
            locations: [{ x: 0.5, y: 0 }, { x: 1, y: 0 }, { x: 2, y: 0 }],
            length: 1.5,
        };
        const expected: Path = {
            ...path,
            end: { edgeId: "BC", distance: 1 },
            nodes: [graph.getNode("B")],
            orientedEdges: [
                { edge: graph.getEdge("AB"), isForward: true },
                { edge: graph.getEdge("BC"), isForward: true },
            ],
        };
        const actual = canonicalizePath(path);
        expect(actual).toEqual(expected);
    });

    it("should remove both starting and ending zero length segments", () => {
        const graph = TestGraphs.getFourNodes();
        const path: Path = {
            start: { edgeId: "AB", distance: 1 },
            end: { edgeId: "CD", distance: 0 },
            nodes: [graph.getNode("B"), graph.getNode("C")],
            orientedEdges: [
                { edge: graph.getEdge("AB"), isForward: true },
                { edge: graph.getEdge("BC"), isForward: true },
                { edge: graph.getEdge("CD"), isForward: true },
            ],
            locations: [{ x: 1, y: 0 }, { x: 2, y: 0 }],
            length: 1,
        };
        const expected: Path = {
            ...path,
            start: { edgeId: "BC", distance: 0 },
            end: { edgeId: "BC", distance: 1 },
            nodes: [],
            orientedEdges: [{ edge: graph.getEdge("BC"), isForward: true }],
        };
        const actual = canonicalizePath(path);
        expect(actual).toEqual(expected);
    });

    it("should behave on single point path", () => {
        const graph = TestGraphs.getTwoNodes();
        const start = { edgeId: "AB", distance: 0.5 };
        const path: Path = {
            start,
            end: start,
            nodes: [],
            orientedEdges: [{ edge: graph.getEdge("AB"), isForward: true }],
            locations: [{ x: 0.5, y: 0 }],
            length: 0,
        };
        const canonPath = canonicalizePath(path);
        expect(canonPath).toBe(path);
    });

    it("should behave on single point path where that point is a node", () => {
        const graph = TestGraphs.getTwoNodes();
        const start = { edgeId: "AB", distance: 1 };
        const path: Path = {
            start,
            end: start,
            nodes: [],
            orientedEdges: [{ edge: graph.getEdge("AB"), isForward: true }],
            locations: [{ x: 1, y: 0 }],
            length: 0,
        };
        const canonPath = canonicalizePath(path);
        expect(canonPath).toBe(path);
    });

    it("should behave on path where start and end are different representations of same node", () => {
        const graph = TestGraphs.getFourNodes();
        const start = { edgeId: "AB", distance: 1 };
        const end = { edgeId: "BC", distance: 0 };
        const path: Path = {
            start,
            end,
            nodes: [graph.getNode("B")],
            orientedEdges: [
                { edge: graph.getEdge("AB"), isForward: true },
                { edge: graph.getEdge("BC"), isForward: true },
            ],
            locations: [{ x: 1, y: 0 }],
            length: 0,
        };
        const expected: Path = {
            ...path,
            start: end,
            nodes: [],
            orientedEdges: [{ edge: graph.getEdge("BC"), isForward: true }],
        };
        const actual = canonicalizePath(path);
        expect(expected).toEqual(actual);
    });
});


text:
package br.com.navita.mobile.console.operator;

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

import javax.naming.NamingException;
import javax.sql.DataSource;

import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jndi.JndiObjectFactoryBean;

import br.com.navita.mobile.console.domain.DataSourceConnector;
import br.com.navita.mobile.console.domain.DataSourceQueryOperation;
import br.com.navita.mobile.console.domain.Operation;
import br.com.navita.mobile.domain.MobileBean;

public class DataSourceOperator implements Operator{

	@Override
	public MobileBean doOperation(Operation operation, Map<String, Object> params) throws NamingException {
		DataSourceQueryOperation queryOperation = (DataSourceQueryOperation) operation;
		DataSourceConnector connector = (DataSourceConnector) operation.getConnector();
		JndiObjectFactoryBean jndiBean = new JndiObjectFactoryBean();
		DataSource ds = (DataSource)jndiBean.getJndiTemplate().lookup(connector.getDataSource());
		NamedParameterJdbcTemplate  tp = new NamedParameterJdbcTemplate (ds);
		//FIXME: deve vir ja convertido em <String,String>
		Map<String,String> processedParams = prepareParameters(params);
		SqlParameterSource args = new MapSqlParameterSource(processedParams);
		MobileBean bean = new MobileBean();
		if(queryOperation.isReturnResultSet()){
			List<?> result = tp.queryForList(queryOperation.getQuery(), args);
			bean.setList(result);
		}else{
			int resultCode = tp.update(queryOperation.getQuery(), args);
			bean.setObject(resultCode);
		}

		return bean;
	}

	private Map<String, String> prepareParameters(Map<String, Object> params) {
		Map<String, String> ret = new HashMap<String, String>();
		for(String key: params.keySet()){
			Object value = params.get(key);
			if(value != null && value.getClass().isArray()){
				ret.put(key, ((Object[])value)[0].toString());
			}else{
				ret.put(key, value.toString());
			}
		}

		return ret;
	}

}


text:
The "[Resource](https://github.com/resource) Way" of writing performant and maintainable jQuery.

## Table of Contents

1. [Variable Naming](#variables)
1. [Re-query](#re-query)
1. [Sizzle](#sizzle)

***

### Variable Naming
Prefix jQuery object variables with a `$`.

```javascript
// bad
var sidebar = $('.sidebar');

// good
var $sidebar = $('.sidebar');
```

### Re-query
Cache jQuery lookups.

```javascript
// bad
var setSidebar = function() {

	$('.sidebar').addClass('hidden-visually');

	// ...stuff...

	$('.sidebar').removeClass('hidden-visually');

}

// good
var setSidebar = function() {

	var $sidebar = $('.sidebar');

	$sidebar.addClass('hidden-visually');

	// ...stuff...

	$sidebar.removeClass('hidden-visually');

}
```

### Sizzle

Use performant selectors. Sizzle reads [right-to-left](http://css-tricks.com/efficiently-rendering-css/) like native CSS, so much of the same rules apply.

```javascript
// bad
var $sidebar = $('.main > .column .sidebar');

// good
var $sidebar = $('.sidebar');
```

Use `find` to select scoped jQuery object queries.

```javascript
// bad
var $sidebarList = $('ul', '.sidebar');

// bad
var $sidebarList = $('.sidebar ul');

// good
var $sidebarList = $('.sidebar').find('ul');
```


text:
package com.subgraph.orchid.directory.parsing;

public interface DocumentParsingHandler {
	void parseKeywordLine();
	void endOfDocument();
}


text:
std::string responseHead ();
std::string response (const std::string&, bool = false);
std::string error (const std::string&);


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mattieapps.openbrowser" >

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.mattieapps.openbrowser.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.LAUNCHER" />
                <category android:name="android.intent.category.BROWSABLE" />
                <category android:name="android.intent.category.APP_BROWSER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <!--Needed for reconizition as browser-->

                <data android:scheme="http" />
                <data android:scheme="https" />
                <data android:scheme="about" />
                <data android:scheme="javascript" />
            </intent-filter>
        </activity>
        <activity android:name=".Preferences"
            android:parentActivityName=".MainActivity"/>
    </application>

</manifest>


text:
function [ eyeMask ] = getEyeMask( img , varargin)

%% parse params
if isempty(varargin)
   perimeter_tickness = 10;
   do_plot = 0;
elseif (length(varargin) == 1 && strcmp(varargin{1}, 'do_plot')) || ...
        (length(varargin) == 3 && strcmp(varargin{3}, 'do_plot'))
   perimeter_tickness = 10;
   do_plot = 1;
elseif (length(varargin) == 2 || length(varargin) == 3) && strcmp(varargin{1}, 'perimeter')
   perimeter_tickness = varargin{2};
   do_plot = 0;
elseif length(varargin) == 3 && strcmp(varargin{2}, 'perimeter')
   perimeter_tickness = varargin{3};
   do_plot = 0;
else
   error('Incorrect inputs.')
end

%% create mask
if size(img,3) > 1
grayImg = rgb2gray(img);
else
    grayImg = img;
end
eyeMask = im2bw(grayImg , graythresh(grayImg));
eyeMask = imfill(eyeMask,'holes');

%% refine mask
CC = bwconncomp(eyeMask);
numPixels = cellfun(@numel,CC.PixelIdxList);
[biggest,idx] = max(numPixels);

% reset other small CCs (noise)
for i = 1:length(CC.PixelIdxList)
    if (i ~= idx)
        eyeMask(CC.PixelIdxList{i}) = 0;
    end
end

% find perimter
perimeter = bwperim(eyeMask);
perimeter = imdilate(perimeter,strel('disk',perimeter_tickness));

% sutract the perimeter to the mask
old_mask = eyeMask;
eyeMask(perimeter > 0) = 0;

%% plot
if do_plot
    figure
    subplot(2,2,1);
    imshow(img)
    title('Initial image')

    subplot(2,2,2);
    imshow(eyeMask)
    title('final mask')

    subplot(2,2,3);
    imshow(perimeter)
    title('perimeter')

    subplot(2,2,4);
    imshow(old_mask)
    title('Mask with perimter')
end


text:
package main

import (
	"math/rand"
	"os"
	"path/filepath"
	"runtime"
	"time"

	utilruntime "k8s.io/apimachinery/pkg/util/runtime"
	"k8s.io/apiserver/pkg/util/logs"
	"k8s.io/kubernetes/pkg/kubectl/scheme"

	"github.com/openshift/api/apps"
	"github.com/openshift/api/authorization"
	"github.com/openshift/api/build"
	"github.com/openshift/api/image"
	"github.com/openshift/api/network"
	"github.com/openshift/api/oauth"
	"github.com/openshift/api/operator"
	"github.com/openshift/api/project"
	"github.com/openshift/api/quota"
	"github.com/openshift/api/route"
	"github.com/openshift/api/security"
	"github.com/openshift/api/template"
	"github.com/openshift/api/user"
	"github.com/openshift/library-go/pkg/serviceability"
	"github.com/openshift/origin/pkg/api/install"
	"github.com/openshift/origin/pkg/api/legacy"
	"github.com/openshift/origin/pkg/oc/cli"
	"github.com/openshift/origin/pkg/version"
	"k8s.io/kubernetes/pkg/api/legacyscheme"
)

func main() {
	logs.InitLogs()
	defer logs.FlushLogs()
	defer serviceability.BehaviorOnPanic(os.Getenv("OPENSHIFT_ON_PANIC"), version.Get())()
	defer serviceability.Profile(os.Getenv("OPENSHIFT_PROFILE")).Stop()

	rand.Seed(time.Now().UTC().UnixNano())
	if len(os.Getenv("GOMAXPROCS")) == 0 {
		runtime.GOMAXPROCS(runtime.NumCPU())
	}

	// the kubectl scheme expects to have all the recognizable external types it needs to consume.  Install those here.
	// We can't use the "normal" scheme because apply will use that to build stategic merge patches on CustomResources
	utilruntime.Must(apps.Install(scheme.Scheme))
	utilruntime.Must(authorization.Install(scheme.Scheme))
	utilruntime.Must(build.Install(scheme.Scheme))
	utilruntime.Must(image.Install(scheme.Scheme))
	utilruntime.Must(network.Install(scheme.Scheme))
	utilruntime.Must(oauth.Install(scheme.Scheme))
	utilruntime.Must(operator.Install(scheme.Scheme))
	utilruntime.Must(project.Install(scheme.Scheme))
	utilruntime.Must(quota.Install(scheme.Scheme))
	utilruntime.Must(route.Install(scheme.Scheme))
	utilruntime.Must(security.Install(scheme.Scheme))
	utilruntime.Must(template.Install(scheme.Scheme))
	utilruntime.Must(user.Install(scheme.Scheme))
	legacy.InstallExternalLegacyAll(scheme.Scheme)

	// the legacyscheme is used in kubectl and expects to have the internal types registered.  Explicitly wire our types here.
	// this does
	install.InstallInternalOpenShift(legacyscheme.Scheme)
	legacy.InstallInternalLegacyAll(scheme.Scheme)

	basename := filepath.Base(os.Args[0])
	command := cli.CommandFor(basename)
	if err := command.Execute(); err != nil {
		os.Exit(1)
	}
}


text:
/*
    Author:     Piotr Kapela    [https://github.com/pkapela]
    Program:    WeatherSpot
    Created:    Jun/5/2015
    File:       NetworkClass.cs
    Desc:       WeatherSpot is a client type application which connects to weatherspot.us
                website to fetch and display the data on a graph. The data itself is gathered
                by embedded devices which monitor and record into Influx Database properties
                like temperature, humidity or pressure. In addition, the application includes
                console feature which allows manual querries into the database. The elementary
                statistics section was added for the convinience of a user. This program
                uses two open source libraries JSON.NET for deserialization of JSON data and
                Dynamic Data Display for graphs plotting.
*/

using System.IO;
using System.Net;

namespace WeatherSpot
{
    class NetworkClass
    {
        static public string serverResponse(string dbQuerry)
        {
            HelperClass.serverStringFormatter(ref dbQuerry);

            WebRequest serverResponse;
            serverResponse = WebRequest.Create(dbQuerry);
            /*
                    WebProxy myProxy = new WebProxy("myproxy", 80);
                    myProxy.BypassProxyOnLocal = true;

                    wrGETURL.Proxy = WebProxy.GetDefaultProxy();
           */
            Stream objStream;
            string strLine = "";

            objStream = serverResponse.GetResponse().GetResponseStream();
            StreamReader objReader = new StreamReader(objStream);

            strLine = objReader.ReadLine();
            strLine = objReader.ReadLine();

            HelperClass.stringFormatter(ref strLine);

            return strLine;

        } // end of method

    } // end of class

} // end of namespace


text:
namespace nethack_qt_ {

// for calls to drawWorn
enum drawWornFlag { dollNoFlag = 0, dollUnused = 1, dollReverse = 2 };

class NetHackQtInvUsageWindow : public QWidget {
public:
	NetHackQtInvUsageWindow(QWidget* parent);
	virtual ~NetHackQtInvUsageWindow();
	virtual void paintEvent(QPaintEvent*);
	virtual QSize sizeHint(void) const;

protected:
        virtual bool event(QEvent *event);
	virtual void mousePressEvent(QMouseEvent *event);

private:
        void drawWorn(QPainter &painter, obj *nhobj, int x, int y,
                      const char *alttip, int flags = dollNoFlag);
        bool tooltip_event(QHelpEvent *tipevent);

        char *tips[3][6]; // PAPERDOLL is a grid of 3x6 cells for tiles
};

} // namespace nethack_qt_

#endif


text:
from functools import wraps

def resolve_only_args(func):
    @wraps(func)
    def inner(self, args, info):
        return func(self, **args)
    return inner


text:
"""Reads the EXIF headers from geo-tagged photos. and creates a KML file.

Reads the EXIF headers from geo-tagged photos and creates a KML file with
a PhotoOverlay element for each file. Requires the open source EXIF.py file
downloadable at:

http://sourceforge.net/projects/exif-py/

  GetFile(): Handles the opening of an individual file.
  GetHeaders(): Reads the headers from the file.
  DmsToDecimal(): Converts EXIF GPS headers data to a decimal degree.
  GetGps(): Parses out the the GPS headers from the headers data.
  CreateKmlDoc(): Creates an XML document object to represent the KML document.
  CreatePhotoOverlay: Creates an individual PhotoOverlay XML element object.
  CreateKmlFile(): Creates and writes out a KML document to file.
"""

__author__ = 'mmarks@google.com (Mano Marks)'

import sys
import xml.dom.minidom
import EXIF

def GetFile(file_name):
  """Handles opening the file.

  Args:
    file_name: the name of the file to get

  Returns:
    A file
  """

  the_file = None

  try:
    the_file = open(file_name, 'rb')

  except IOError:
    the_file = None

  return the_file

def GetHeaders(the_file):
  """Handles getting the EXIF headers and returns them as a dict.

  Args:
    the_file: A file object

  Returns:
    a dict mapping keys corresponding to the EXIF headers of a file.
  """

  data = EXIF.process_file(the_file, 'UNDEF', False, False, False)
  return data

def DmsToDecimal(degree_num, degree_den, minute_num, minute_den,
                 second_num, second_den):
  """Converts the Degree/Minute/Second formatted GPS data to decimal degrees.

  Args:
    degree_num: The numerator of the degree object.
    degree_den: The denominator of the degree object.
    minute_num: The numerator of the minute object.
    minute_den: The denominator of the minute object.
    second_num: The numerator of the second object.
    second_den: The denominator of the second object.

  Returns:
    A deciminal degree.
  """

  degree = float(degree_num)/float(degree_den)
  minute = float(minute_num)/float(minute_den)/60
  second = float(second_num)/float(second_den)/3600
  return degree + minute + second

def GetGps(data):
  """Parses out the GPS coordinates from the file.

  Args:
    data: A dict object representing the EXIF headers of the photo.

  Returns:
    A tuple representing the latitude, longitude, and altitude of the photo.
  """

  lat_dms = data['GPS GPSLatitude'].values
  long_dms = data['GPS GPSLongitude'].values
  latitude = DmsToDecimal(lat_dms[0].num, lat_dms[0].den,
                          lat_dms[1].num, lat_dms[1].den,
                          lat_dms[2].num, lat_dms[2].den)
  longitude = DmsToDecimal(long_dms[0].num, long_dms[0].den,
                           long_dms[1].num, long_dms[1].den,
                           long_dms[2].num, long_dms[2].den)
  if data['GPS GPSLatitudeRef'].printable == 'S': latitude *= -1
  if data['GPS GPSLongitudeRef'].printable == 'W': longitude *= -1
  altitude = None

  try:
    alt = data['GPS GPSAltitude'].values[0]
    altitude = alt.num/alt.den
    if data['GPS GPSAltitudeRef'] == 1: altitude *= -1

  except KeyError:
    altitude = 0

  return latitude, longitude, altitude

def CreateKmlDoc():
  """Creates a KML document."""

  kml_doc = xml.dom.minidom.Document()
  kml_element = kml_doc.createElementNS('http://www.opengis.net/kml/2.2', 'kml')
  kml_element.setAttribute('xmlns', 'http://www.opengis.net/kml/2.2')
  kml_element = kml_doc.appendChild(kml_element)
  document = kml_doc.createElement('Document')
  kml_element.appendChild(document)
  return kml_doc

def CreatePhotoOverlay(kml_doc, file_name, the_file, file_iterator):
  """Creates a PhotoOverlay element in the kml_doc element.

  Args:
    kml_doc: An XML document object.
    file_name: The name of the file.
    the_file: The file object.
    file_iterator: The file iterator, used to create the id.

  Returns:
    An XML element representing the PhotoOverlay.
  """

  photo_id = 'photo%s' % file_iterator
  data = GetHeaders(the_file)
  coords = GetGps(data)
  po = kml_doc.createElement('PhotoOverlay')
  po.setAttribute('id', photo_id)
  name = kml_doc.createElement('name')
  name.appendChild(kml_doc.createTextNode(file_name))
  description = kml_doc.createElement('description')
  description.appendChild(kml_doc.createCDATASection(''
                                                     'Click here to fly into '
                                                     'photo' % photo_id))
  po.appendChild(name)
  po.appendChild(description)
  icon = kml_doc.createElement('Icon')
  href = kml_doc.createElement('href')
  href.appendChild(kml_doc.createTextNode(file_name))
  camera = kml_doc.createElement('Camera')
  longitude = kml_doc.createElement('longitude')
  latitude = kml_doc.createElement('latitude')
  altitude = kml_doc.createElement('altitude')
  tilt = kml_doc.createElement('tilt')

  # Determines the proportions of the image and uses them to set FOV.
  width = float(data['EXIF ExifImageWidth'].printable)
  length = float(data['EXIF ExifImageLength'].printable)
  lf = str(width/length * -20.0)
  rf = str(width/length * 20.0)

  longitude.appendChild(kml_doc.createTextNode(str(coords[1])))
  latitude.appendChild(kml_doc.createTextNode(str(coords[0])))
  altitude.appendChild(kml_doc.createTextNode('10'))
  tilt.appendChild(kml_doc.createTextNode('90'))
  camera.appendChild(longitude)
  camera.appendChild(latitude)
  camera.appendChild(altitude)
  camera.appendChild(tilt)
  icon.appendChild(href)
  viewvolume = kml_doc.createElement('ViewVolume')
  leftfov = kml_doc.createElement('leftFov')
  rightfov = kml_doc.createElement('rightFov')
  bottomfov = kml_doc.createElement('bottomFov')
  topfov = kml_doc.createElement('topFov')
  near = kml_doc.createElement('near')
  leftfov.appendChild(kml_doc.createTextNode(lf))
  rightfov.appendChild(kml_doc.createTextNode(rf))
  bottomfov.appendChild(kml_doc.createTextNode('-20'))
  topfov.appendChild(kml_doc.createTextNode('20'))
  near.appendChild(kml_doc.createTextNode('10'))
  viewvolume.appendChild(leftfov)
  viewvolume.appendChild(rightfov)
  viewvolume.appendChild(bottomfov)
  viewvolume.appendChild(topfov)
  viewvolume.appendChild(near)
  po.appendChild(camera)
  po.appendChild(icon)
  po.appendChild(viewvolume)
  point = kml_doc.createElement('point')
  coordinates = kml_doc.createElement('coordinates')
  coordinates.appendChild(kml_doc.createTextNode('%s,%s,%s' %(coords[1],
                                                              coords[0],
                                                              coords[2])))
  point.appendChild(coordinates)
  po.appendChild(point)
  document = kml_doc.getElementsByTagName('Document')[0]
  document.appendChild(po)

def CreateKmlFile(file_names, new_file_name):
  """Creates the KML Document with the PhotoOverlays, and writes it to a file.

  Args:
    file_names: A list object of all the names of the files.
    new_file_name: A string of the name of the new file to be created.
  """

  files = {}

  for file_name in file_names:
    the_file = GetFile(file_name)
    if the_file is None:
      print "'%s' is unreadable\n" % file_name
      file_names.remove(file_name)
      continue
    else:
      files[file_name] = the_file

  kml_doc = CreateKmlDoc()
  file_iterator = 0
  for key in files.iterkeys():
    CreatePhotoOverlay(kml_doc, key, files[key], file_iterator)
    file_iterator += 1

  kml_file = open(new_file_name, 'w')
  kml_file.write(kml_doc.toprettyxml('  ', newl='\n', encoding='utf-8'))

def main():
# This function was taken from EXIF.py to directly handle
# command line arguments.

  args = sys.argv[1:]
  if len(args) < 1:
    print 'Please try again with a file name'

  else:
    CreateKmlFile(args, 'test.kml')

if __name__ == '__main__':
  main()


text:
[![alt text](https://readthedocs.org/projects/docs/badge/?version=latest "Documentation Status")](https://esp-idf.readthedocs.io/en/latest/?badge=latest)

ESP-IDF is the official development framework for the [ESP32](https://espressif.com/en/products/hardware/esp32/overview) chip.

# Developing With the ESP-IDF

## Setting Up ESP-IDF

See setup guides for detailed instructions to set up the ESP-IDF:

* [Windows Setup Guide](https://esp-idf.readthedocs.io/en/latest/get-started/windows-setup.html)
* [Mac OS Setup Guide](https://esp-idf.readthedocs.io/en/latest/get-started/macos-setup.html)
* [Linux Setup Guide](https://esp-idf.readthedocs.io/en/latest/get-started/linux-setup.html)

## Finding a Project

As well as the [esp-idf-template](https://github.com/espressif/esp-idf-template) project mentioned in the setup guide, ESP-IDF comes with some example projects in the [examples](examples) directory.

Once you've found the project you want to work with, change to its directory and you can configure and build it.

## Configuring the Project

`make menuconfig`

* Opens a text-based configuration menu for the project.
* Use up & down arrow keys to navigate the menu.
* Use Enter key to go into a submenu, Escape key to go out or to exit.
* Type `?` to see a help screen. Enter key exits the help screen.
* Use Space key, or `Y` and `N` keys to enable (Yes) and disable (No) configuration items with checkboxes "`[*]`"
* Pressing `?` while highlighting a configuration item displays help about that item.
* Type `/` to search the configuration items.

Once done configuring, press Escape multiple times to exit and say "Yes" to save the new configuration when prompted.

## Compiling the Project

`make all`

... will compile app, bootloader and generate a partition table based on the config.

## Flashing the Project

When `make all` finishes, it will print a command line to use esptool.py to flash the chip. However you can also do this from make by running:

`make flash`

This will flash the entire project (app, bootloader and partition table) to a new chip. The settings for serial port flashing can be configured with `make menuconfig`.

You don't need to run `make all` before running `make flash`, `make flash` will automatically rebuild anything which needs it.

## Viewing Serial Output

The `make monitor` target uses the [idf_monitor tool](https://esp-idf.readthedocs.io/en/latest/get-started/idf-monitor.html) to display serial output from the ESP32. idf_monitor also has a range of features to decode crash output and interact with the device. [Check the documentation page for details](https://esp-idf.readthedocs.io/en/latest/get-started/idf-monitor.html).

Exit the monitor by typing Ctrl-].

To flash and monitor output in one pass, you can run:

`make flash monitor`

## Compiling & Flashing Just the App

After the initial flash, you may just want to build and flash just your app, not the bootloader and partition table:

* `make app` - build just the app.
* `make app-flash` - flash just the app.

`make app-flash` will automatically rebuild the app if it needs it.

(In normal development there's no downside to reflashing the bootloader and partition table each time, if they haven't changed.)

## Parallel Builds

ESP-IDF supports compiling multiple files in parallel, so all of the above commands can be run as `make -jN` where `N` is the number of parallel make processes to run (generally N should be equal to or one more than the number of CPU cores in your system.)

Multiple make functions can be combined into one. For example: to build the app & bootloader using 5 jobs in parallel, then flash everything, and then display serial output from the ESP32 run:

```
make -j5 flash monitor
```

## The Partition Table

Once you've compiled your project, the "build" directory will contain a binary file with a name like "my_app.bin". This is an ESP32 image binary that can be loaded by the bootloader.

A single ESP32's flash can contain multiple apps, as well as many different kinds of data (calibration data, filesystems, parameter storage, etc). For this reason a partition table is flashed to offset 0x8000 in the flash.

Each entry in the partition table has a name (label), type (app, data, or something else), subtype and the offset in flash where the partition is loaded.

The simplest way to use the partition table is to `make menuconfig` and choose one of the simple predefined partition tables:

* "Single factory app, no OTA"
* "Factory app, two OTA definitions"

In both cases the factory app is flashed at offset 0x10000. If you `make partition_table` then it will print a summary of the partition table.

For more details about partition tables and how to create custom variations, view the [`docs/api-guides/partition-tables.rst`](docs/api-guides/partition-tables.rst) file.

## Erasing Flash

The `make flash` target does not erase the entire flash contents. However it is sometimes useful to set the device back to a totally erased state, particularly when making partition table changes or OTA app updates. To erase the entire flash, run `make erase_flash`.

This can be combined with other targets, ie `make erase_flash flash` will erase everything and then re-flash the new app, bootloader and partition table.

# Resources

* Documentation for the latest version: https://esp-idf.readthedocs.io/. This documentation is built from the [docs directory](docs) of this repository.

* The [esp32.com forum](https://esp32.com/) is a place to ask questions and find community resources.

* [Check the Issues section on github](https://github.com/espressif/esp-idf/issues) if you find a bug or have a feature request. Please check existing Issues before opening a new one.

* If you're interested in contributing to ESP-IDF, please check the [Contributions Guide](https://esp-idf.readthedocs.io/en/latest/contribute/index.html).


text:
namespace exo {
namespace wayland {

namespace {

////////////////////////////////////////////////////////////////////////////////
// cursor_shapes interface:

static ui::mojom::CursorType GetCursorType(int32_t cursor_shape) {
  switch (cursor_shape) {
#define ADD_CASE(wayland, chrome)                        \
  case ZCR_CURSOR_SHAPES_V1_CURSOR_SHAPE_TYPE_##wayland: \
    return ui::mojom::CursorType::chrome

    ADD_CASE(POINTER, kPointer);
    ADD_CASE(CROSS, kCross);
    ADD_CASE(HAND, kHand);
    ADD_CASE(IBEAM, kIBeam);
    ADD_CASE(WAIT, kWait);
    ADD_CASE(HELP, kHelp);
    ADD_CASE(EAST_RESIZE, kEastResize);
    ADD_CASE(NORTH_RESIZE, kNorthResize);
    ADD_CASE(NORTH_EAST_RESIZE, kNorthEastResize);
    ADD_CASE(NORTH_WEST_RESIZE, kNorthWestResize);
    ADD_CASE(SOUTH_RESIZE, kSouthResize);
    ADD_CASE(SOUTH_EAST_RESIZE, kSouthEastResize);
    ADD_CASE(SOUTH_WEST_RESIZE, kSouthWestResize);
    ADD_CASE(WEST_RESIZE, kWestResize);
    ADD_CASE(NORTH_SOUTH_RESIZE, kNorthSouthResize);
    ADD_CASE(EAST_WEST_RESIZE, kEastWestResize);
    ADD_CASE(NORTH_EAST_SOUTH_WEST_RESIZE, kNorthEastSouthWestResize);
    ADD_CASE(NORTH_WEST_SOUTH_EAST_RESIZE, kNorthWestSouthEastResize);
    ADD_CASE(COLUMN_RESIZE, kColumnResize);
    ADD_CASE(ROW_RESIZE, kRowResize);
    ADD_CASE(MIDDLE_PANNING, kMiddlePanning);
    ADD_CASE(EAST_PANNING, kEastPanning);
    ADD_CASE(NORTH_PANNING, kNorthPanning);
    ADD_CASE(NORTH_EAST_PANNING, kNorthEastPanning);
    ADD_CASE(NORTH_WEST_PANNING, kNorthWestPanning);
    ADD_CASE(SOUTH_PANNING, kSouthPanning);
    ADD_CASE(SOUTH_EAST_PANNING, kSouthEastPanning);
    ADD_CASE(SOUTH_WEST_PANNING, kSouthWestPanning);
    ADD_CASE(WEST_PANNING, kWestPanning);
    ADD_CASE(MOVE, kMove);
    ADD_CASE(VERTICAL_TEXT, kVerticalText);
    ADD_CASE(CELL, kCell);
    ADD_CASE(CONTEXT_MENU, kContextMenu);
    ADD_CASE(ALIAS, kAlias);
    ADD_CASE(PROGRESS, kProgress);
    ADD_CASE(NO_DROP, kNoDrop);
    ADD_CASE(COPY, kCopy);
    ADD_CASE(NONE, kNone);
    ADD_CASE(NOT_ALLOWED, kNotAllowed);
    ADD_CASE(ZOOM_IN, kZoomIn);
    ADD_CASE(ZOOM_OUT, kZoomOut);
    ADD_CASE(GRAB, kGrab);
    ADD_CASE(GRABBING, kGrabbing);
    ADD_CASE(DND_NONE, kDndNone);
    ADD_CASE(DND_MOVE, kDndMove);
    ADD_CASE(DND_COPY, kDndCopy);
    ADD_CASE(DND_LINK, kDndLink);
#undef ADD_CASE
    default:
      return ui::mojom::CursorType::kNull;
  }
}

void cursor_shapes_set_cursor_shape(wl_client* client,
                                    wl_resource* resource,
                                    wl_resource* pointer_resource,
                                    int32_t shape) {
  ui::mojom::CursorType cursor_type = GetCursorType(shape);
  if (cursor_type == ui::mojom::CursorType::kNull) {
    wl_resource_post_error(resource, ZCR_CURSOR_SHAPES_V1_ERROR_INVALID_SHAPE,
                           "Unrecognized shape %d", shape);
    return;
  }

  Pointer* pointer = GetUserDataAs<Pointer>(pointer_resource);
  pointer->SetCursorType(cursor_type);
}

const struct zcr_cursor_shapes_v1_interface cursor_shapes_implementation = {
    cursor_shapes_set_cursor_shape};

}  // namespace

void bind_cursor_shapes(wl_client* client,
                        void* data,
                        uint32_t version,
                        uint32_t id) {
  wl_resource* resource =
      wl_resource_create(client, &zcr_cursor_shapes_v1_interface, version, id);

  wl_resource_set_implementation(resource, &cursor_shapes_implementation, data,
                                 nullptr);
}

}  // namespace wayland
}  // namespace exo


text:
module Fog
  module AWS
    class Glacier
      class Real

        # Complete an upload
        #
        # ==== Parameters
        # * name<~String> Name of the vault to upload to
        # * upload_id<~String> The id of the upload to complete
        # * total_size<~Integer> The total archive size
        # * tree_hash<~String> the treehash for the archive
        # * options<~Hash>
        #   * account_id<~String> - The AWS account id. Defaults to the account owning the credentials making the request
        # ==== Returns
        # * response<~Excon::Response>:
        #
        # ==== See Also
        # http://docs.amazonwebservices.com/amazonglacier/latest/dev/api-multipart-complete-upload.html
        #
        def complete_multipart_upload(vault_name, upload_id, total_size, tree_hash, options={})
          account_id = options['account_id'] || '-'
          path = "/#{account_id}/vaults/#{Fog::AWS.escape(vault_name)}/multipart-uploads/#{upload_id}"

          headers = {
            'x-amz-archive-size' => total_size.to_s,
            'x-amz-sha256-tree-hash' => tree_hash
          }

          request(
            :expects  => 201,
            :idempotent => true,
            :headers => headers,
            :method   => :post,
            :path     => path
          )
        end
      end

    end
  end
end


text:
@interface EditableTextFieldCell : UITableViewCell

@property UITextField *textField;

@property NSAttributedString *activeLeftAttributedString;
@property NSAttributedString *inactiveLeftAttributedString;

@end


text:
dspacelabs/filesystem [![Travis](https://img.shields.io/travis/dSpaceLabs/Filesystem.svg)](https://travis-ci.org/dSpaceLabs/Filesystem)
=====================

Filesystem is generic PHP wrapper around the filesystem that allows you to setup
your application to store files almost anywhere. The problem this solves is that
during development you want to store things on disk, next you deploy your
application to Heroku and now you are having to deal with messy code that is
checking to see if you are on localhost or on a Heroku instance.

## Features

- Store assets on:
  - Local Disk
  - S3
  - More coming soon
- Mock Filesystem for testing
- Support for logging using `psr/log` package

## Installation

Stable: [![Packagist](https://img.shields.io/packagist/v/dspacelabs/filesystem.svg)](https://packagist.org/packages/dspacelabs/filesystem)

Development: [![Packagist Pre Release](https://img.shields.io/packagist/vpre/dspacelabs/filesystem.svg)](https://packagist.org/packages/dspacelabs/filesystem)

```shell
composer require "dspacelabs/filesystem:0.1@dev"
```

## Configuration

Each adapter has it's own configuration, I've tried to document that in the
adapter files. Use the source.

## Usage

```php
<?php

$adapter    = new \Dspacelabs\Component\Filesystem\Adapter\LocalAdapter('/tmp');
$filesystem = new \Dspacelabs\Component\Filesystem\Filesystem($adapter);

// Everything uses the `dspace` protocol, you can swap out different adapters
// but the protocol will always stay the same.
$handle = fopen('dspace://file.txt', 'w+');
fwrite($handle, 'testing');
fclose($handle);
```

```shell
$ cat /tmp/file.txt
testing
```

For more usage example, check out the tests directory.

## Testing

Just run `phpunit` to run all the tests.

```bash
phpunit
```

## Change Log

See [CHANGELOG.md].

## License

[![Packagist](https://img.shields.io/packagist/l/dSpaceLabs/Filesystem.svg)](https://github.com/dSpaceLabs/Filesystem/blob/master/LICENSE)

See [LICENSE].

[CHANGELOG.md]: CHANGELOG.md
[LICENSE]: LICENSE


text:
Reports unnecessary cast expressions.

Example:

  static Object toObject(String s) {
    return (Object) s;
  }

  Use the checkbox below to ignore clarifying casts e.g., casts in collection calls where Object is expected:

  static void removeFromList(List<String> l, Object o) {
    l.remove((String)o);
  }


text:
class ChangelogError(Exception):
    """ Common module exception class"""
    pass

class WrongMessageTypeError(ChangelogError):
    pass

class ConfigNotFoundError(ChangelogError):
    pass


text: Contains a number of useful scripts to migrate your configuration and data to a new installation


text:
// Copyright (c) Christof Senn. All rights reserved. See license.txt in the project root for license information.

namespace Aqua.TypeSystem.Emit
{
    using System;
    using System.Runtime.Serialization;

    [Serializable]
    public class TypeEmitterException : Exception
    {
        public TypeEmitterException()
        {
        }

        public TypeEmitterException(string message)
            : base(message)
        {
        }

        public TypeEmitterException(string message, Exception? innerException)
            : base(message, innerException)
        {
        }

        protected TypeEmitterException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }
    }
}


text:
<?php
namespace Lead\Sql\Dialect\Statement\Behavior;

trait HasFlags
{
    /**
     * Sets a flag.
     *
     * @param  string  $name   The name of the flag to set.
     * @param  boolean $enable The boolean value to set.
     * @return boolean         The flag value.
     */
    public function setFlag($flag, $enable = true)
    {
        return $this->_parts['flags'][$flag] = !!$enable;
    }

    /**
     * Gets a flag.
     *
     * @param  string  $name The name of the flag to get.
     * @return boolean       The flag value.
     */
    public function getFlag($flag)
    {
        return isset($this->_parts['flags'][$flag]) ? $this->_parts['flags'][$flag] : null;
    }
}


text:
- [Getting Started with Arduino](http://www.arduino.cc/en/Guide/HomePage)
- [Unofficial list of 3rd party boards support urls](https://github.com/arduino/Arduino/wiki/Unofficial-list-of-3rd-party-boards-support-urls)
  - Generic ESP8266 modules
  - Olimex MOD-WIFI-ESP8266
  - NodeMCU 0.9 (ESP-12)
  - NodeMCU 1.0 (ESP-12E)
  - Adafruit HUZZAH ESP8266 (ESP-12)
  - SparkFun Thing
  - SweetPea ESP-210
  - WeMos D1
  - WeMos D1 mini

# Setup Steps

1. File > Preferences > Additional Boards Manager URLs
   - http://arduino.esp8266.com/stable/package_esp8266com_index.json
2. Tools > Board > Board Manager

# Linux Configuration

```sh
user@workstation:~/Downloads/arduino-1.8.2$ sudo usermod -a -G dialout xe1gyq
```

```sh
[  346.986871] usb 2-2.2: new full-speed USB device number 12 using xhci_hcd
[  347.137961] usb 2-2.2: New USB device found, idVendor=10c4, idProduct=ea60
[  347.137964] usb 2-2.2: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[  347.137965] usb 2-2.2: Product: CP2102 USB to UART Bridge Controller
[  347.137966] usb 2-2.2: Manufacturer: Silicon Labs
[  347.137968] usb 2-2.2: SerialNumber: 0001
[  347.155481] usbcore: registered new interface driver cp210x
[  347.155501] usbserial: USB Serial support registered for cp210x
[  347.155536] cp210x 2-2.2:1.0: cp210x converter detected
[  347.156815] usb 2-2.2: cp210x converter now attached to ttyUSB0
```

# Arduino IDE Configuration

```
Board: NodeMCU 1.0
CPU Frequency: 80 MHz
Flash Size: 4M (3M SPIFFS)
Upload Speed: 115200
Port: /dev/ttyUSB0
```

Board Info

```sh
BN: Unknown board
VID: 10C4
PID: EA60
SN: Upload any sketch to obtain it
```

After uploading in Linux console:

```sh
Archiving built core (caching) in: /tmp/arduino_cache_802597/core/core_esp8266_esp8266_nodemcuv2_CpuFrequency_80,UploadSpeed_115200,FlashSize_4M3M_270be6ff9182869e36429f5bd365089d.a
Sketch uses 222129 bytes (21%) of program storage space. Maximum is 1044464 bytes.
Global variables use 31496 bytes (38%) of dynamic memory, leaving 50424 bytes for local variables. Maximum is 81920 bytes.
Uploading 226272 bytes from /tmp/arduino_build_658763/Blink.ino.bin to flash at 0x00000000
................................................................................ [ 36% ]
................................................................................ [ 72% ]
.............................................................                    [ 100% ]

```


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
in Wu & Zhuang, Fungal Diversity Res. Ser. (Hong Kong) 15: 109 (2005)

#### Original name
Sporidesmium bambusae M.B. Ellis, 1965

### Remarks
null


text:
Statistics
==========

.. module:: sympy.statistics

Note: This module has been deprecated. See the stats module.

The *statistics* module in SymPy implements standard probability distributions
and related tools. Its contents can be imported with the following statement::

    >>> from sympy import *
    >>> from sympy.statistics import *
    >>> init_printing(use_unicode=False, wrap_line=False, no_global=True)

Normal distributions
--------------------

``Normal(mu, sigma)`` creates a normal distribution with mean value ``mu`` and
standard deviation ``sigma``. The ``Normal`` class defines several
useful methods and properties. Various properties can be accessed directly as
follows:

    >>> N = Normal(0, 1)
    >>> N.mean
    0
    >>> N.median
    0
    >>> N.variance
    1
    >>> N.stddev
    1

You can generate random numbers from the desired distribution with the
``random`` method:

    >>> N = Normal(10, 5)
    >>> N.random() #doctest: +SKIP
    4.914375200829805834246144514
    >>> N.random() #doctest: +SKIP
    11.84331557474637897087177407
    >>> N.random() #doctest: +SKIP
    17.22474580071733640806996846
    >>> N.random() #doctest: +SKIP
    9.864643097429464546621602494

The probability density function (pdf) and cumulative distribution function
(cdf) of a distribution can be computed, either in symbolic form or for
particular values:

    >>> N = Normal(1, 1)
    >>> x = Symbol('x')
    >>> N.pdf(1)
       ___
     \/ 2
    --------
        ____
    2*\/ pi
    >>> N.pdf(3).evalf()
    0.0539909665131880
    >>> N.cdf(x)
       /  ___        \
       |\/ 2 *(x - 1)|
    erf|-------------|
       \      2      /   1
    ------------------ + -
            2            2
    >>> N.cdf(-oo), N.cdf(1), N.cdf(oo)
    (0, 1/2, 1)
    >>> N.cdf(5).evalf()
    0.999968328758167

The method ``probability`` gives the total probability on a given interval (a
convenient alternative syntax for cdf(b)-cdf(a)):

    >>> N = Normal(0, 1)
    >>> N.probability(-oo, 0)
    1/2
    >>> N.probability(-1, 1)
       /  ___\
       |\/ 2 |
    erf|-----|
       \  2  /
    >>> N.probability(-1, 1).evalf()
    0.682689492137086

You can also generate a symmetric confidence interval from a given desired
confidence level (given as a fraction 0-1). For the normal distribution, 68%,
95% and 99.7% confidence levels respectively correspond to approximately 1, 2
and 3 standard deviations:

    >>> N = Normal(0, 1)
    >>> N.confidence(0.68)
    (-0.994457883209753, 0.994457883209753)
    >>> N.confidence(0.95)
    (-1.95996398454005, 1.95996398454005)
    >>> N.confidence(0.997)
    (-2.96773792534178, 2.96773792534178)

Plug the interval back in to see that the value is correct:

    >>> N.probability(*N.confidence(0.95)).evalf()
    0.950000000000000

Other distributions
-------------------

Besides the normal distribution, uniform continuous distributions are also
supported. ``Uniform(a, b)`` represents the distribution with uniform
probability on the interval [a, b] and zero probability everywhere else. The
``Uniform`` class supports the same methods as the ``Normal`` class.

Additional distributions, including support for arbitrary user-defined distributions, are planned for the future.

API Reference
-------------

Sample
^^^^^^

.. autoclass:: sympy.statistics.distributions.Sample
   :members:

Continuous Probability Distributions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. autoclass:: sympy.statistics.distributions.ContinuousProbability
   :members:

.. autoclass:: sympy.statistics.distributions.Normal
   :members:

.. autoclass:: sympy.statistics.distributions.Uniform
   :members:

.. autoclass:: sympy.statistics.distributions.PDF
   :members:


text:
<?php
session_start();
include("cn.php");
$usuario  = $_SESSION['id'];

if( isset($_POST['boton'])  && isset($_SESSION['tipo']) ){
  $monto    = addslashes($_POST['monto']);
  $planta   = addslashes($_POST['planta']);
  $empresa  = addslashes($_POST['empresa']);
  $encargado= addslashes($_POST['encargado']);
  $user     = addslashes($_POST['usuario']);

  $s  = "update cobro set monto='".$monto."'  where encargado='".$encargado."' and empresa='".$empresa."' and id_usuario='".$usuario."'";
  $sql = mysql_query($s);
  echo "<script>  alert('Monto Actualizado correctamente');</script>";
  echo "<script>  location.href='index.php?planta=".$planta."&empresa=".$empresa."&encargado=".$encargado."&usuario=".$user."';</script>";
}
?>