text
stringlengths
2
1.04M
meta
dict
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Citp.IO; namespace Citp.Packets.FPtc { public class FPtcPatch : FPtcHeader { public const string PacketType = "Ptch"; #region Setup and Initialisation public FPtcPatch() : base(PacketType) { } #endregion #region Packet Content public ushort FixtureIdentifier { get; set; } public byte Universe { get; set; } public ushort Channel { get; set; } public ushort ChannelCount { get; set; } public string FixtureMake { get; set; } public string FixtureName { get; set; } #endregion #region Read/Write public override void ReadData(CitpBinaryReader data) { base.ReadData(data); FixtureIdentifier = data.ReadUInt16(); Universe = data.ReadByte(); data.ReadByte(); Channel = data.ReadUInt16(); ChannelCount = data.ReadUInt16(); FixtureMake = data.ReadUcs1(); FixtureName = data.ReadUcs1(); } public override void WriteData(CitpBinaryWriter data) { base.WriteData(data); data.Write(FixtureIdentifier); data.Write(Universe); data.Write((byte)0); data.Write(Channel); data.Write(ChannelCount); data.WriteUcs1(FixtureMake); data.WriteUcs1(FixtureName); } #endregion } }
{ "content_hash": "2014c0279024b842affd9d60fa73ede0", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 61, "avg_line_length": 23.352941176470587, "alnum_prop": 0.5698992443324937, "repo_name": "HakanL/ACN", "id": "981ae214cdfd8efcaddfc13f48259ad91a2deed9", "size": "1590", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Citp/Packets/FPtc/FPtcPatch.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "907709" } ], "symlink_target": "" }
package uk.gov.gchq.gaffer.accumulostore.integration; import com.google.common.collect.Lists; import org.junit.jupiter.api.Test; import uk.gov.gchq.gaffer.accumulostore.AccumuloProperties; import uk.gov.gchq.gaffer.accumulostore.utils.AccumuloPropertyNames; import uk.gov.gchq.gaffer.commonutil.StreamUtil; import uk.gov.gchq.gaffer.commonutil.TestGroups; import uk.gov.gchq.gaffer.commonutil.TestPropertyNames; import uk.gov.gchq.gaffer.data.element.Element; import uk.gov.gchq.gaffer.data.element.Entity; import uk.gov.gchq.gaffer.data.elementdefinition.view.View; import uk.gov.gchq.gaffer.data.elementdefinition.view.ViewElementDefinition; import uk.gov.gchq.gaffer.graph.Graph; import uk.gov.gchq.gaffer.graph.Graph.Builder; import uk.gov.gchq.gaffer.graph.GraphConfig; import uk.gov.gchq.gaffer.integration.StandaloneIT; import uk.gov.gchq.gaffer.operation.OperationException; import uk.gov.gchq.gaffer.operation.data.EntitySeed; import uk.gov.gchq.gaffer.operation.impl.add.AddElements; import uk.gov.gchq.gaffer.operation.impl.get.GetAllElements; import uk.gov.gchq.gaffer.operation.impl.get.GetElements; import uk.gov.gchq.gaffer.serialisation.implementation.StringSerialiser; import uk.gov.gchq.gaffer.store.StoreProperties; import uk.gov.gchq.gaffer.store.TestTypes; import uk.gov.gchq.gaffer.store.schema.Schema; import uk.gov.gchq.gaffer.store.schema.SchemaEntityDefinition; import uk.gov.gchq.gaffer.store.schema.TypeDefinition; import uk.gov.gchq.gaffer.user.User; import uk.gov.gchq.koryphe.impl.binaryoperator.StringConcat; import java.io.UnsupportedEncodingException; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; public class AccumuloAggregationIT extends StandaloneIT { private static final String VERTEX = "vertex"; private static final String PUBLIC_VISIBILITY = "publicVisibility"; private static final String PRIVATE_VISIBILITY = "privateVisibility"; private final User user = getUser(); private static final AccumuloProperties PROPERTIES = AccumuloProperties.loadStoreProperties(StreamUtil.storeProps(AccumuloStoreITs.class)); @Test public void shouldOnlyAggregateVisibilityWhenGroupByIsNull() throws Exception { final Graph graph = createGraph(); final Entity entity1 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(AccumuloPropertyNames.COLUMN_QUALIFIER_3, "value 3a") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_4, "value 4") .property(AccumuloPropertyNames.VISIBILITY, PUBLIC_VISIBILITY) .build(); final Entity entity2 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(AccumuloPropertyNames.COLUMN_QUALIFIER_3, "value 3a") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_4, "value 4") .property(AccumuloPropertyNames.VISIBILITY, PRIVATE_VISIBILITY) .build(); final Entity entity3 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(AccumuloPropertyNames.COLUMN_QUALIFIER_3, "value 3b") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_4, "value 4") .property(AccumuloPropertyNames.VISIBILITY, PRIVATE_VISIBILITY) .build(); graph.execute(new AddElements.Builder() .input(entity1, entity2, entity3) .build(), user); // Given final GetElements getElements = new GetElements.Builder() .input(new EntitySeed(VERTEX)) .view(new View.Builder() .entity(TestGroups.ENTITY) .build()) .build(); // When final List<Element> results = Lists.newArrayList(graph.execute(getElements, user)); // Then assertThat(results) .hasSize(2); final Entity expectedSummarisedEntity = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(AccumuloPropertyNames.COLUMN_QUALIFIER, "") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_2, "") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_3, "value 3a") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_4, "value 4") .property(AccumuloPropertyNames.VISIBILITY, PRIVATE_VISIBILITY + "," + PUBLIC_VISIBILITY) .build(); final Entity expectedEntity = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(AccumuloPropertyNames.COLUMN_QUALIFIER, "") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_2, "") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_3, "value 3b") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_4, "value 4") .property(AccumuloPropertyNames.VISIBILITY, PRIVATE_VISIBILITY) .build(); assertThat(results).contains(expectedSummarisedEntity, expectedEntity); } @Test public void shouldAggregateOverAllPropertiesExceptForGroupByProperties() throws Exception { final Graph graph = createGraph(); final Entity entity1 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(AccumuloPropertyNames.COLUMN_QUALIFIER, "some value") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_2, "some value 2") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_3, "some value 3") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_4, "some value 4") .property(AccumuloPropertyNames.VISIBILITY, PUBLIC_VISIBILITY) .build(); final Entity entity2 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(AccumuloPropertyNames.COLUMN_QUALIFIER, "some value") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_2, "some value 2b") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_3, "some value 3b") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_4, "some value 4b") .property(AccumuloPropertyNames.VISIBILITY, PRIVATE_VISIBILITY) .build(); final Entity entity3 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(AccumuloPropertyNames.COLUMN_QUALIFIER, "some value c") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_2, "some value 2c") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_3, "some value 3c") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_4, "some value 4c") .property(AccumuloPropertyNames.VISIBILITY, PRIVATE_VISIBILITY) .build(); graph.execute(new AddElements.Builder().input(entity1, entity2, entity3).build(), user); // Given final GetElements getElements = new GetElements.Builder() .input(new EntitySeed(VERTEX)) .view(new View.Builder() .entity(TestGroups.ENTITY, new ViewElementDefinition.Builder() .groupBy(AccumuloPropertyNames.COLUMN_QUALIFIER) .build()) .build()) .build(); // When final List<Element> results = Lists.newArrayList(graph.execute(getElements, user)); // Then assertThat(results) .hasSize(2); final Entity expectedEntity = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(AccumuloPropertyNames.COLUMN_QUALIFIER, "some value") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_2, "some value 2,some value 2b") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_3, "some value 3,some value 3b") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_4, "some value 4,some value 4b") .property(AccumuloPropertyNames.VISIBILITY, PUBLIC_VISIBILITY + "," + PRIVATE_VISIBILITY) .build(); assertThat(results).contains(expectedEntity, entity3); } @Test public void shouldHandleAggregationWhenGroupByPropertiesAreNull() throws OperationException, UnsupportedEncodingException { final Graph graph = createGraphNoVisibility(); final Entity entity1 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(AccumuloPropertyNames.COLUMN_QUALIFIER, null) .property(AccumuloPropertyNames.COLUMN_QUALIFIER_2, null) .property(AccumuloPropertyNames.COLUMN_QUALIFIER_3, null) .property(AccumuloPropertyNames.COLUMN_QUALIFIER_4, null) .build(); final Entity entity2 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(AccumuloPropertyNames.COLUMN_QUALIFIER_3, "test 3") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_4, "test 4") .build(); graph.execute(new AddElements.Builder().input(entity1, entity2).build(), user); // Given final GetElements getElements = new GetElements.Builder() .input(new EntitySeed(VERTEX)) .view(new View.Builder() .entity(TestGroups.ENTITY, new ViewElementDefinition.Builder() .groupBy() .build()) .build()) .build(); // When final List<Element> results = Lists.newArrayList(graph.execute(getElements, user)); // Then assertThat(results) .hasSize(1); final Entity expectedEntity = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(AccumuloPropertyNames.COLUMN_QUALIFIER, ",") //String Aggregation is combining two empty strings -> "","" .property(AccumuloPropertyNames.COLUMN_QUALIFIER_2, ",") //String Aggregation is combining two empty strings -> "","" .property(AccumuloPropertyNames.COLUMN_QUALIFIER_3, ",test 3") //String Aggregation is combining one empty strings -> "","test 3" .property(AccumuloPropertyNames.COLUMN_QUALIFIER_4, ",test 4") //String Aggregation is combining one empty strings -> "","test 4" .build(); assertThat(results.get(0)).isEqualTo(expectedEntity); } @Test public void shouldHandleAggregationWhenAllColumnQualifierPropertiesAreGroupByProperties() throws OperationException, UnsupportedEncodingException { final Graph graph = createGraphNoVisibility(); final Entity entity1 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(AccumuloPropertyNames.COLUMN_QUALIFIER, "test 3") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_2, "test 4") .build(); final Entity entity2 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(AccumuloPropertyNames.COLUMN_QUALIFIER, "test 3") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_2, "test 4") .build(); graph.execute(new AddElements.Builder().input(entity1, entity2).build(), user); // Given final GetElements getElements = new GetElements.Builder() .input(new EntitySeed(VERTEX)) .view(new View.Builder() .entity(TestGroups.ENTITY, new ViewElementDefinition.Builder() .groupBy(AccumuloPropertyNames.COLUMN_QUALIFIER, AccumuloPropertyNames.COLUMN_QUALIFIER_2) .build()) .build()) .build(); // When final List<Element> results = Lists.newArrayList(graph.execute(getElements, user)); // Then assertThat(results) .hasSize(1); final Entity expectedEntity = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(AccumuloPropertyNames.COLUMN_QUALIFIER, "test 3") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_2, "test 4") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_3, "") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_4, "") .build(); assertThat(results.get(0)).isEqualTo(expectedEntity); } @Test public void shouldHandleAggregationWhenGroupByPropertiesAreNotSet() throws OperationException, UnsupportedEncodingException { final Graph graph = createGraphNoVisibility(); final Entity entity1 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(AccumuloPropertyNames.COLUMN_QUALIFIER_3, "test 3") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_4, "test 4") .build(); final Entity entity2 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(AccumuloPropertyNames.COLUMN_QUALIFIER_3, "test 3") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_4, "test 4") .build(); graph.execute(new AddElements.Builder().input(entity1, entity2).build(), user); // Given final GetElements getElements = new GetElements.Builder() .input(new EntitySeed(VERTEX)) .view(new View.Builder() .entity(TestGroups.ENTITY, new ViewElementDefinition.Builder() .groupBy(AccumuloPropertyNames.COLUMN_QUALIFIER, AccumuloPropertyNames.COLUMN_QUALIFIER_2) .build()) .build()) .build(); // When final List<Element> results = Lists.newArrayList(graph.execute(getElements, user)); // Then assertThat(results) .hasSize(1); final Entity expectedEntity = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(AccumuloPropertyNames.COLUMN_QUALIFIER, "") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_2, "") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_3, "test 3") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_4, "test 4") .build(); assertThat(results.get(0)).isEqualTo(expectedEntity); } @Test public void shouldHandleAggregationWithMultipleCombinations() throws OperationException, UnsupportedEncodingException { final Graph graph = createGraphNoVisibility(); final Entity entity1 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(AccumuloPropertyNames.COLUMN_QUALIFIER_3, "test 3") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_4, "test 4") .build(); final Entity entity2 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(AccumuloPropertyNames.COLUMN_QUALIFIER, null) .property(AccumuloPropertyNames.COLUMN_QUALIFIER_3, "test 3") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_4, "test 4") .build(); final Entity entity3 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(AccumuloPropertyNames.COLUMN_QUALIFIER, "test1a") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_3, "test 3") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_4, "test 4") .build(); final Entity entity4 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(AccumuloPropertyNames.COLUMN_QUALIFIER, "test1b") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_3, "test 3") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_4, "test 4") .build(); final Entity entity5 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(AccumuloPropertyNames.COLUMN_QUALIFIER, "test1a") .build(); final Entity entity6 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(AccumuloPropertyNames.COLUMN_QUALIFIER, "test1b") .build(); final Entity entity7 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(AccumuloPropertyNames.COLUMN_QUALIFIER_2, "test2a") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_3, "test 3") .build(); graph.execute(new AddElements.Builder().input( entity1, entity2, entity3, entity4, entity5, entity6, entity7 ).build(), user); // Duplicate the entities to check they are aggregated properly graph.execute(new AddElements.Builder().input( entity1, entity2, entity3, entity4, entity5, entity6, entity7 ).build(), user); // Given final GetElements getElements = new GetElements.Builder() .input(new EntitySeed(VERTEX)) .view(new View.Builder() .entity(TestGroups.ENTITY, new ViewElementDefinition.Builder() .groupBy(AccumuloPropertyNames.COLUMN_QUALIFIER, AccumuloPropertyNames.COLUMN_QUALIFIER_2) .build()) .build()) .build(); // When final List<Element> results = Lists.newArrayList(graph.execute(getElements, user)); // Then assertThat(results) .hasSize(4); final Entity expectedEntity1 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(AccumuloPropertyNames.COLUMN_QUALIFIER, "") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_2, "") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_3, "test 3") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_4, "test 4") .build(); final Entity expectedEntity2 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(AccumuloPropertyNames.COLUMN_QUALIFIER, "test1a") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_2, "") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_3, ",test 3") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_4, ",test 4") .build(); final Entity expectedEntity3 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(AccumuloPropertyNames.COLUMN_QUALIFIER, "test1b") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_2, "") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_3, ",test 3") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_4, ",test 4") .build(); final Entity expectedEntity4 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(AccumuloPropertyNames.COLUMN_QUALIFIER, "") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_2, "test2a") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_3, "test 3") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_4, "") .build(); assertThat(results).contains(expectedEntity1, expectedEntity2, expectedEntity3, expectedEntity4); } @Test public void shouldHandleAggregationWhenNoAggregatorsAreProvided() throws OperationException { final Graph graph = createGraphNoAggregators(); final Entity entity1 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(TestPropertyNames.PROP_3, "test 3") .property(TestPropertyNames.PROP_4, "test 4") .build(); final Entity entity2 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(TestPropertyNames.PROP_1, null) .property(TestPropertyNames.PROP_3, "test 3") .property(TestPropertyNames.PROP_4, "test 4") .build(); final Entity entity3 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(TestPropertyNames.PROP_1, "test1a") .property(TestPropertyNames.PROP_3, "test 3") .property(TestPropertyNames.PROP_4, "test 4") .build(); final Entity entity4 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(TestPropertyNames.PROP_1, "test1b") .property(TestPropertyNames.PROP_3, "test 3") .property(TestPropertyNames.PROP_4, "test 4") .build(); final Entity entity5 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(TestPropertyNames.PROP_1, "test1a") .build(); final Entity entity6 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(TestPropertyNames.PROP_1, "test1b") .build(); final Entity entity7 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(TestPropertyNames.PROP_2, "test2a") .property(TestPropertyNames.PROP_3, "test 3") .build(); graph.execute(new AddElements.Builder().input( entity1, entity2, entity3, entity4, entity5, entity6, entity7 ).build(), user); // Duplicate the entities to check they are not aggregated graph.execute(new AddElements.Builder() .input(entity1, entity2, entity3, entity4, entity5, entity6, entity7) .build(), user); // Given final GetAllElements getAllEntities = new GetAllElements.Builder() .view(new View.Builder() .entity(TestGroups.ENTITY) .build()) .build(); // When final List<Element> results = Lists.newArrayList(graph.execute(getAllEntities, user)); // Then assertThat(results) .hasSize(14); final Entity expectedEntity1 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(TestPropertyNames.PROP_1, "") .property(TestPropertyNames.PROP_2, "") .property(TestPropertyNames.PROP_3, "test 3") .property(TestPropertyNames.PROP_4, "test 4") .build(); final Entity expectedEntity2 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(TestPropertyNames.PROP_1, "test1a") .property(TestPropertyNames.PROP_2, "") .property(TestPropertyNames.PROP_3, "test 3") .property(TestPropertyNames.PROP_4, "test 4") .build(); final Entity expectedEntity3 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(TestPropertyNames.PROP_1, "test1b") .property(TestPropertyNames.PROP_2, "") .property(TestPropertyNames.PROP_3, "test 3") .property(TestPropertyNames.PROP_4, "test 4") .build(); final Entity expectedEntity4 = new Entity.Builder() .vertex(VERTEX) .group(TestGroups.ENTITY) .property(TestPropertyNames.PROP_1, "") .property(TestPropertyNames.PROP_2, "test2a") .property(TestPropertyNames.PROP_3, "test 3") .property(TestPropertyNames.PROP_4, "") .build(); assertThat(results).contains(expectedEntity1, expectedEntity2, expectedEntity3, expectedEntity4); } protected Graph createGraphNoVisibility() { return new Builder() .config(new GraphConfig.Builder() .graphId("graphWithNoVisibility") .build()) .storeProperties(createStoreProperties()) .addSchema(new Schema.Builder() .type(TestTypes.ID_STRING, new TypeDefinition.Builder() .clazz(String.class) .build()) .type("colQual", new TypeDefinition.Builder() .clazz(String.class) .aggregateFunction(new StringConcat()) .serialiser(new StringSerialiser()) .build()) .entity(TestGroups.ENTITY, new SchemaEntityDefinition.Builder() .vertex(TestTypes.ID_STRING) .property(AccumuloPropertyNames.COLUMN_QUALIFIER, "colQual") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_2, "colQual") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_3, "colQual") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_4, "colQual") .groupBy(AccumuloPropertyNames.COLUMN_QUALIFIER, AccumuloPropertyNames.COLUMN_QUALIFIER_2, AccumuloPropertyNames.COLUMN_QUALIFIER_3, AccumuloPropertyNames.COLUMN_QUALIFIER_4) .build()) .build()) .build(); } protected Graph createGraphNoAggregators() { return new Builder() .config(new GraphConfig.Builder() .graphId("graphWithNoAggregators") .build()) .storeProperties(createStoreProperties()) .addSchema(new Schema.Builder() .type(TestTypes.ID_STRING, new TypeDefinition.Builder() .clazz(String.class) .build()) .type("prop", new TypeDefinition.Builder() .clazz(String.class) .serialiser(new StringSerialiser()) .build()) .entity(TestGroups.ENTITY, new SchemaEntityDefinition.Builder() .vertex(TestTypes.ID_STRING) .property(TestPropertyNames.PROP_1, "prop") .property(TestPropertyNames.PROP_2, "prop") .property(TestPropertyNames.PROP_3, "prop") .property(TestPropertyNames.PROP_4, "prop") .aggregate(false) .build()) .build()) .build(); } @Override protected Schema createSchema() { return new Schema.Builder() .type(TestTypes.ID_STRING, new TypeDefinition.Builder() .clazz(String.class) .build()) .type("colQual", new TypeDefinition.Builder() .clazz(String.class) .aggregateFunction(new StringConcat()) .serialiser(new StringSerialiser()) .build()) .type("visibility", new TypeDefinition.Builder() .clazz(String.class) .aggregateFunction(new StringConcat()) .serialiser(new StringSerialiser()) .build()) .entity(TestGroups.ENTITY, new SchemaEntityDefinition.Builder() .vertex(TestTypes.ID_STRING) .property(AccumuloPropertyNames.COLUMN_QUALIFIER, "colQual") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_2, "colQual") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_3, "colQual") .property(AccumuloPropertyNames.COLUMN_QUALIFIER_4, "colQual") .property(AccumuloPropertyNames.VISIBILITY, "visibility") .groupBy(AccumuloPropertyNames.COLUMN_QUALIFIER, AccumuloPropertyNames.COLUMN_QUALIFIER_2, AccumuloPropertyNames.COLUMN_QUALIFIER_3, AccumuloPropertyNames.COLUMN_QUALIFIER_4) .build()) .visibilityProperty(AccumuloPropertyNames.VISIBILITY) .build(); } @Override protected User getUser() { return new User.Builder() .dataAuth(PUBLIC_VISIBILITY) .dataAuth(PRIVATE_VISIBILITY) .build(); } @Override public StoreProperties createStoreProperties() { return PROPERTIES; } }
{ "content_hash": "ec7308ff264818bb6bcd2e5f3ae21056", "timestamp": "", "source": "github", "line_count": 667, "max_line_length": 151, "avg_line_length": 46.44827586206897, "alnum_prop": 0.5681546754462412, "repo_name": "gchq/Gaffer", "id": "ad6e94de0e2d8a44b3d56df8e4ffaf6329fb3ac6", "size": "31584", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "store-implementation/accumulo-store/src/test/java/uk/gov/gchq/gaffer/accumulostore/integration/AccumuloAggregationIT.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "505" }, { "name": "HTML", "bytes": "3332" }, { "name": "Java", "bytes": "10043679" }, { "name": "JavaScript", "bytes": "2752310" }, { "name": "Shell", "bytes": "12638" } ], "symlink_target": "" }
package org.onosproject.incubator.net.routing; import org.onosproject.event.AbstractEvent; import java.util.Objects; /** * Describes an event about a route. */ public class RouteEvent extends AbstractEvent<RouteEvent.Type, ResolvedRoute> { /** * Route event type. */ public enum Type { /** * Route is new. */ ROUTE_ADDED, /** * Route has updated information. */ ROUTE_UPDATED, /** * Route was removed. */ ROUTE_REMOVED } /** * Creates a new route event. * * @param type event type * @param subject event subject */ public RouteEvent(Type type, ResolvedRoute subject) { super(type, subject); } /** * Creates a new route event. * * @param type event type * @param subject event subject * @param time event time */ protected RouteEvent(Type type, ResolvedRoute subject, long time) { super(type, subject, time); } @Override public int hashCode() { return Objects.hash(subject(), type()); } @Override public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof RouteEvent)) { return false; } RouteEvent that = (RouteEvent) other; return Objects.equals(this.subject(), that.subject()) && Objects.equals(this.type(), that.type()); } }
{ "content_hash": "e33716b50c8ee2d140f9cf7e3917d383", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 79, "avg_line_length": 20.026315789473685, "alnum_prop": 0.5486202365308804, "repo_name": "VinodKumarS-Huawei/ietf96yang", "id": "1889a532d5e999a844822a0efb8271af61404a3c", "size": "2139", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "incubator/api/src/main/java/org/onosproject/incubator/net/routing/RouteEvent.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "74069" }, { "name": "CSS", "bytes": "192215" }, { "name": "Groff", "bytes": "1090" }, { "name": "HTML", "bytes": "170763" }, { "name": "Java", "bytes": "26926510" }, { "name": "JavaScript", "bytes": "3066650" }, { "name": "Protocol Buffer", "bytes": "7499" }, { "name": "Python", "bytes": "121312" }, { "name": "Shell", "bytes": "913" } ], "symlink_target": "" }
/* This file was auto-generated by ensurePackage() in @jupyterlab/buildutils */ @import url('~@jupyterlab/apputils/style/index.css'); @import url('~@jupyterlab/docregistry/style/index.css'); @import url('~@jupyterlab/application/style/index.css'); @import url('~@jupyterlab/imageviewer/style/index.css');
{ "content_hash": "f7be07d8c18e2ad058d08575f7e583c3", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 79, "avg_line_length": 43.857142857142854, "alnum_prop": 0.749185667752443, "repo_name": "jupyter/jupyterlab", "id": "7f40d9606cab46ae4d7877a3f685908feead7696", "size": "567", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "packages/imageviewer-extension/style/index.css", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "7475" }, { "name": "CSS", "bytes": "94068" }, { "name": "HTML", "bytes": "1493" }, { "name": "JavaScript", "bytes": "9240" }, { "name": "Makefile", "bytes": "7654" }, { "name": "Python", "bytes": "74649" }, { "name": "Shell", "bytes": "2344" }, { "name": "TypeScript", "bytes": "1090669" } ], "symlink_target": "" }
package com.timeyang.jkes.core.elasticsearch.exception; /** * * @author chaokunyang */ public class IllegalAnnotatedFieldException extends RuntimeException { public IllegalAnnotatedFieldException() { } public IllegalAnnotatedFieldException(String message) { super(message); } }
{ "content_hash": "cc391359ab7158c7fcb4f0834e4a70cd", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 70, "avg_line_length": 21.928571428571427, "alnum_prop": 0.7361563517915309, "repo_name": "chaokunyang/jkes", "id": "72b726cc10c32ba158158cc5cce30079c624e34a", "size": "307", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jkes-core/src/main/java/com/timeyang/jkes/core/elasticsearch/exception/IllegalAnnotatedFieldException.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "6475" }, { "name": "CSS", "bytes": "8325" }, { "name": "Dockerfile", "bytes": "294" }, { "name": "HTML", "bytes": "14026" }, { "name": "Java", "bytes": "362430" }, { "name": "JavaScript", "bytes": "5360" }, { "name": "Makefile", "bytes": "6923" }, { "name": "Python", "bytes": "8750" } ], "symlink_target": "" }
import numpy as np from sdafile.character_inserter import ( ArrayInserter, BytesInserter, StringInserter, ) from sdafile.testing import InserterTestCase class TestCharacterInserter(InserterTestCase): def setUp(self): InserterTestCase.setUp(self) self.grp_attrs = dict( RecordType='character', Empty='no', ) self.ds_attrs = dict( RecordType='character', Empty='no', ) def tearDown(self): del self.grp_attrs del self.ds_attrs InserterTestCase.tearDown(self) def test_array_inserter(self): data = np.frombuffer(b'01', 'S1') expected = np.array([48, 49], np.uint8).reshape(2, -1) self.assertSimpleInsert( ArrayInserter, data, self.grp_attrs, self.ds_attrs, expected ) def test_array_inserter_reshaped(self): data = np.frombuffer(b'01', 'S1').reshape(2, -1) expected = np.array([48, 49], np.uint8).reshape(-1, 2) self.assertSimpleInsert( ArrayInserter, data, self.grp_attrs, self.ds_attrs, expected ) def test_array_inserter_empty(self): data = np.array([], 'S1') self.grp_attrs['Empty'] = self.ds_attrs['Empty'] = 'yes' self.assertSimpleInsert( ArrayInserter, data, self.grp_attrs, self.ds_attrs, expected=None ) def test_string_inserter(self): data = '01' expected = np.array([48, 49], np.uint8).reshape(2, -1) self.assertSimpleInsert( StringInserter, data, self.grp_attrs, self.ds_attrs, expected, ) def test_string_inserter_unicode(self): data = u'01' expected = np.array([48, 49], np.uint8).reshape(2, -1) self.assertSimpleInsert( StringInserter, data, self.grp_attrs, self.ds_attrs, expected, ) def test_string_inserter_empty(self): data = '' self.grp_attrs['Empty'] = self.ds_attrs['Empty'] = 'yes' self.assertSimpleInsert( StringInserter, data, self.grp_attrs, self.ds_attrs, expected=None ) def test_bytes_inserter(self): data = b'01' expected = np.array([48, 49], np.uint8).reshape(2, -1) self.assertSimpleInsert( BytesInserter, data, self.grp_attrs, self.ds_attrs, expected, ) def test_bytes_inserter_empty(self): data = b'' self.grp_attrs['Empty'] = self.ds_attrs['Empty'] = 'yes' self.assertSimpleInsert( BytesInserter, data, self.grp_attrs, self.ds_attrs, expected=None )
{ "content_hash": "e078c35f8dc730936f6cf639a96f9c14", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 64, "avg_line_length": 26.424778761061948, "alnum_prop": 0.5154052243804421, "repo_name": "enthought/sandia-data-archive", "id": "04dd713b2f9de1f962aea8c94db031117697760e", "size": "2986", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sdafile/tests/test_character_inserter.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "4012" }, { "name": "Matlab", "bytes": "1597" }, { "name": "Python", "bytes": "134833" } ], "symlink_target": "" }
class ApplicationController < ActionController::Base # Forgery Protection protect_from_forgery with: :exception # Filters before_action :authenticate_user! after_action :update_last_seen_at #before_action :http_basic_auth # Actions # Methods protected def find_lab_from_cookies if cookies.permanent.signed[:current_lab_id] @lab = current_user.labs.where(:id => cookies.permanent.signed[:current_lab_id]).first if !@lab @lab = current_user.labs.first end end end def save_lab_in_cookies(lab) cookies.permanent.signed[:current_lab_id] = lab.id end def render_404 raise ActionController::RoutingError.new('Not Found') end def set_flash_now_errors(object) if object.errors.any? flash.now[:alert] = object.errors.messages.values.join('<br />').html_safe end end def update_last_seen_at if current_user current_user.update_column(:last_seen_at, Time.now) if @lab lab_user_link = @lab.lab_user_links.where(:user_id => current_user.id).first if lab_user_link.try(:last_seen_at) && lab_user_link.last_seen_at < 30.minutes.ago @lab.increase_lab_visits end if lab_user_link lab_user_link.update_column(:last_seen_at, Time.now) end end end end def render_json_success(params = {}) render :json => { :success => true }.merge(params) end def render_json_errors(object) render :json => { :success => false, :errors => object.errors.messages.values } end def render_permission_error respond_to do |format| format.html do render :text => 'permission error' end format.json do render :json => { :success => false, :errors => ['permission error'] } end end end def render_xlsx(data, filename) # send_data(data, :disposition => :attachment, :filename => filename) send_data(data, :disposition => :inline, :filename => filename) end def admin_page? params[:controller].split('/').first == 'admin' end def http_basic_auth if ENV['HTTP_BASIC_AUTH_USERNAME'].present? authenticate_or_request_with_http_basic do |username, password| username == ENV['HTTP_BASIC_AUTH_USERNAME'] && password == ENV['HTTP_BASIC_AUTH_PASSWORD'] end end end end
{ "content_hash": "0433e1bf5d0674180aae20f1c19f194d", "timestamp": "", "source": "github", "line_count": 106, "max_line_length": 92, "avg_line_length": 22.660377358490567, "alnum_prop": 0.6240632805995004, "repo_name": "cetic/sitcom", "id": "cb278174e6d9863065b31c28ff5ac53dead719ed", "size": "2402", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/controllers/application_controller.rb", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "218471" }, { "name": "JavaScript", "bytes": "1071461" }, { "name": "Procfile", "bytes": "383" }, { "name": "Ruby", "bytes": "403764" }, { "name": "SCSS", "bytes": "66430" } ], "symlink_target": "" }
package org.testcontainers.junit.jupiter; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ConditionEvaluationResult; import org.junit.jupiter.api.extension.ExtensionContext; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class TestcontainersExtensionTests { @Test void whenDisabledWithoutDockerAndDockerIsAvailableTestsAreEnabled() { ConditionEvaluationResult result = new TestTestcontainersExtension(true) .evaluateExecutionCondition(extensionContext(DisabledWithoutDocker.class)); assertFalse(result.isDisabled()); } @Test void whenDisabledWithoutDockerAndDockerIsUnavailableTestsAreDisabled() { ConditionEvaluationResult result = new TestTestcontainersExtension(false) .evaluateExecutionCondition(extensionContext(DisabledWithoutDocker.class)); assertTrue(result.isDisabled()); } @Test void whenEnabledWithoutDockerAndDockerIsAvailableTestsAreEnabled() { ConditionEvaluationResult result = new TestTestcontainersExtension(true) .evaluateExecutionCondition(extensionContext(EnabledWithoutDocker.class)); assertFalse(result.isDisabled()); } @Test void whenEnabledWithoutDockerAndDockerIsUnavailableTestsAreEnabled() { ConditionEvaluationResult result = new TestTestcontainersExtension(false) .evaluateExecutionCondition(extensionContext(EnabledWithoutDocker.class)); assertFalse(result.isDisabled()); } private ExtensionContext extensionContext(Class clazz) { ExtensionContext extensionContext = mock(ExtensionContext.class); when(extensionContext.getRequiredTestClass()).thenReturn(clazz); return extensionContext; } @Testcontainers(disabledWithoutDocker = true) static final class DisabledWithoutDocker { } @Testcontainers static final class EnabledWithoutDocker { } static final class TestTestcontainersExtension extends TestcontainersExtension { private final boolean dockerAvailable; private TestTestcontainersExtension(boolean dockerAvailable) { this.dockerAvailable = dockerAvailable; } boolean isDockerAvailable() { return dockerAvailable; } } }
{ "content_hash": "2134c989ab7f51d48cd8167ec18b3785", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 87, "avg_line_length": 33.97222222222222, "alnum_prop": 0.7530662305805397, "repo_name": "outofcoffee/testcontainers-java", "id": "f3aea9bb8504c8033c466a7fbab0d90b05d83a82", "size": "2446", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/junit-jupiter/src/test/java/org/testcontainers/junit/jupiter/TestcontainersExtensionTests.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "729" }, { "name": "Dockerfile", "bytes": "518" }, { "name": "Groovy", "bytes": "16608" }, { "name": "HTML", "bytes": "149" }, { "name": "Java", "bytes": "1186664" }, { "name": "Shell", "bytes": "1375" }, { "name": "TSQL", "bytes": "824" } ], "symlink_target": "" }
var paper = function(self, undefined) { self = self || require('./node/self.js'); var window = self.window, document = self.document; var Base = new function() { var hidden = /^(statics|enumerable|beans|preserve)$/, array = [], slice = array.slice, create = Object.create, describe = Object.getOwnPropertyDescriptor, define = Object.defineProperty, forEach = array.forEach || function(iter, bind) { for (var i = 0, l = this.length; i < l; i++) { iter.call(bind, this[i], i, this); } }, forIn = function(iter, bind) { for (var i in this) { if (this.hasOwnProperty(i)) iter.call(bind, this[i], i, this); } }, set = Object.assign || function(dst) { for (var i = 1, l = arguments.length; i < l; i++) { var src = arguments[i]; for (var key in src) { if (src.hasOwnProperty(key)) dst[key] = src[key]; } } return dst; }, each = function(obj, iter, bind) { if (obj) { var desc = describe(obj, 'length'); (desc && typeof desc.value === 'number' ? forEach : forIn) .call(obj, iter, bind = bind || obj); } return bind; }; function inject(dest, src, enumerable, beans, preserve) { var beansNames = {}; function field(name, val) { val = val || (val = describe(src, name)) && (val.get ? val : val.value); if (typeof val === 'string' && val[0] === '#') val = dest[val.substring(1)] || val; var isFunc = typeof val === 'function', res = val, prev = preserve || isFunc && !val.base ? (val && val.get ? name in dest : dest[name]) : null, bean; if (!preserve || !prev) { if (isFunc && prev) val.base = prev; if (isFunc && beans !== false && (bean = name.match(/^([gs]et|is)(([A-Z])(.*))$/))) beansNames[bean[3].toLowerCase() + bean[4]] = bean[2]; if (!res || isFunc || !res.get || typeof res.get !== 'function' || !Base.isPlainObject(res)) { res = { value: res, writable: true }; } if ((describe(dest, name) || { configurable: true }).configurable) { res.configurable = true; res.enumerable = enumerable != null ? enumerable : !bean; } define(dest, name, res); } } if (src) { for (var name in src) { if (src.hasOwnProperty(name) && !hidden.test(name)) field(name); } for (var name in beansNames) { var part = beansNames[name], set = dest['set' + part], get = dest['get' + part] || set && dest['is' + part]; if (get && (beans === true || get.length === 0)) field(name, { get: get, set: set }); } } return dest; } function Base() { for (var i = 0, l = arguments.length; i < l; i++) { var src = arguments[i]; if (src) set(this, src); } return this; } return inject(Base, { inject: function(src) { if (src) { var statics = src.statics === true ? src : src.statics, beans = src.beans, preserve = src.preserve; if (statics !== src) inject(this.prototype, src, src.enumerable, beans, preserve); inject(this, statics, null, beans, preserve); } for (var i = 1, l = arguments.length; i < l; i++) this.inject(arguments[i]); return this; }, extend: function() { var base = this, ctor, proto; for (var i = 0, obj, l = arguments.length; i < l && !(ctor && proto); i++) { obj = arguments[i]; ctor = ctor || obj.initialize; proto = proto || obj.prototype; } ctor = ctor || function() { base.apply(this, arguments); }; proto = ctor.prototype = proto || create(this.prototype); define(proto, 'constructor', { value: ctor, writable: true, configurable: true }); inject(ctor, this); if (arguments.length) this.inject.apply(ctor, arguments); ctor.base = base; return ctor; } }).inject({ enumerable: false, initialize: Base, set: Base, inject: function() { for (var i = 0, l = arguments.length; i < l; i++) { var src = arguments[i]; if (src) { inject(this, src, src.enumerable, src.beans, src.preserve); } } return this; }, extend: function() { var res = create(this); return res.inject.apply(res, arguments); }, each: function(iter, bind) { return each(this, iter, bind); }, clone: function() { return new this.constructor(this); }, statics: { set: set, each: each, create: create, define: define, describe: describe, clone: function(obj) { return set(new obj.constructor(), obj); }, isPlainObject: function(obj) { var ctor = obj != null && obj.constructor; return ctor && (ctor === Object || ctor === Base || ctor.name === 'Object'); }, pick: function(a, b) { return a !== undefined ? a : b; }, slice: function(list, begin, end) { return slice.call(list, begin, end); } } }); }; if (typeof module !== 'undefined') module.exports = Base; Base.inject({ enumerable: false, toString: function() { return this._id != null ? (this._class || 'Object') + (this._name ? " '" + this._name + "'" : ' @' + this._id) : '{ ' + Base.each(this, function(value, key) { if (!/^_/.test(key)) { var type = typeof value; this.push(key + ': ' + (type === 'number' ? Formatter.instance.number(value) : type === 'string' ? "'" + value + "'" : value)); } }, []).join(', ') + ' }'; }, getClassName: function() { return this._class || ''; }, importJSON: function(json) { return Base.importJSON(json, this); }, exportJSON: function(options) { return Base.exportJSON(this, options); }, toJSON: function() { return Base.serialize(this); }, set: function(props, exclude) { if (props) Base.filter(this, props, exclude, this._prioritize); return this; } }, { beans: false, statics: { exports: {}, extend: function extend() { var res = extend.base.apply(this, arguments), name = res.prototype._class; if (name && !Base.exports[name]) Base.exports[name] = res; return res; }, equals: function(obj1, obj2) { if (obj1 === obj2) return true; if (obj1 && obj1.equals) return obj1.equals(obj2); if (obj2 && obj2.equals) return obj2.equals(obj1); if (obj1 && obj2 && typeof obj1 === 'object' && typeof obj2 === 'object') { if (Array.isArray(obj1) && Array.isArray(obj2)) { var length = obj1.length; if (length !== obj2.length) return false; while (length--) { if (!Base.equals(obj1[length], obj2[length])) return false; } } else { var keys = Object.keys(obj1), length = keys.length; if (length !== Object.keys(obj2).length) return false; while (length--) { var key = keys[length]; if (!(obj2.hasOwnProperty(key) && Base.equals(obj1[key], obj2[key]))) return false; } } return true; } return false; }, read: function(list, start, options, amount) { if (this === Base) { var value = this.peek(list, start); list.__index++; return value; } var proto = this.prototype, readIndex = proto._readIndex, begin = start || readIndex && list.__index || 0, length = list.length, obj = list[begin]; amount = amount || length - begin; if (obj instanceof this || options && options.readNull && obj == null && amount <= 1) { if (readIndex) list.__index = begin + 1; return obj && options && options.clone ? obj.clone() : obj; } obj = Base.create(proto); if (readIndex) obj.__read = true; obj = obj.initialize.apply(obj, begin > 0 || begin + amount < length ? Base.slice(list, begin, begin + amount) : list) || obj; if (readIndex) { list.__index = begin + obj.__read; var filtered = obj.__filtered; if (filtered) { list.__filtered = filtered; obj.__filtered = undefined; } obj.__read = undefined; } return obj; }, peek: function(list, start) { return list[list.__index = start || list.__index || 0]; }, remain: function(list) { return list.length - (list.__index || 0); }, readList: function(list, start, options, amount) { var res = [], entry, begin = start || 0, end = amount ? begin + amount : list.length; for (var i = begin; i < end; i++) { res.push(Array.isArray(entry = list[i]) ? this.read(entry, 0, options) : this.read(list, i, options, 1)); } return res; }, readNamed: function(list, name, start, options, amount) { var value = this.getNamed(list, name), hasValue = value !== undefined; if (hasValue) { var filtered = list.__filtered; if (!filtered) { var source = this.getSource(list); filtered = list.__filtered = Base.create(source); filtered.__unfiltered = source; } filtered[name] = undefined; } return this.read(hasValue ? [value] : list, start, options, amount); }, readSupported: function(list, dest) { var source = this.getSource(list), that = this, read = false; if (source) { Object.keys(source).forEach(function(key) { if (key in dest) { var value = that.readNamed(list, key); if (value !== undefined) { dest[key] = value; } read = true; } }); } return read; }, getSource: function(list) { var source = list.__source; if (source === undefined) { var arg = list.length === 1 && list[0]; source = list.__source = arg && Base.isPlainObject(arg) ? arg : null; } return source; }, getNamed: function(list, name) { var source = this.getSource(list); if (source) { return name ? source[name] : list.__filtered || source; } }, hasNamed: function(list, name) { return !!this.getNamed(list, name); }, filter: function(dest, source, exclude, prioritize) { var processed; function handleKey(key) { if (!(exclude && key in exclude) && !(processed && key in processed)) { var value = source[key]; if (value !== undefined) dest[key] = value; } } if (prioritize) { var keys = {}; for (var i = 0, key, l = prioritize.length; i < l; i++) { if ((key = prioritize[i]) in source) { handleKey(key); keys[key] = true; } } processed = keys; } Object.keys(source.__unfiltered || source).forEach(handleKey); return dest; }, isPlainValue: function(obj, asString) { return Base.isPlainObject(obj) || Array.isArray(obj) || asString && typeof obj === 'string'; }, serialize: function(obj, options, compact, dictionary) { options = options || {}; var isRoot = !dictionary, res; if (isRoot) { options.formatter = new Formatter(options.precision); dictionary = { length: 0, definitions: {}, references: {}, add: function(item, create) { var id = '#' + item._id, ref = this.references[id]; if (!ref) { this.length++; var res = create.call(item), name = item._class; if (name && res[0] !== name) res.unshift(name); this.definitions[id] = res; ref = this.references[id] = [id]; } return ref; } }; } if (obj && obj._serialize) { res = obj._serialize(options, dictionary); var name = obj._class; if (name && !obj._compactSerialize && (isRoot || !compact) && res[0] !== name) { res.unshift(name); } } else if (Array.isArray(obj)) { res = []; for (var i = 0, l = obj.length; i < l; i++) res[i] = Base.serialize(obj[i], options, compact, dictionary); } else if (Base.isPlainObject(obj)) { res = {}; var keys = Object.keys(obj); for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; res[key] = Base.serialize(obj[key], options, compact, dictionary); } } else if (typeof obj === 'number') { res = options.formatter.number(obj, options.precision); } else { res = obj; } return isRoot && dictionary.length > 0 ? [['dictionary', dictionary.definitions], res] : res; }, deserialize: function(json, create, _data, _setDictionary, _isRoot) { var res = json, isFirst = !_data, hasDictionary = isFirst && json && json.length && json[0][0] === 'dictionary'; _data = _data || {}; if (Array.isArray(json)) { var type = json[0], isDictionary = type === 'dictionary'; if (json.length == 1 && /^#/.test(type)) { return _data.dictionary[type]; } type = Base.exports[type]; res = []; for (var i = type ? 1 : 0, l = json.length; i < l; i++) { res.push(Base.deserialize(json[i], create, _data, isDictionary, hasDictionary)); } if (type) { var args = res; if (create) { res = create(type, args, isFirst || _isRoot); } else { res = new type(args); } } } else if (Base.isPlainObject(json)) { res = {}; if (_setDictionary) _data.dictionary = res; for (var key in json) res[key] = Base.deserialize(json[key], create, _data); } return hasDictionary ? res[1] : res; }, exportJSON: function(obj, options) { var json = Base.serialize(obj, options); return options && options.asString == false ? json : JSON.stringify(json); }, importJSON: function(json, target) { return Base.deserialize( typeof json === 'string' ? JSON.parse(json) : json, function(ctor, args, isRoot) { var useTarget = isRoot && target && target.constructor === ctor, obj = useTarget ? target : Base.create(ctor.prototype); if (args.length === 1 && obj instanceof Item && (useTarget || !(obj instanceof Layer))) { var arg = args[0]; if (Base.isPlainObject(arg)) { arg.insert = false; if (useTarget) { args = args.concat([{ insert: true }]); } } } (useTarget ? obj.set : ctor).apply(obj, args); if (useTarget) target = null; return obj; }); }, push: function(list, items) { var itemsLength = items.length; if (itemsLength < 4096) { list.push.apply(list, items); } else { var startLength = list.length; list.length += itemsLength; for (var i = 0; i < itemsLength; i++) { list[startLength + i] = items[i]; } } return list; }, splice: function(list, items, index, remove) { var amount = items && items.length, append = index === undefined; index = append ? list.length : index; if (index > list.length) index = list.length; for (var i = 0; i < amount; i++) items[i]._index = index + i; if (append) { Base.push(list, items); return []; } else { var args = [index, remove]; if (items) Base.push(args, items); var removed = list.splice.apply(list, args); for (var i = 0, l = removed.length; i < l; i++) removed[i]._index = undefined; for (var i = index + amount, l = list.length; i < l; i++) list[i]._index = i; return removed; } }, capitalize: function(str) { return str.replace(/\b[a-z]/g, function(match) { return match.toUpperCase(); }); }, camelize: function(str) { return str.replace(/-(.)/g, function(match, chr) { return chr.toUpperCase(); }); }, hyphenate: function(str) { return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); } }}); var Emitter = { on: function(type, func) { if (typeof type !== 'string') { Base.each(type, function(value, key) { this.on(key, value); }, this); } else { var types = this._eventTypes, entry = types && types[type], handlers = this._callbacks = this._callbacks || {}; handlers = handlers[type] = handlers[type] || []; if (handlers.indexOf(func) === -1) { handlers.push(func); if (entry && entry.install && handlers.length === 1) entry.install.call(this, type); } } return this; }, off: function(type, func) { if (typeof type !== 'string') { Base.each(type, function(value, key) { this.off(key, value); }, this); return; } var types = this._eventTypes, entry = types && types[type], handlers = this._callbacks && this._callbacks[type], index; if (handlers) { if (!func || (index = handlers.indexOf(func)) !== -1 && handlers.length === 1) { if (entry && entry.uninstall) entry.uninstall.call(this, type); delete this._callbacks[type]; } else if (index !== -1) { handlers.splice(index, 1); } } return this; }, once: function(type, func) { return this.on(type, function handler() { func.apply(this, arguments); this.off(type, handler); }); }, emit: function(type, event) { var handlers = this._callbacks && this._callbacks[type]; if (!handlers) return false; var args = Base.slice(arguments, 1), setTarget = event && event.target && !event.currentTarget; handlers = handlers.slice(); if (setTarget) event.currentTarget = this; for (var i = 0, l = handlers.length; i < l; i++) { if (handlers[i].apply(this, args) == false) { if (event && event.stop) event.stop(); break; } } if (setTarget) delete event.currentTarget; return true; }, responds: function(type) { return !!(this._callbacks && this._callbacks[type]); }, attach: '#on', detach: '#off', fire: '#emit', _installEvents: function(install) { var types = this._eventTypes, handlers = this._callbacks, key = install ? 'install' : 'uninstall'; if (types) { for (var type in handlers) { if (handlers[type].length > 0) { var entry = types[type], func = entry && entry[key]; if (func) func.call(this, type); } } } }, statics: { inject: function inject(src) { var events = src._events; if (events) { var types = {}; Base.each(events, function(entry, key) { var isString = typeof entry === 'string', name = isString ? entry : key, part = Base.capitalize(name), type = name.substring(2).toLowerCase(); types[type] = isString ? {} : entry; name = '_' + name; src['get' + part] = function() { return this[name]; }; src['set' + part] = function(func) { var prev = this[name]; if (prev) this.off(type, prev); if (func) this.on(type, func); this[name] = func; }; }); src._eventTypes = types; } return inject.base.apply(this, arguments); } } }; var PaperScope = Base.extend({ _class: 'PaperScope', initialize: function PaperScope() { paper = this; this.settings = new Base({ applyMatrix: true, insertItems: true, handleSize: 4, hitTolerance: 0 }); this.project = null; this.projects = []; this.tools = []; this._id = PaperScope._id++; PaperScope._scopes[this._id] = this; var proto = PaperScope.prototype; if (!this.support) { var ctx = CanvasProvider.getContext(1, 1) || {}; proto.support = { nativeDash: 'setLineDash' in ctx || 'mozDash' in ctx, nativeBlendModes: BlendMode.nativeModes }; CanvasProvider.release(ctx); } if (!this.agent) { var user = self.navigator.userAgent.toLowerCase(), os = (/(darwin|win|mac|linux|freebsd|sunos)/.exec(user)||[])[0], platform = os === 'darwin' ? 'mac' : os, agent = proto.agent = proto.browser = { platform: platform }; if (platform) agent[platform] = true; user.replace( /(opera|chrome|safari|webkit|firefox|msie|trident|atom|node|jsdom)\/?\s*([.\d]+)(?:.*version\/([.\d]+))?(?:.*rv\:v?([.\d]+))?/g, function(match, n, v1, v2, rv) { if (!agent.chrome) { var v = n === 'opera' ? v2 : /^(node|trident)$/.test(n) ? rv : v1; agent.version = v; agent.versionNumber = parseFloat(v); n = { trident: 'msie', jsdom: 'node' }[n] || n; agent.name = n; agent[n] = true; } } ); if (agent.chrome) delete agent.webkit; if (agent.atom) delete agent.chrome; } }, version: "0.12.12", getView: function() { var project = this.project; return project && project._view; }, getPaper: function() { return this; }, execute: function(code, options) { }, install: function(scope) { var that = this; Base.each(['project', 'view', 'tool'], function(key) { Base.define(scope, key, { configurable: true, get: function() { return that[key]; } }); }); for (var key in this) if (!/^_/.test(key) && this[key]) scope[key] = this[key]; }, setup: function(element) { paper = this; this.project = new Project(element); return this; }, createCanvas: function(width, height) { return CanvasProvider.getCanvas(width, height); }, activate: function() { paper = this; }, clear: function() { var projects = this.projects, tools = this.tools; for (var i = projects.length - 1; i >= 0; i--) projects[i].remove(); for (var i = tools.length - 1; i >= 0; i--) tools[i].remove(); }, remove: function() { this.clear(); delete PaperScope._scopes[this._id]; }, statics: new function() { function handleAttribute(name) { name += 'Attribute'; return function(el, attr) { return el[name](attr) || el[name]('data-paper-' + attr); }; } return { _scopes: {}, _id: 0, get: function(id) { return this._scopes[id] || null; }, getAttribute: handleAttribute('get'), hasAttribute: handleAttribute('has') }; } }); var PaperScopeItem = Base.extend(Emitter, { initialize: function(activate) { this._scope = paper; this._index = this._scope[this._list].push(this) - 1; if (activate || !this._scope[this._reference]) this.activate(); }, activate: function() { if (!this._scope) return false; var prev = this._scope[this._reference]; if (prev && prev !== this) prev.emit('deactivate'); this._scope[this._reference] = this; this.emit('activate', prev); return true; }, isActive: function() { return this._scope[this._reference] === this; }, remove: function() { if (this._index == null) return false; Base.splice(this._scope[this._list], null, this._index, 1); if (this._scope[this._reference] == this) this._scope[this._reference] = null; this._scope = null; return true; }, getView: function() { return this._scope.getView(); } }); var CollisionDetection = { findItemBoundsCollisions: function(items1, items2, tolerance) { function getBounds(items) { var bounds = new Array(items.length); for (var i = 0; i < items.length; i++) { var rect = items[i].getBounds(); bounds[i] = [rect.left, rect.top, rect.right, rect.bottom]; } return bounds; } var bounds1 = getBounds(items1), bounds2 = !items2 || items2 === items1 ? bounds1 : getBounds(items2); return this.findBoundsCollisions(bounds1, bounds2, tolerance || 0); }, findCurveBoundsCollisions: function(curves1, curves2, tolerance, bothAxis) { function getBounds(curves) { var min = Math.min, max = Math.max, bounds = new Array(curves.length); for (var i = 0; i < curves.length; i++) { var v = curves[i]; bounds[i] = [ min(v[0], v[2], v[4], v[6]), min(v[1], v[3], v[5], v[7]), max(v[0], v[2], v[4], v[6]), max(v[1], v[3], v[5], v[7]) ]; } return bounds; } var bounds1 = getBounds(curves1), bounds2 = !curves2 || curves2 === curves1 ? bounds1 : getBounds(curves2); if (bothAxis) { var hor = this.findBoundsCollisions( bounds1, bounds2, tolerance || 0, false, true), ver = this.findBoundsCollisions( bounds1, bounds2, tolerance || 0, true, true), list = []; for (var i = 0, l = hor.length; i < l; i++) { list[i] = { hor: hor[i], ver: ver[i] }; } return list; } return this.findBoundsCollisions(bounds1, bounds2, tolerance || 0); }, findBoundsCollisions: function(boundsA, boundsB, tolerance, sweepVertical, onlySweepAxisCollisions) { var self = !boundsB || boundsA === boundsB, allBounds = self ? boundsA : boundsA.concat(boundsB), lengthA = boundsA.length, lengthAll = allBounds.length; function binarySearch(indices, coord, value) { var lo = 0, hi = indices.length; while (lo < hi) { var mid = (hi + lo) >>> 1; if (allBounds[indices[mid]][coord] < value) { lo = mid + 1; } else { hi = mid; } } return lo - 1; } var pri0 = sweepVertical ? 1 : 0, pri1 = pri0 + 2, sec0 = sweepVertical ? 0 : 1, sec1 = sec0 + 2; var allIndicesByPri0 = new Array(lengthAll); for (var i = 0; i < lengthAll; i++) { allIndicesByPri0[i] = i; } allIndicesByPri0.sort(function(i1, i2) { return allBounds[i1][pri0] - allBounds[i2][pri0]; }); var activeIndicesByPri1 = [], allCollisions = new Array(lengthA); for (var i = 0; i < lengthAll; i++) { var curIndex = allIndicesByPri0[i], curBounds = allBounds[curIndex], origIndex = self ? curIndex : curIndex - lengthA, isCurrentA = curIndex < lengthA, isCurrentB = self || !isCurrentA, curCollisions = isCurrentA ? [] : null; if (activeIndicesByPri1.length) { var pruneCount = binarySearch(activeIndicesByPri1, pri1, curBounds[pri0] - tolerance) + 1; activeIndicesByPri1.splice(0, pruneCount); if (self && onlySweepAxisCollisions) { curCollisions = curCollisions.concat(activeIndicesByPri1); for (var j = 0; j < activeIndicesByPri1.length; j++) { var activeIndex = activeIndicesByPri1[j]; allCollisions[activeIndex].push(origIndex); } } else { var curSec1 = curBounds[sec1], curSec0 = curBounds[sec0]; for (var j = 0; j < activeIndicesByPri1.length; j++) { var activeIndex = activeIndicesByPri1[j], activeBounds = allBounds[activeIndex], isActiveA = activeIndex < lengthA, isActiveB = self || activeIndex >= lengthA; if ( onlySweepAxisCollisions || ( isCurrentA && isActiveB || isCurrentB && isActiveA ) && ( curSec1 >= activeBounds[sec0] - tolerance && curSec0 <= activeBounds[sec1] + tolerance ) ) { if (isCurrentA && isActiveB) { curCollisions.push( self ? activeIndex : activeIndex - lengthA); } if (isCurrentB && isActiveA) { allCollisions[activeIndex].push(origIndex); } } } } } if (isCurrentA) { if (boundsA === boundsB) { curCollisions.push(curIndex); } allCollisions[curIndex] = curCollisions; } if (activeIndicesByPri1.length) { var curPri1 = curBounds[pri1], index = binarySearch(activeIndicesByPri1, pri1, curPri1); activeIndicesByPri1.splice(index + 1, 0, curIndex); } else { activeIndicesByPri1.push(curIndex); } } for (var i = 0; i < allCollisions.length; i++) { var collisions = allCollisions[i]; if (collisions) { collisions.sort(function(i1, i2) { return i1 - i2; }); } } return allCollisions; } }; var Formatter = Base.extend({ initialize: function(precision) { this.precision = Base.pick(precision, 5); this.multiplier = Math.pow(10, this.precision); }, number: function(val) { return this.precision < 16 ? Math.round(val * this.multiplier) / this.multiplier : val; }, pair: function(val1, val2, separator) { return this.number(val1) + (separator || ',') + this.number(val2); }, point: function(val, separator) { return this.number(val.x) + (separator || ',') + this.number(val.y); }, size: function(val, separator) { return this.number(val.width) + (separator || ',') + this.number(val.height); }, rectangle: function(val, separator) { return this.point(val, separator) + (separator || ',') + this.size(val, separator); } }); Formatter.instance = new Formatter(); var Numerical = new function() { var abscissas = [ [ 0.5773502691896257645091488], [0,0.7745966692414833770358531], [ 0.3399810435848562648026658,0.8611363115940525752239465], [0,0.5384693101056830910363144,0.9061798459386639927976269], [ 0.2386191860831969086305017,0.6612093864662645136613996,0.9324695142031520278123016], [0,0.4058451513773971669066064,0.7415311855993944398638648,0.9491079123427585245261897], [ 0.1834346424956498049394761,0.5255324099163289858177390,0.7966664774136267395915539,0.9602898564975362316835609], [0,0.3242534234038089290385380,0.6133714327005903973087020,0.8360311073266357942994298,0.9681602395076260898355762], [ 0.1488743389816312108848260,0.4333953941292471907992659,0.6794095682990244062343274,0.8650633666889845107320967,0.9739065285171717200779640], [0,0.2695431559523449723315320,0.5190961292068118159257257,0.7301520055740493240934163,0.8870625997680952990751578,0.9782286581460569928039380], [ 0.1252334085114689154724414,0.3678314989981801937526915,0.5873179542866174472967024,0.7699026741943046870368938,0.9041172563704748566784659,0.9815606342467192506905491], [0,0.2304583159551347940655281,0.4484927510364468528779129,0.6423493394403402206439846,0.8015780907333099127942065,0.9175983992229779652065478,0.9841830547185881494728294], [ 0.1080549487073436620662447,0.3191123689278897604356718,0.5152486363581540919652907,0.6872929048116854701480198,0.8272013150697649931897947,0.9284348836635735173363911,0.9862838086968123388415973], [0,0.2011940939974345223006283,0.3941513470775633698972074,0.5709721726085388475372267,0.7244177313601700474161861,0.8482065834104272162006483,0.9372733924007059043077589,0.9879925180204854284895657], [ 0.0950125098376374401853193,0.2816035507792589132304605,0.4580167776572273863424194,0.6178762444026437484466718,0.7554044083550030338951012,0.8656312023878317438804679,0.9445750230732325760779884,0.9894009349916499325961542] ]; var weights = [ [1], [0.8888888888888888888888889,0.5555555555555555555555556], [0.6521451548625461426269361,0.3478548451374538573730639], [0.5688888888888888888888889,0.4786286704993664680412915,0.2369268850561890875142640], [0.4679139345726910473898703,0.3607615730481386075698335,0.1713244923791703450402961], [0.4179591836734693877551020,0.3818300505051189449503698,0.2797053914892766679014678,0.1294849661688696932706114], [0.3626837833783619829651504,0.3137066458778872873379622,0.2223810344533744705443560,0.1012285362903762591525314], [0.3302393550012597631645251,0.3123470770400028400686304,0.2606106964029354623187429,0.1806481606948574040584720,0.0812743883615744119718922], [0.2955242247147528701738930,0.2692667193099963550912269,0.2190863625159820439955349,0.1494513491505805931457763,0.0666713443086881375935688], [0.2729250867779006307144835,0.2628045445102466621806889,0.2331937645919904799185237,0.1862902109277342514260976,0.1255803694649046246346943,0.0556685671161736664827537], [0.2491470458134027850005624,0.2334925365383548087608499,0.2031674267230659217490645,0.1600783285433462263346525,0.1069393259953184309602547,0.0471753363865118271946160], [0.2325515532308739101945895,0.2262831802628972384120902,0.2078160475368885023125232,0.1781459807619457382800467,0.1388735102197872384636018,0.0921214998377284479144218,0.0404840047653158795200216], [0.2152638534631577901958764,0.2051984637212956039659241,0.1855383974779378137417166,0.1572031671581935345696019,0.1215185706879031846894148,0.0801580871597602098056333,0.0351194603317518630318329], [0.2025782419255612728806202,0.1984314853271115764561183,0.1861610000155622110268006,0.1662692058169939335532009,0.1395706779261543144478048,0.1071592204671719350118695,0.0703660474881081247092674,0.0307532419961172683546284], [0.1894506104550684962853967,0.1826034150449235888667637,0.1691565193950025381893121,0.1495959888165767320815017,0.1246289712555338720524763,0.0951585116824927848099251,0.0622535239386478928628438,0.0271524594117540948517806] ]; var abs = Math.abs, sqrt = Math.sqrt, pow = Math.pow, log2 = Math.log2 || function(x) { return Math.log(x) * Math.LOG2E; }, EPSILON = 1e-12, MACHINE_EPSILON = 1.12e-16; function clamp(value, min, max) { return value < min ? min : value > max ? max : value; } function getDiscriminant(a, b, c) { function split(v) { var x = v * 134217729, y = v - x, hi = y + x, lo = v - hi; return [hi, lo]; } var D = b * b - a * c, E = b * b + a * c; if (abs(D) * 3 < E) { var ad = split(a), bd = split(b), cd = split(c), p = b * b, dp = (bd[0] * bd[0] - p + 2 * bd[0] * bd[1]) + bd[1] * bd[1], q = a * c, dq = (ad[0] * cd[0] - q + ad[0] * cd[1] + ad[1] * cd[0]) + ad[1] * cd[1]; D = (p - q) + (dp - dq); } return D; } function getNormalizationFactor() { var norm = Math.max.apply(Math, arguments); return norm && (norm < 1e-8 || norm > 1e8) ? pow(2, -Math.round(log2(norm))) : 0; } return { EPSILON: EPSILON, MACHINE_EPSILON: MACHINE_EPSILON, CURVETIME_EPSILON: 1e-8, GEOMETRIC_EPSILON: 1e-7, TRIGONOMETRIC_EPSILON: 1e-8, KAPPA: 4 * (sqrt(2) - 1) / 3, isZero: function(val) { return val >= -EPSILON && val <= EPSILON; }, isMachineZero: function(val) { return val >= -MACHINE_EPSILON && val <= MACHINE_EPSILON; }, clamp: clamp, integrate: function(f, a, b, n) { var x = abscissas[n - 2], w = weights[n - 2], A = (b - a) * 0.5, B = A + a, i = 0, m = (n + 1) >> 1, sum = n & 1 ? w[i++] * f(B) : 0; while (i < m) { var Ax = A * x[i]; sum += w[i++] * (f(B + Ax) + f(B - Ax)); } return A * sum; }, findRoot: function(f, df, x, a, b, n, tolerance) { for (var i = 0; i < n; i++) { var fx = f(x), dx = fx / df(x), nx = x - dx; if (abs(dx) < tolerance) { x = nx; break; } if (fx > 0) { b = x; x = nx <= a ? (a + b) * 0.5 : nx; } else { a = x; x = nx >= b ? (a + b) * 0.5 : nx; } } return clamp(x, a, b); }, solveQuadratic: function(a, b, c, roots, min, max) { var x1, x2 = Infinity; if (abs(a) < EPSILON) { if (abs(b) < EPSILON) return abs(c) < EPSILON ? -1 : 0; x1 = -c / b; } else { b *= -0.5; var D = getDiscriminant(a, b, c); if (D && abs(D) < MACHINE_EPSILON) { var f = getNormalizationFactor(abs(a), abs(b), abs(c)); if (f) { a *= f; b *= f; c *= f; D = getDiscriminant(a, b, c); } } if (D >= -MACHINE_EPSILON) { var Q = D < 0 ? 0 : sqrt(D), R = b + (b < 0 ? -Q : Q); if (R === 0) { x1 = c / a; x2 = -x1; } else { x1 = R / a; x2 = c / R; } } } var count = 0, boundless = min == null, minB = min - EPSILON, maxB = max + EPSILON; if (isFinite(x1) && (boundless || x1 > minB && x1 < maxB)) roots[count++] = boundless ? x1 : clamp(x1, min, max); if (x2 !== x1 && isFinite(x2) && (boundless || x2 > minB && x2 < maxB)) roots[count++] = boundless ? x2 : clamp(x2, min, max); return count; }, solveCubic: function(a, b, c, d, roots, min, max) { var f = getNormalizationFactor(abs(a), abs(b), abs(c), abs(d)), x, b1, c2, qd, q; if (f) { a *= f; b *= f; c *= f; d *= f; } function evaluate(x0) { x = x0; var tmp = a * x; b1 = tmp + b; c2 = b1 * x + c; qd = (tmp + b1) * x + c2; q = c2 * x + d; } if (abs(a) < EPSILON) { a = b; b1 = c; c2 = d; x = Infinity; } else if (abs(d) < EPSILON) { b1 = b; c2 = c; x = 0; } else { evaluate(-(b / a) / 3); var t = q / a, r = pow(abs(t), 1/3), s = t < 0 ? -1 : 1, td = -qd / a, rd = td > 0 ? 1.324717957244746 * Math.max(r, sqrt(td)) : r, x0 = x - s * rd; if (x0 !== x) { do { evaluate(x0); x0 = qd === 0 ? x : x - q / qd / (1 + MACHINE_EPSILON); } while (s * x0 > s * x); if (abs(a) * x * x > abs(d / x)) { c2 = -d / x; b1 = (c2 - c) / x; } } } var count = Numerical.solveQuadratic(a, b1, c2, roots, min, max), boundless = min == null; if (isFinite(x) && (count === 0 || count > 0 && x !== roots[0] && x !== roots[1]) && (boundless || x > min - EPSILON && x < max + EPSILON)) roots[count++] = boundless ? x : clamp(x, min, max); return count; } }; }; var UID = { _id: 1, _pools: {}, get: function(name) { if (name) { var pool = this._pools[name]; if (!pool) pool = this._pools[name] = { _id: 1 }; return pool._id++; } else { return this._id++; } } }; var Point = Base.extend({ _class: 'Point', _readIndex: true, initialize: function Point(arg0, arg1) { var type = typeof arg0, reading = this.__read, read = 0; if (type === 'number') { var hasY = typeof arg1 === 'number'; this._set(arg0, hasY ? arg1 : arg0); if (reading) read = hasY ? 2 : 1; } else if (type === 'undefined' || arg0 === null) { this._set(0, 0); if (reading) read = arg0 === null ? 1 : 0; } else { var obj = type === 'string' ? arg0.split(/[\s,]+/) || [] : arg0; read = 1; if (Array.isArray(obj)) { this._set(+obj[0], +(obj.length > 1 ? obj[1] : obj[0])); } else if ('x' in obj) { this._set(obj.x || 0, obj.y || 0); } else if ('width' in obj) { this._set(obj.width || 0, obj.height || 0); } else if ('angle' in obj) { this._set(obj.length || 0, 0); this.setAngle(obj.angle || 0); } else { this._set(0, 0); read = 0; } } if (reading) this.__read = read; return this; }, set: '#initialize', _set: function(x, y) { this.x = x; this.y = y; return this; }, equals: function(point) { return this === point || point && (this.x === point.x && this.y === point.y || Array.isArray(point) && this.x === point[0] && this.y === point[1]) || false; }, clone: function() { return new Point(this.x, this.y); }, toString: function() { var f = Formatter.instance; return '{ x: ' + f.number(this.x) + ', y: ' + f.number(this.y) + ' }'; }, _serialize: function(options) { var f = options.formatter; return [f.number(this.x), f.number(this.y)]; }, getLength: function() { return Math.sqrt(this.x * this.x + this.y * this.y); }, setLength: function(length) { if (this.isZero()) { var angle = this._angle || 0; this._set( Math.cos(angle) * length, Math.sin(angle) * length ); } else { var scale = length / this.getLength(); if (Numerical.isZero(scale)) this.getAngle(); this._set( this.x * scale, this.y * scale ); } }, getAngle: function() { return this.getAngleInRadians.apply(this, arguments) * 180 / Math.PI; }, setAngle: function(angle) { this.setAngleInRadians.call(this, angle * Math.PI / 180); }, getAngleInDegrees: '#getAngle', setAngleInDegrees: '#setAngle', getAngleInRadians: function() { if (!arguments.length) { return this.isZero() ? this._angle || 0 : this._angle = Math.atan2(this.y, this.x); } else { var point = Point.read(arguments), div = this.getLength() * point.getLength(); if (Numerical.isZero(div)) { return NaN; } else { var a = this.dot(point) / div; return Math.acos(a < -1 ? -1 : a > 1 ? 1 : a); } } }, setAngleInRadians: function(angle) { this._angle = angle; if (!this.isZero()) { var length = this.getLength(); this._set( Math.cos(angle) * length, Math.sin(angle) * length ); } }, getQuadrant: function() { return this.x >= 0 ? this.y >= 0 ? 1 : 4 : this.y >= 0 ? 2 : 3; } }, { beans: false, getDirectedAngle: function() { var point = Point.read(arguments); return Math.atan2(this.cross(point), this.dot(point)) * 180 / Math.PI; }, getDistance: function() { var args = arguments, point = Point.read(args), x = point.x - this.x, y = point.y - this.y, d = x * x + y * y, squared = Base.read(args); return squared ? d : Math.sqrt(d); }, normalize: function(length) { if (length === undefined) length = 1; var current = this.getLength(), scale = current !== 0 ? length / current : 0, point = new Point(this.x * scale, this.y * scale); if (scale >= 0) point._angle = this._angle; return point; }, rotate: function(angle, center) { if (angle === 0) return this.clone(); angle = angle * Math.PI / 180; var point = center ? this.subtract(center) : this, sin = Math.sin(angle), cos = Math.cos(angle); point = new Point( point.x * cos - point.y * sin, point.x * sin + point.y * cos ); return center ? point.add(center) : point; }, transform: function(matrix) { return matrix ? matrix._transformPoint(this) : this; }, add: function() { var point = Point.read(arguments); return new Point(this.x + point.x, this.y + point.y); }, subtract: function() { var point = Point.read(arguments); return new Point(this.x - point.x, this.y - point.y); }, multiply: function() { var point = Point.read(arguments); return new Point(this.x * point.x, this.y * point.y); }, divide: function() { var point = Point.read(arguments); return new Point(this.x / point.x, this.y / point.y); }, modulo: function() { var point = Point.read(arguments); return new Point(this.x % point.x, this.y % point.y); }, negate: function() { return new Point(-this.x, -this.y); }, isInside: function() { return Rectangle.read(arguments).contains(this); }, isClose: function() { var args = arguments, point = Point.read(args), tolerance = Base.read(args); return this.getDistance(point) <= tolerance; }, isCollinear: function() { var point = Point.read(arguments); return Point.isCollinear(this.x, this.y, point.x, point.y); }, isColinear: '#isCollinear', isOrthogonal: function() { var point = Point.read(arguments); return Point.isOrthogonal(this.x, this.y, point.x, point.y); }, isZero: function() { var isZero = Numerical.isZero; return isZero(this.x) && isZero(this.y); }, isNaN: function() { return isNaN(this.x) || isNaN(this.y); }, isInQuadrant: function(q) { return this.x * (q > 1 && q < 4 ? -1 : 1) >= 0 && this.y * (q > 2 ? -1 : 1) >= 0; }, dot: function() { var point = Point.read(arguments); return this.x * point.x + this.y * point.y; }, cross: function() { var point = Point.read(arguments); return this.x * point.y - this.y * point.x; }, project: function() { var point = Point.read(arguments), scale = point.isZero() ? 0 : this.dot(point) / point.dot(point); return new Point( point.x * scale, point.y * scale ); }, statics: { min: function() { var args = arguments, point1 = Point.read(args), point2 = Point.read(args); return new Point( Math.min(point1.x, point2.x), Math.min(point1.y, point2.y) ); }, max: function() { var args = arguments, point1 = Point.read(args), point2 = Point.read(args); return new Point( Math.max(point1.x, point2.x), Math.max(point1.y, point2.y) ); }, random: function() { return new Point(Math.random(), Math.random()); }, isCollinear: function(x1, y1, x2, y2) { return Math.abs(x1 * y2 - y1 * x2) <= Math.sqrt((x1 * x1 + y1 * y1) * (x2 * x2 + y2 * y2)) * 1e-8; }, isOrthogonal: function(x1, y1, x2, y2) { return Math.abs(x1 * x2 + y1 * y2) <= Math.sqrt((x1 * x1 + y1 * y1) * (x2 * x2 + y2 * y2)) * 1e-8; } } }, Base.each(['round', 'ceil', 'floor', 'abs'], function(key) { var op = Math[key]; this[key] = function() { return new Point(op(this.x), op(this.y)); }; }, {})); var LinkedPoint = Point.extend({ initialize: function Point(x, y, owner, setter) { this._x = x; this._y = y; this._owner = owner; this._setter = setter; }, _set: function(x, y, _dontNotify) { this._x = x; this._y = y; if (!_dontNotify) this._owner[this._setter](this); return this; }, getX: function() { return this._x; }, setX: function(x) { this._x = x; this._owner[this._setter](this); }, getY: function() { return this._y; }, setY: function(y) { this._y = y; this._owner[this._setter](this); }, isSelected: function() { return !!(this._owner._selection & this._getSelection()); }, setSelected: function(selected) { this._owner._changeSelection(this._getSelection(), selected); }, _getSelection: function() { return this._setter === 'setPosition' ? 4 : 0; } }); var Size = Base.extend({ _class: 'Size', _readIndex: true, initialize: function Size(arg0, arg1) { var type = typeof arg0, reading = this.__read, read = 0; if (type === 'number') { var hasHeight = typeof arg1 === 'number'; this._set(arg0, hasHeight ? arg1 : arg0); if (reading) read = hasHeight ? 2 : 1; } else if (type === 'undefined' || arg0 === null) { this._set(0, 0); if (reading) read = arg0 === null ? 1 : 0; } else { var obj = type === 'string' ? arg0.split(/[\s,]+/) || [] : arg0; read = 1; if (Array.isArray(obj)) { this._set(+obj[0], +(obj.length > 1 ? obj[1] : obj[0])); } else if ('width' in obj) { this._set(obj.width || 0, obj.height || 0); } else if ('x' in obj) { this._set(obj.x || 0, obj.y || 0); } else { this._set(0, 0); read = 0; } } if (reading) this.__read = read; return this; }, set: '#initialize', _set: function(width, height) { this.width = width; this.height = height; return this; }, equals: function(size) { return size === this || size && (this.width === size.width && this.height === size.height || Array.isArray(size) && this.width === size[0] && this.height === size[1]) || false; }, clone: function() { return new Size(this.width, this.height); }, toString: function() { var f = Formatter.instance; return '{ width: ' + f.number(this.width) + ', height: ' + f.number(this.height) + ' }'; }, _serialize: function(options) { var f = options.formatter; return [f.number(this.width), f.number(this.height)]; }, add: function() { var size = Size.read(arguments); return new Size(this.width + size.width, this.height + size.height); }, subtract: function() { var size = Size.read(arguments); return new Size(this.width - size.width, this.height - size.height); }, multiply: function() { var size = Size.read(arguments); return new Size(this.width * size.width, this.height * size.height); }, divide: function() { var size = Size.read(arguments); return new Size(this.width / size.width, this.height / size.height); }, modulo: function() { var size = Size.read(arguments); return new Size(this.width % size.width, this.height % size.height); }, negate: function() { return new Size(-this.width, -this.height); }, isZero: function() { var isZero = Numerical.isZero; return isZero(this.width) && isZero(this.height); }, isNaN: function() { return isNaN(this.width) || isNaN(this.height); }, statics: { min: function(size1, size2) { return new Size( Math.min(size1.width, size2.width), Math.min(size1.height, size2.height)); }, max: function(size1, size2) { return new Size( Math.max(size1.width, size2.width), Math.max(size1.height, size2.height)); }, random: function() { return new Size(Math.random(), Math.random()); } } }, Base.each(['round', 'ceil', 'floor', 'abs'], function(key) { var op = Math[key]; this[key] = function() { return new Size(op(this.width), op(this.height)); }; }, {})); var LinkedSize = Size.extend({ initialize: function Size(width, height, owner, setter) { this._width = width; this._height = height; this._owner = owner; this._setter = setter; }, _set: function(width, height, _dontNotify) { this._width = width; this._height = height; if (!_dontNotify) this._owner[this._setter](this); return this; }, getWidth: function() { return this._width; }, setWidth: function(width) { this._width = width; this._owner[this._setter](this); }, getHeight: function() { return this._height; }, setHeight: function(height) { this._height = height; this._owner[this._setter](this); } }); var Rectangle = Base.extend({ _class: 'Rectangle', _readIndex: true, beans: true, initialize: function Rectangle(arg0, arg1, arg2, arg3) { var args = arguments, type = typeof arg0, read; if (type === 'number') { this._set(arg0, arg1, arg2, arg3); read = 4; } else if (type === 'undefined' || arg0 === null) { this._set(0, 0, 0, 0); read = arg0 === null ? 1 : 0; } else if (args.length === 1) { if (Array.isArray(arg0)) { this._set.apply(this, arg0); read = 1; } else if (arg0.x !== undefined || arg0.width !== undefined) { this._set(arg0.x || 0, arg0.y || 0, arg0.width || 0, arg0.height || 0); read = 1; } else if (arg0.from === undefined && arg0.to === undefined) { this._set(0, 0, 0, 0); if (Base.readSupported(args, this)) { read = 1; } } } if (read === undefined) { var frm = Point.readNamed(args, 'from'), next = Base.peek(args), x = frm.x, y = frm.y, width, height; if (next && next.x !== undefined || Base.hasNamed(args, 'to')) { var to = Point.readNamed(args, 'to'); width = to.x - x; height = to.y - y; if (width < 0) { x = to.x; width = -width; } if (height < 0) { y = to.y; height = -height; } } else { var size = Size.read(args); width = size.width; height = size.height; } this._set(x, y, width, height); read = args.__index; } var filtered = args.__filtered; if (filtered) this.__filtered = filtered; if (this.__read) this.__read = read; return this; }, set: '#initialize', _set: function(x, y, width, height) { this.x = x; this.y = y; this.width = width; this.height = height; return this; }, clone: function() { return new Rectangle(this.x, this.y, this.width, this.height); }, equals: function(rect) { var rt = Base.isPlainValue(rect) ? Rectangle.read(arguments) : rect; return rt === this || rt && this.x === rt.x && this.y === rt.y && this.width === rt.width && this.height === rt.height || false; }, toString: function() { var f = Formatter.instance; return '{ x: ' + f.number(this.x) + ', y: ' + f.number(this.y) + ', width: ' + f.number(this.width) + ', height: ' + f.number(this.height) + ' }'; }, _serialize: function(options) { var f = options.formatter; return [f.number(this.x), f.number(this.y), f.number(this.width), f.number(this.height)]; }, getPoint: function(_dontLink) { var ctor = _dontLink ? Point : LinkedPoint; return new ctor(this.x, this.y, this, 'setPoint'); }, setPoint: function() { var point = Point.read(arguments); this.x = point.x; this.y = point.y; }, getSize: function(_dontLink) { var ctor = _dontLink ? Size : LinkedSize; return new ctor(this.width, this.height, this, 'setSize'); }, _fw: 1, _fh: 1, setSize: function() { var size = Size.read(arguments), sx = this._sx, sy = this._sy, w = size.width, h = size.height; if (sx) { this.x += (this.width - w) * sx; } if (sy) { this.y += (this.height - h) * sy; } this.width = w; this.height = h; this._fw = this._fh = 1; }, getLeft: function() { return this.x; }, setLeft: function(left) { if (!this._fw) { var amount = left - this.x; this.width -= this._sx === 0.5 ? amount * 2 : amount; } this.x = left; this._sx = this._fw = 0; }, getTop: function() { return this.y; }, setTop: function(top) { if (!this._fh) { var amount = top - this.y; this.height -= this._sy === 0.5 ? amount * 2 : amount; } this.y = top; this._sy = this._fh = 0; }, getRight: function() { return this.x + this.width; }, setRight: function(right) { if (!this._fw) { var amount = right - this.x; this.width = this._sx === 0.5 ? amount * 2 : amount; } this.x = right - this.width; this._sx = 1; this._fw = 0; }, getBottom: function() { return this.y + this.height; }, setBottom: function(bottom) { if (!this._fh) { var amount = bottom - this.y; this.height = this._sy === 0.5 ? amount * 2 : amount; } this.y = bottom - this.height; this._sy = 1; this._fh = 0; }, getCenterX: function() { return this.x + this.width / 2; }, setCenterX: function(x) { if (this._fw || this._sx === 0.5) { this.x = x - this.width / 2; } else { if (this._sx) { this.x += (x - this.x) * 2 * this._sx; } this.width = (x - this.x) * 2; } this._sx = 0.5; this._fw = 0; }, getCenterY: function() { return this.y + this.height / 2; }, setCenterY: function(y) { if (this._fh || this._sy === 0.5) { this.y = y - this.height / 2; } else { if (this._sy) { this.y += (y - this.y) * 2 * this._sy; } this.height = (y - this.y) * 2; } this._sy = 0.5; this._fh = 0; }, getCenter: function(_dontLink) { var ctor = _dontLink ? Point : LinkedPoint; return new ctor(this.getCenterX(), this.getCenterY(), this, 'setCenter'); }, setCenter: function() { var point = Point.read(arguments); this.setCenterX(point.x); this.setCenterY(point.y); return this; }, getArea: function() { return this.width * this.height; }, isEmpty: function() { return this.width === 0 || this.height === 0; }, contains: function(arg) { return arg && arg.width !== undefined || (Array.isArray(arg) ? arg : arguments).length === 4 ? this._containsRectangle(Rectangle.read(arguments)) : this._containsPoint(Point.read(arguments)); }, _containsPoint: function(point) { var x = point.x, y = point.y; return x >= this.x && y >= this.y && x <= this.x + this.width && y <= this.y + this.height; }, _containsRectangle: function(rect) { var x = rect.x, y = rect.y; return x >= this.x && y >= this.y && x + rect.width <= this.x + this.width && y + rect.height <= this.y + this.height; }, intersects: function() { var rect = Rectangle.read(arguments), epsilon = Base.read(arguments) || 0; return rect.x + rect.width > this.x - epsilon && rect.y + rect.height > this.y - epsilon && rect.x < this.x + this.width + epsilon && rect.y < this.y + this.height + epsilon; }, intersect: function() { var rect = Rectangle.read(arguments), x1 = Math.max(this.x, rect.x), y1 = Math.max(this.y, rect.y), x2 = Math.min(this.x + this.width, rect.x + rect.width), y2 = Math.min(this.y + this.height, rect.y + rect.height); return new Rectangle(x1, y1, x2 - x1, y2 - y1); }, unite: function() { var rect = Rectangle.read(arguments), x1 = Math.min(this.x, rect.x), y1 = Math.min(this.y, rect.y), x2 = Math.max(this.x + this.width, rect.x + rect.width), y2 = Math.max(this.y + this.height, rect.y + rect.height); return new Rectangle(x1, y1, x2 - x1, y2 - y1); }, include: function() { var point = Point.read(arguments); var x1 = Math.min(this.x, point.x), y1 = Math.min(this.y, point.y), x2 = Math.max(this.x + this.width, point.x), y2 = Math.max(this.y + this.height, point.y); return new Rectangle(x1, y1, x2 - x1, y2 - y1); }, expand: function() { var amount = Size.read(arguments), hor = amount.width, ver = amount.height; return new Rectangle(this.x - hor / 2, this.y - ver / 2, this.width + hor, this.height + ver); }, scale: function(hor, ver) { return this.expand(this.width * hor - this.width, this.height * (ver === undefined ? hor : ver) - this.height); } }, Base.each([ ['Top', 'Left'], ['Top', 'Right'], ['Bottom', 'Left'], ['Bottom', 'Right'], ['Left', 'Center'], ['Top', 'Center'], ['Right', 'Center'], ['Bottom', 'Center'] ], function(parts, index) { var part = parts.join(''), xFirst = /^[RL]/.test(part); if (index >= 4) parts[1] += xFirst ? 'Y' : 'X'; var x = parts[xFirst ? 0 : 1], y = parts[xFirst ? 1 : 0], getX = 'get' + x, getY = 'get' + y, setX = 'set' + x, setY = 'set' + y, get = 'get' + part, set = 'set' + part; this[get] = function(_dontLink) { var ctor = _dontLink ? Point : LinkedPoint; return new ctor(this[getX](), this[getY](), this, set); }; this[set] = function() { var point = Point.read(arguments); this[setX](point.x); this[setY](point.y); }; }, { beans: true } )); var LinkedRectangle = Rectangle.extend({ initialize: function Rectangle(x, y, width, height, owner, setter) { this._set(x, y, width, height, true); this._owner = owner; this._setter = setter; }, _set: function(x, y, width, height, _dontNotify) { this._x = x; this._y = y; this._width = width; this._height = height; if (!_dontNotify) this._owner[this._setter](this); return this; } }, new function() { var proto = Rectangle.prototype; return Base.each(['x', 'y', 'width', 'height'], function(key) { var part = Base.capitalize(key), internal = '_' + key; this['get' + part] = function() { return this[internal]; }; this['set' + part] = function(value) { this[internal] = value; if (!this._dontNotify) this._owner[this._setter](this); }; }, Base.each(['Point', 'Size', 'Center', 'Left', 'Top', 'Right', 'Bottom', 'CenterX', 'CenterY', 'TopLeft', 'TopRight', 'BottomLeft', 'BottomRight', 'LeftCenter', 'TopCenter', 'RightCenter', 'BottomCenter'], function(key) { var name = 'set' + key; this[name] = function() { this._dontNotify = true; proto[name].apply(this, arguments); this._dontNotify = false; this._owner[this._setter](this); }; }, { isSelected: function() { return !!(this._owner._selection & 2); }, setSelected: function(selected) { var owner = this._owner; if (owner._changeSelection) { owner._changeSelection(2, selected); } } }) ); }); var Matrix = Base.extend({ _class: 'Matrix', initialize: function Matrix(arg, _dontNotify) { var args = arguments, count = args.length, ok = true; if (count >= 6) { this._set.apply(this, args); } else if (count === 1 || count === 2) { if (arg instanceof Matrix) { this._set(arg._a, arg._b, arg._c, arg._d, arg._tx, arg._ty, _dontNotify); } else if (Array.isArray(arg)) { this._set.apply(this, _dontNotify ? arg.concat([_dontNotify]) : arg); } else { ok = false; } } else if (!count) { this.reset(); } else { ok = false; } if (!ok) { throw new Error('Unsupported matrix parameters'); } return this; }, set: '#initialize', _set: function(a, b, c, d, tx, ty, _dontNotify) { this._a = a; this._b = b; this._c = c; this._d = d; this._tx = tx; this._ty = ty; if (!_dontNotify) this._changed(); return this; }, _serialize: function(options, dictionary) { return Base.serialize(this.getValues(), options, true, dictionary); }, _changed: function() { var owner = this._owner; if (owner) { if (owner._applyMatrix) { owner.transform(null, true); } else { owner._changed(25); } } }, clone: function() { return new Matrix(this._a, this._b, this._c, this._d, this._tx, this._ty); }, equals: function(mx) { return mx === this || mx && this._a === mx._a && this._b === mx._b && this._c === mx._c && this._d === mx._d && this._tx === mx._tx && this._ty === mx._ty; }, toString: function() { var f = Formatter.instance; return '[[' + [f.number(this._a), f.number(this._c), f.number(this._tx)].join(', ') + '], [' + [f.number(this._b), f.number(this._d), f.number(this._ty)].join(', ') + ']]'; }, reset: function(_dontNotify) { this._a = this._d = 1; this._b = this._c = this._tx = this._ty = 0; if (!_dontNotify) this._changed(); return this; }, apply: function(recursively, _setApplyMatrix) { var owner = this._owner; if (owner) { owner.transform(null, Base.pick(recursively, true), _setApplyMatrix); return this.isIdentity(); } return false; }, translate: function() { var point = Point.read(arguments), x = point.x, y = point.y; this._tx += x * this._a + y * this._c; this._ty += x * this._b + y * this._d; this._changed(); return this; }, scale: function() { var args = arguments, scale = Point.read(args), center = Point.read(args, 0, { readNull: true }); if (center) this.translate(center); this._a *= scale.x; this._b *= scale.x; this._c *= scale.y; this._d *= scale.y; if (center) this.translate(center.negate()); this._changed(); return this; }, rotate: function(angle ) { angle *= Math.PI / 180; var center = Point.read(arguments, 1), x = center.x, y = center.y, cos = Math.cos(angle), sin = Math.sin(angle), tx = x - x * cos + y * sin, ty = y - x * sin - y * cos, a = this._a, b = this._b, c = this._c, d = this._d; this._a = cos * a + sin * c; this._b = cos * b + sin * d; this._c = -sin * a + cos * c; this._d = -sin * b + cos * d; this._tx += tx * a + ty * c; this._ty += tx * b + ty * d; this._changed(); return this; }, shear: function() { var args = arguments, shear = Point.read(args), center = Point.read(args, 0, { readNull: true }); if (center) this.translate(center); var a = this._a, b = this._b; this._a += shear.y * this._c; this._b += shear.y * this._d; this._c += shear.x * a; this._d += shear.x * b; if (center) this.translate(center.negate()); this._changed(); return this; }, skew: function() { var args = arguments, skew = Point.read(args), center = Point.read(args, 0, { readNull: true }), toRadians = Math.PI / 180, shear = new Point(Math.tan(skew.x * toRadians), Math.tan(skew.y * toRadians)); return this.shear(shear, center); }, append: function(mx, _dontNotify) { if (mx) { var a1 = this._a, b1 = this._b, c1 = this._c, d1 = this._d, a2 = mx._a, b2 = mx._c, c2 = mx._b, d2 = mx._d, tx2 = mx._tx, ty2 = mx._ty; this._a = a2 * a1 + c2 * c1; this._c = b2 * a1 + d2 * c1; this._b = a2 * b1 + c2 * d1; this._d = b2 * b1 + d2 * d1; this._tx += tx2 * a1 + ty2 * c1; this._ty += tx2 * b1 + ty2 * d1; if (!_dontNotify) this._changed(); } return this; }, prepend: function(mx, _dontNotify) { if (mx) { var a1 = this._a, b1 = this._b, c1 = this._c, d1 = this._d, tx1 = this._tx, ty1 = this._ty, a2 = mx._a, b2 = mx._c, c2 = mx._b, d2 = mx._d, tx2 = mx._tx, ty2 = mx._ty; this._a = a2 * a1 + b2 * b1; this._c = a2 * c1 + b2 * d1; this._b = c2 * a1 + d2 * b1; this._d = c2 * c1 + d2 * d1; this._tx = a2 * tx1 + b2 * ty1 + tx2; this._ty = c2 * tx1 + d2 * ty1 + ty2; if (!_dontNotify) this._changed(); } return this; }, appended: function(mx) { return this.clone().append(mx); }, prepended: function(mx) { return this.clone().prepend(mx); }, invert: function() { var a = this._a, b = this._b, c = this._c, d = this._d, tx = this._tx, ty = this._ty, det = a * d - b * c, res = null; if (det && !isNaN(det) && isFinite(tx) && isFinite(ty)) { this._a = d / det; this._b = -b / det; this._c = -c / det; this._d = a / det; this._tx = (c * ty - d * tx) / det; this._ty = (b * tx - a * ty) / det; res = this; } return res; }, inverted: function() { return this.clone().invert(); }, concatenate: '#append', preConcatenate: '#prepend', chain: '#appended', _shiftless: function() { return new Matrix(this._a, this._b, this._c, this._d, 0, 0); }, _orNullIfIdentity: function() { return this.isIdentity() ? null : this; }, isIdentity: function() { return this._a === 1 && this._b === 0 && this._c === 0 && this._d === 1 && this._tx === 0 && this._ty === 0; }, isInvertible: function() { var det = this._a * this._d - this._c * this._b; return det && !isNaN(det) && isFinite(this._tx) && isFinite(this._ty); }, isSingular: function() { return !this.isInvertible(); }, transform: function( src, dst, count) { return arguments.length < 3 ? this._transformPoint(Point.read(arguments)) : this._transformCoordinates(src, dst, count); }, _transformPoint: function(point, dest, _dontNotify) { var x = point.x, y = point.y; if (!dest) dest = new Point(); return dest._set( x * this._a + y * this._c + this._tx, x * this._b + y * this._d + this._ty, _dontNotify); }, _transformCoordinates: function(src, dst, count) { for (var i = 0, max = 2 * count; i < max; i += 2) { var x = src[i], y = src[i + 1]; dst[i] = x * this._a + y * this._c + this._tx; dst[i + 1] = x * this._b + y * this._d + this._ty; } return dst; }, _transformCorners: function(rect) { var x1 = rect.x, y1 = rect.y, x2 = x1 + rect.width, y2 = y1 + rect.height, coords = [ x1, y1, x2, y1, x2, y2, x1, y2 ]; return this._transformCoordinates(coords, coords, 4); }, _transformBounds: function(bounds, dest, _dontNotify) { var coords = this._transformCorners(bounds), min = coords.slice(0, 2), max = min.slice(); for (var i = 2; i < 8; i++) { var val = coords[i], j = i & 1; if (val < min[j]) { min[j] = val; } else if (val > max[j]) { max[j] = val; } } if (!dest) dest = new Rectangle(); return dest._set(min[0], min[1], max[0] - min[0], max[1] - min[1], _dontNotify); }, inverseTransform: function() { return this._inverseTransform(Point.read(arguments)); }, _inverseTransform: function(point, dest, _dontNotify) { var a = this._a, b = this._b, c = this._c, d = this._d, tx = this._tx, ty = this._ty, det = a * d - b * c, res = null; if (det && !isNaN(det) && isFinite(tx) && isFinite(ty)) { var x = point.x - this._tx, y = point.y - this._ty; if (!dest) dest = new Point(); res = dest._set( (x * d - y * c) / det, (y * a - x * b) / det, _dontNotify); } return res; }, decompose: function() { var a = this._a, b = this._b, c = this._c, d = this._d, det = a * d - b * c, sqrt = Math.sqrt, atan2 = Math.atan2, degrees = 180 / Math.PI, rotate, scale, skew; if (a !== 0 || b !== 0) { var r = sqrt(a * a + b * b); rotate = Math.acos(a / r) * (b > 0 ? 1 : -1); scale = [r, det / r]; skew = [atan2(a * c + b * d, r * r), 0]; } else if (c !== 0 || d !== 0) { var s = sqrt(c * c + d * d); rotate = Math.asin(c / s) * (d > 0 ? 1 : -1); scale = [det / s, s]; skew = [0, atan2(a * c + b * d, s * s)]; } else { rotate = 0; skew = scale = [0, 0]; } return { translation: this.getTranslation(), rotation: rotate * degrees, scaling: new Point(scale), skewing: new Point(skew[0] * degrees, skew[1] * degrees) }; }, getValues: function() { return [ this._a, this._b, this._c, this._d, this._tx, this._ty ]; }, getTranslation: function() { return new Point(this._tx, this._ty); }, getScaling: function() { return this.decompose().scaling; }, getRotation: function() { return this.decompose().rotation; }, applyToContext: function(ctx) { if (!this.isIdentity()) { ctx.transform(this._a, this._b, this._c, this._d, this._tx, this._ty); } } }, Base.each(['a', 'b', 'c', 'd', 'tx', 'ty'], function(key) { var part = Base.capitalize(key), prop = '_' + key; this['get' + part] = function() { return this[prop]; }; this['set' + part] = function(value) { this[prop] = value; this._changed(); }; }, {})); var Line = Base.extend({ _class: 'Line', initialize: function Line(arg0, arg1, arg2, arg3, arg4) { var asVector = false; if (arguments.length >= 4) { this._px = arg0; this._py = arg1; this._vx = arg2; this._vy = arg3; asVector = arg4; } else { this._px = arg0.x; this._py = arg0.y; this._vx = arg1.x; this._vy = arg1.y; asVector = arg2; } if (!asVector) { this._vx -= this._px; this._vy -= this._py; } }, getPoint: function() { return new Point(this._px, this._py); }, getVector: function() { return new Point(this._vx, this._vy); }, getLength: function() { return this.getVector().getLength(); }, intersect: function(line, isInfinite) { return Line.intersect( this._px, this._py, this._vx, this._vy, line._px, line._py, line._vx, line._vy, true, isInfinite); }, getSide: function(point, isInfinite) { return Line.getSide( this._px, this._py, this._vx, this._vy, point.x, point.y, true, isInfinite); }, getDistance: function(point) { return Math.abs(this.getSignedDistance(point)); }, getSignedDistance: function(point) { return Line.getSignedDistance(this._px, this._py, this._vx, this._vy, point.x, point.y, true); }, isCollinear: function(line) { return Point.isCollinear(this._vx, this._vy, line._vx, line._vy); }, isOrthogonal: function(line) { return Point.isOrthogonal(this._vx, this._vy, line._vx, line._vy); }, statics: { intersect: function(p1x, p1y, v1x, v1y, p2x, p2y, v2x, v2y, asVector, isInfinite) { if (!asVector) { v1x -= p1x; v1y -= p1y; v2x -= p2x; v2y -= p2y; } var cross = v1x * v2y - v1y * v2x; if (!Numerical.isMachineZero(cross)) { var dx = p1x - p2x, dy = p1y - p2y, u1 = (v2x * dy - v2y * dx) / cross, u2 = (v1x * dy - v1y * dx) / cross, epsilon = 1e-12, uMin = -epsilon, uMax = 1 + epsilon; if (isInfinite || uMin < u1 && u1 < uMax && uMin < u2 && u2 < uMax) { if (!isInfinite) { u1 = u1 <= 0 ? 0 : u1 >= 1 ? 1 : u1; } return new Point( p1x + u1 * v1x, p1y + u1 * v1y); } } }, getSide: function(px, py, vx, vy, x, y, asVector, isInfinite) { if (!asVector) { vx -= px; vy -= py; } var v2x = x - px, v2y = y - py, ccw = v2x * vy - v2y * vx; if (!isInfinite && Numerical.isMachineZero(ccw)) { ccw = (v2x * vx + v2x * vx) / (vx * vx + vy * vy); if (ccw >= 0 && ccw <= 1) ccw = 0; } return ccw < 0 ? -1 : ccw > 0 ? 1 : 0; }, getSignedDistance: function(px, py, vx, vy, x, y, asVector) { if (!asVector) { vx -= px; vy -= py; } return vx === 0 ? (vy > 0 ? x - px : px - x) : vy === 0 ? (vx < 0 ? y - py : py - y) : ((x - px) * vy - (y - py) * vx) / ( vy > vx ? vy * Math.sqrt(1 + (vx * vx) / (vy * vy)) : vx * Math.sqrt(1 + (vy * vy) / (vx * vx)) ); }, getDistance: function(px, py, vx, vy, x, y, asVector) { return Math.abs( Line.getSignedDistance(px, py, vx, vy, x, y, asVector)); } } }); var Project = PaperScopeItem.extend({ _class: 'Project', _list: 'projects', _reference: 'project', _compactSerialize: true, initialize: function Project(element) { PaperScopeItem.call(this, true); this._children = []; this._namedChildren = {}; this._activeLayer = null; this._currentStyle = new Style(null, null, this); this._view = View.create(this, element || CanvasProvider.getCanvas(1, 1)); this._selectionItems = {}; this._selectionCount = 0; this._updateVersion = 0; }, _serialize: function(options, dictionary) { return Base.serialize(this._children, options, true, dictionary); }, _changed: function(flags, item) { if (flags & 1) { var view = this._view; if (view) { view._needsUpdate = true; if (!view._requested && view._autoUpdate) view.requestUpdate(); } } var changes = this._changes; if (changes && item) { var changesById = this._changesById, id = item._id, entry = changesById[id]; if (entry) { entry.flags |= flags; } else { changes.push(changesById[id] = { item: item, flags: flags }); } } }, clear: function() { var children = this._children; for (var i = children.length - 1; i >= 0; i--) children[i].remove(); }, isEmpty: function() { return !this._children.length; }, remove: function remove() { if (!remove.base.call(this)) return false; if (this._view) this._view.remove(); return true; }, getView: function() { return this._view; }, getCurrentStyle: function() { return this._currentStyle; }, setCurrentStyle: function(style) { this._currentStyle.set(style); }, getIndex: function() { return this._index; }, getOptions: function() { return this._scope.settings; }, getLayers: function() { return this._children; }, getActiveLayer: function() { return this._activeLayer || new Layer({ project: this, insert: true }); }, getSymbolDefinitions: function() { var definitions = [], ids = {}; this.getItems({ class: SymbolItem, match: function(item) { var definition = item._definition, id = definition._id; if (!ids[id]) { ids[id] = true; definitions.push(definition); } return false; } }); return definitions; }, getSymbols: 'getSymbolDefinitions', getSelectedItems: function() { var selectionItems = this._selectionItems, items = []; for (var id in selectionItems) { var item = selectionItems[id], selection = item._selection; if ((selection & 1) && item.isInserted()) { items.push(item); } else if (!selection) { this._updateSelection(item); } } return items; }, _updateSelection: function(item) { var id = item._id, selectionItems = this._selectionItems; if (item._selection) { if (selectionItems[id] !== item) { this._selectionCount++; selectionItems[id] = item; } } else if (selectionItems[id] === item) { this._selectionCount--; delete selectionItems[id]; } }, selectAll: function() { var children = this._children; for (var i = 0, l = children.length; i < l; i++) children[i].setFullySelected(true); }, deselectAll: function() { var selectionItems = this._selectionItems; for (var i in selectionItems) selectionItems[i].setFullySelected(false); }, addLayer: function(layer) { return this.insertLayer(undefined, layer); }, insertLayer: function(index, layer) { if (layer instanceof Layer) { layer._remove(false, true); Base.splice(this._children, [layer], index, 0); layer._setProject(this, true); var name = layer._name; if (name) layer.setName(name); if (this._changes) layer._changed(5); if (!this._activeLayer) this._activeLayer = layer; } else { layer = null; } return layer; }, _insertItem: function(index, item, _created) { item = this.insertLayer(index, item) || (this._activeLayer || this._insertItem(undefined, new Layer(Item.NO_INSERT), true)) .insertChild(index, item); if (_created && item.activate) item.activate(); return item; }, getItems: function(options) { return Item._getItems(this, options); }, getItem: function(options) { return Item._getItems(this, options, null, null, true)[0] || null; }, importJSON: function(json) { this.activate(); var layer = this._activeLayer; return Base.importJSON(json, layer && layer.isEmpty() && layer); }, removeOn: function(type) { var sets = this._removeSets; if (sets) { if (type === 'mouseup') sets.mousedrag = null; var set = sets[type]; if (set) { for (var id in set) { var item = set[id]; for (var key in sets) { var other = sets[key]; if (other && other != set) delete other[item._id]; } item.remove(); } sets[type] = null; } } }, draw: function(ctx, matrix, pixelRatio) { this._updateVersion++; ctx.save(); matrix.applyToContext(ctx); var children = this._children, param = new Base({ offset: new Point(0, 0), pixelRatio: pixelRatio, viewMatrix: matrix.isIdentity() ? null : matrix, matrices: [new Matrix()], updateMatrix: true }); for (var i = 0, l = children.length; i < l; i++) { children[i].draw(ctx, param); } ctx.restore(); if (this._selectionCount > 0) { ctx.save(); ctx.strokeWidth = 1; var items = this._selectionItems, size = this._scope.settings.handleSize, version = this._updateVersion; for (var id in items) { items[id]._drawSelection(ctx, matrix, size, items, version); } ctx.restore(); } } }); var Item = Base.extend(Emitter, { statics: { extend: function extend(src) { if (src._serializeFields) src._serializeFields = Base.set({}, this.prototype._serializeFields, src._serializeFields); return extend.base.apply(this, arguments); }, NO_INSERT: { insert: false } }, _class: 'Item', _name: null, _applyMatrix: true, _canApplyMatrix: true, _canScaleStroke: false, _pivot: null, _visible: true, _blendMode: 'normal', _opacity: 1, _locked: false, _guide: false, _clipMask: false, _selection: 0, _selectBounds: true, _selectChildren: false, _serializeFields: { name: null, applyMatrix: null, matrix: new Matrix(), pivot: null, visible: true, blendMode: 'normal', opacity: 1, locked: false, guide: false, clipMask: false, selected: false, data: {} }, _prioritize: ['applyMatrix'] }, new function() { var handlers = ['onMouseDown', 'onMouseUp', 'onMouseDrag', 'onClick', 'onDoubleClick', 'onMouseMove', 'onMouseEnter', 'onMouseLeave']; return Base.each(handlers, function(name) { this._events[name] = { install: function(type) { this.getView()._countItemEvent(type, 1); }, uninstall: function(type) { this.getView()._countItemEvent(type, -1); } }; }, { _events: { onFrame: { install: function() { this.getView()._animateItem(this, true); }, uninstall: function() { this.getView()._animateItem(this, false); } }, onLoad: {}, onError: {} }, statics: { _itemHandlers: handlers } } ); }, { initialize: function Item() { }, _initialize: function(props, point) { var hasProps = props && Base.isPlainObject(props), internal = hasProps && props.internal === true, matrix = this._matrix = new Matrix(), project = hasProps && props.project || paper.project, settings = paper.settings; this._id = internal ? null : UID.get(); this._parent = this._index = null; this._applyMatrix = this._canApplyMatrix && settings.applyMatrix; if (point) matrix.translate(point); matrix._owner = this; this._style = new Style(project._currentStyle, this, project); if (internal || hasProps && props.insert == false || !settings.insertItems && !(hasProps && props.insert === true)) { this._setProject(project); } else { (hasProps && props.parent || project) ._insertItem(undefined, this, true); } if (hasProps && props !== Item.NO_INSERT) { this.set(props, { internal: true, insert: true, project: true, parent: true }); } return hasProps; }, _serialize: function(options, dictionary) { var props = {}, that = this; function serialize(fields) { for (var key in fields) { var value = that[key]; if (!Base.equals(value, key === 'leading' ? fields.fontSize * 1.2 : fields[key])) { props[key] = Base.serialize(value, options, key !== 'data', dictionary); } } } serialize(this._serializeFields); if (!(this instanceof Group)) serialize(this._style._defaults); return [ this._class, props ]; }, _changed: function(flags) { var symbol = this._symbol, cacheParent = this._parent || symbol, project = this._project; if (flags & 8) { this._bounds = this._position = this._decomposed = undefined; } if (flags & 16) { this._globalMatrix = undefined; } if (cacheParent && (flags & 72)) { Item._clearBoundsCache(cacheParent); } if (flags & 2) { Item._clearBoundsCache(this); } if (project) project._changed(flags, this); if (symbol) symbol._changed(flags); }, getId: function() { return this._id; }, getName: function() { return this._name; }, setName: function(name) { if (this._name) this._removeNamed(); if (name === (+name) + '') throw new Error( 'Names consisting only of numbers are not supported.'); var owner = this._getOwner(); if (name && owner) { var children = owner._children, namedChildren = owner._namedChildren; (namedChildren[name] = namedChildren[name] || []).push(this); if (!(name in children)) children[name] = this; } this._name = name || undefined; this._changed(256); }, getStyle: function() { return this._style; }, setStyle: function(style) { this.getStyle().set(style); } }, Base.each(['locked', 'visible', 'blendMode', 'opacity', 'guide'], function(name) { var part = Base.capitalize(name), key = '_' + name, flags = { locked: 256, visible: 265 }; this['get' + part] = function() { return this[key]; }; this['set' + part] = function(value) { if (value != this[key]) { this[key] = value; this._changed(flags[name] || 257); } }; }, {}), { beans: true, getSelection: function() { return this._selection; }, setSelection: function(selection) { if (selection !== this._selection) { this._selection = selection; var project = this._project; if (project) { project._updateSelection(this); this._changed(257); } } }, _changeSelection: function(flag, selected) { var selection = this._selection; this.setSelection(selected ? selection | flag : selection & ~flag); }, isSelected: function() { if (this._selectChildren) { var children = this._children; for (var i = 0, l = children.length; i < l; i++) if (children[i].isSelected()) return true; } return !!(this._selection & 1); }, setSelected: function(selected) { if (this._selectChildren) { var children = this._children; for (var i = 0, l = children.length; i < l; i++) children[i].setSelected(selected); } this._changeSelection(1, selected); }, isFullySelected: function() { var children = this._children, selected = !!(this._selection & 1); if (children && selected) { for (var i = 0, l = children.length; i < l; i++) if (!children[i].isFullySelected()) return false; return true; } return selected; }, setFullySelected: function(selected) { var children = this._children; if (children) { for (var i = 0, l = children.length; i < l; i++) children[i].setFullySelected(selected); } this._changeSelection(1, selected); }, isClipMask: function() { return this._clipMask; }, setClipMask: function(clipMask) { if (this._clipMask != (clipMask = !!clipMask)) { this._clipMask = clipMask; if (clipMask) { this.setFillColor(null); this.setStrokeColor(null); } this._changed(257); if (this._parent) this._parent._changed(2048); } }, getData: function() { if (!this._data) this._data = {}; return this._data; }, setData: function(data) { this._data = data; }, getPosition: function(_dontLink) { var ctor = _dontLink ? Point : LinkedPoint; var position = this._position || (this._position = this._getPositionFromBounds()); return new ctor(position.x, position.y, this, 'setPosition'); }, setPosition: function() { this.translate(Point.read(arguments).subtract(this.getPosition(true))); }, _getPositionFromBounds: function(bounds) { return this._pivot ? this._matrix._transformPoint(this._pivot) : (bounds || this.getBounds()).getCenter(true); }, getPivot: function() { var pivot = this._pivot; return pivot ? new LinkedPoint(pivot.x, pivot.y, this, 'setPivot') : null; }, setPivot: function() { this._pivot = Point.read(arguments, 0, { clone: true, readNull: true }); this._position = undefined; } }, Base.each({ getStrokeBounds: { stroke: true }, getHandleBounds: { handle: true }, getInternalBounds: { internal: true } }, function(options, key) { this[key] = function(matrix) { return this.getBounds(matrix, options); }; }, { beans: true, getBounds: function(matrix, options) { var hasMatrix = options || matrix instanceof Matrix, opts = Base.set({}, hasMatrix ? options : matrix, this._boundsOptions); if (!opts.stroke || this.getStrokeScaling()) opts.cacheItem = this; var rect = this._getCachedBounds(hasMatrix && matrix, opts).rect; return !arguments.length ? new LinkedRectangle(rect.x, rect.y, rect.width, rect.height, this, 'setBounds') : rect; }, setBounds: function() { var rect = Rectangle.read(arguments), bounds = this.getBounds(), _matrix = this._matrix, matrix = new Matrix(), center = rect.getCenter(); matrix.translate(center); if (rect.width != bounds.width || rect.height != bounds.height) { if (!_matrix.isInvertible()) { _matrix.set(_matrix._backup || new Matrix().translate(_matrix.getTranslation())); bounds = this.getBounds(); } matrix.scale( bounds.width !== 0 ? rect.width / bounds.width : 0, bounds.height !== 0 ? rect.height / bounds.height : 0); } center = bounds.getCenter(); matrix.translate(-center.x, -center.y); this.transform(matrix); }, _getBounds: function(matrix, options) { var children = this._children; if (!children || !children.length) return new Rectangle(); Item._updateBoundsCache(this, options.cacheItem); return Item._getBounds(children, matrix, options); }, _getBoundsCacheKey: function(options, internal) { return [ options.stroke ? 1 : 0, options.handle ? 1 : 0, internal ? 1 : 0 ].join(''); }, _getCachedBounds: function(matrix, options, noInternal) { matrix = matrix && matrix._orNullIfIdentity(); var internal = options.internal && !noInternal, cacheItem = options.cacheItem, _matrix = internal ? null : this._matrix._orNullIfIdentity(), cacheKey = cacheItem && (!matrix || matrix.equals(_matrix)) && this._getBoundsCacheKey(options, internal), bounds = this._bounds; Item._updateBoundsCache(this._parent || this._symbol, cacheItem); if (cacheKey && bounds && cacheKey in bounds) { var cached = bounds[cacheKey]; return { rect: cached.rect.clone(), nonscaling: cached.nonscaling }; } var res = this._getBounds(matrix || _matrix, options), rect = res.rect || res, style = this._style, nonscaling = res.nonscaling || style.hasStroke() && !style.getStrokeScaling(); if (cacheKey) { if (!bounds) { this._bounds = bounds = {}; } var cached = bounds[cacheKey] = { rect: rect.clone(), nonscaling: nonscaling, internal: internal }; } return { rect: rect, nonscaling: nonscaling }; }, _getStrokeMatrix: function(matrix, options) { var parent = this.getStrokeScaling() ? null : options && options.internal ? this : this._parent || this._symbol && this._symbol._item, mx = parent ? parent.getViewMatrix().invert() : matrix; return mx && mx._shiftless(); }, statics: { _updateBoundsCache: function(parent, item) { if (parent && item) { var id = item._id, ref = parent._boundsCache = parent._boundsCache || { ids: {}, list: [] }; if (!ref.ids[id]) { ref.list.push(item); ref.ids[id] = item; } } }, _clearBoundsCache: function(item) { var cache = item._boundsCache; if (cache) { item._bounds = item._position = item._boundsCache = undefined; for (var i = 0, list = cache.list, l = list.length; i < l; i++){ var other = list[i]; if (other !== item) { other._bounds = other._position = undefined; if (other._boundsCache) Item._clearBoundsCache(other); } } } }, _getBounds: function(items, matrix, options) { var x1 = Infinity, x2 = -x1, y1 = x1, y2 = x2, nonscaling = false; options = options || {}; for (var i = 0, l = items.length; i < l; i++) { var item = items[i]; if (item._visible && !item.isEmpty(true)) { var bounds = item._getCachedBounds( matrix && matrix.appended(item._matrix), options, true), rect = bounds.rect; x1 = Math.min(rect.x, x1); y1 = Math.min(rect.y, y1); x2 = Math.max(rect.x + rect.width, x2); y2 = Math.max(rect.y + rect.height, y2); if (bounds.nonscaling) nonscaling = true; } } return { rect: isFinite(x1) ? new Rectangle(x1, y1, x2 - x1, y2 - y1) : new Rectangle(), nonscaling: nonscaling }; } } }), { beans: true, _decompose: function() { return this._applyMatrix ? null : this._decomposed || (this._decomposed = this._matrix.decompose()); }, getRotation: function() { var decomposed = this._decompose(); return decomposed ? decomposed.rotation : 0; }, setRotation: function(rotation) { var current = this.getRotation(); if (current != null && rotation != null) { var decomposed = this._decomposed; this.rotate(rotation - current); if (decomposed) { decomposed.rotation = rotation; this._decomposed = decomposed; } } }, getScaling: function() { var decomposed = this._decompose(), s = decomposed && decomposed.scaling; return new LinkedPoint(s ? s.x : 1, s ? s.y : 1, this, 'setScaling'); }, setScaling: function() { var current = this.getScaling(), scaling = Point.read(arguments, 0, { clone: true, readNull: true }); if (current && scaling && !current.equals(scaling)) { var rotation = this.getRotation(), decomposed = this._decomposed, matrix = new Matrix(), isZero = Numerical.isZero; if (isZero(current.x) || isZero(current.y)) { matrix.translate(decomposed.translation); if (rotation) { matrix.rotate(rotation); } matrix.scale(scaling.x, scaling.y); this._matrix.set(matrix); } else { var center = this.getPosition(true); matrix.translate(center); if (rotation) matrix.rotate(rotation); matrix.scale(scaling.x / current.x, scaling.y / current.y); if (rotation) matrix.rotate(-rotation); matrix.translate(center.negate()); this.transform(matrix); } if (decomposed) { decomposed.scaling = scaling; this._decomposed = decomposed; } } }, getMatrix: function() { return this._matrix; }, setMatrix: function() { var matrix = this._matrix; matrix.set.apply(matrix, arguments); }, getGlobalMatrix: function(_dontClone) { var matrix = this._globalMatrix; if (matrix) { var parent = this._parent; var parents = []; while (parent) { if (!parent._globalMatrix) { matrix = null; for (var i = 0, l = parents.length; i < l; i++) { parents[i]._globalMatrix = null; } break; } parents.push(parent); parent = parent._parent; } } if (!matrix) { matrix = this._globalMatrix = this._matrix.clone(); var parent = this._parent; if (parent) matrix.prepend(parent.getGlobalMatrix(true)); } return _dontClone ? matrix : matrix.clone(); }, getViewMatrix: function() { return this.getGlobalMatrix().prepend(this.getView()._matrix); }, getApplyMatrix: function() { return this._applyMatrix; }, setApplyMatrix: function(apply) { if (this._applyMatrix = this._canApplyMatrix && !!apply) this.transform(null, true); }, getTransformContent: '#getApplyMatrix', setTransformContent: '#setApplyMatrix', }, { getProject: function() { return this._project; }, _setProject: function(project, installEvents) { if (this._project !== project) { if (this._project) this._installEvents(false); this._project = project; var children = this._children; for (var i = 0, l = children && children.length; i < l; i++) children[i]._setProject(project); installEvents = true; } if (installEvents) this._installEvents(true); }, getView: function() { return this._project._view; }, _installEvents: function _installEvents(install) { _installEvents.base.call(this, install); var children = this._children; for (var i = 0, l = children && children.length; i < l; i++) children[i]._installEvents(install); }, getLayer: function() { var parent = this; while (parent = parent._parent) { if (parent instanceof Layer) return parent; } return null; }, getParent: function() { return this._parent; }, setParent: function(item) { return item.addChild(this); }, _getOwner: '#getParent', getChildren: function() { return this._children; }, setChildren: function(items) { this.removeChildren(); this.addChildren(items); }, getFirstChild: function() { return this._children && this._children[0] || null; }, getLastChild: function() { return this._children && this._children[this._children.length - 1] || null; }, getNextSibling: function() { var owner = this._getOwner(); return owner && owner._children[this._index + 1] || null; }, getPreviousSibling: function() { var owner = this._getOwner(); return owner && owner._children[this._index - 1] || null; }, getIndex: function() { return this._index; }, equals: function(item) { return item === this || item && this._class === item._class && this._style.equals(item._style) && this._matrix.equals(item._matrix) && this._locked === item._locked && this._visible === item._visible && this._blendMode === item._blendMode && this._opacity === item._opacity && this._clipMask === item._clipMask && this._guide === item._guide && this._equals(item) || false; }, _equals: function(item) { return Base.equals(this._children, item._children); }, clone: function(options) { var copy = new this.constructor(Item.NO_INSERT), children = this._children, insert = Base.pick(options ? options.insert : undefined, options === undefined || options === true), deep = Base.pick(options ? options.deep : undefined, true); if (children) copy.copyAttributes(this); if (!children || deep) copy.copyContent(this); if (!children) copy.copyAttributes(this); if (insert) copy.insertAbove(this); var name = this._name, parent = this._parent; if (name && parent) { var children = parent._children, orig = name, i = 1; while (children[name]) name = orig + ' ' + (i++); if (name !== orig) copy.setName(name); } return copy; }, copyContent: function(source) { var children = source._children; for (var i = 0, l = children && children.length; i < l; i++) { this.addChild(children[i].clone(false), true); } }, copyAttributes: function(source, excludeMatrix) { this.setStyle(source._style); var keys = ['_locked', '_visible', '_blendMode', '_opacity', '_clipMask', '_guide']; for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; if (source.hasOwnProperty(key)) this[key] = source[key]; } if (!excludeMatrix) this._matrix.set(source._matrix, true); this.setApplyMatrix(source._applyMatrix); this.setPivot(source._pivot); this.setSelection(source._selection); var data = source._data, name = source._name; this._data = data ? Base.clone(data) : null; if (name) this.setName(name); }, rasterize: function(arg0, arg1) { var resolution, insert, raster; if (Base.isPlainObject(arg0)) { resolution = arg0.resolution; insert = arg0.insert; raster = arg0.raster; } else { resolution = arg0; insert = arg1; } if (!raster) { raster = new Raster(Item.NO_INSERT); } var bounds = this.getStrokeBounds(), scale = (resolution || this.getView().getResolution()) / 72, topLeft = bounds.getTopLeft().floor(), bottomRight = bounds.getBottomRight().ceil(), size = new Size(bottomRight.subtract(topLeft)).multiply(scale); raster.setSize(size, true); if (!size.isZero()) { var ctx = raster.getContext(true), matrix = new Matrix().scale(scale).translate(topLeft.negate()); ctx.save(); matrix.applyToContext(ctx); this.draw(ctx, new Base({ matrices: [matrix] })); ctx.restore(); } raster.transform(new Matrix().translate(topLeft.add(size.divide(2))) .scale(1 / scale)); if (insert === undefined || insert) raster.insertAbove(this); return raster; }, contains: function() { var matrix = this._matrix; return ( matrix.isInvertible() && !!this._contains(matrix._inverseTransform(Point.read(arguments))) ); }, _contains: function(point) { var children = this._children; if (children) { for (var i = children.length - 1; i >= 0; i--) { if (children[i].contains(point)) return true; } return false; } return point.isInside(this.getInternalBounds()); }, isInside: function() { return Rectangle.read(arguments).contains(this.getBounds()); }, _asPathItem: function() { return new Path.Rectangle({ rectangle: this.getInternalBounds(), matrix: this._matrix, insert: false, }); }, intersects: function(item, _matrix) { if (!(item instanceof Item)) return false; return this._asPathItem().getIntersections(item._asPathItem(), null, _matrix, true).length > 0; } }, new function() { function hitTest() { var args = arguments; return this._hitTest( Point.read(args), HitResult.getOptions(args)); } function hitTestAll() { var args = arguments, point = Point.read(args), options = HitResult.getOptions(args), all = []; this._hitTest(point, new Base({ all: all }, options)); return all; } function hitTestChildren(point, options, viewMatrix, _exclude) { var children = this._children; if (children) { for (var i = children.length - 1; i >= 0; i--) { var child = children[i]; var res = child !== _exclude && child._hitTest(point, options, viewMatrix); if (res && !options.all) return res; } } return null; } Project.inject({ hitTest: hitTest, hitTestAll: hitTestAll, _hitTest: hitTestChildren }); return { hitTest: hitTest, hitTestAll: hitTestAll, _hitTestChildren: hitTestChildren, }; }, { _hitTest: function(point, options, parentViewMatrix) { if (this._locked || !this._visible || this._guide && !options.guides || this.isEmpty()) { return null; } var matrix = this._matrix, viewMatrix = parentViewMatrix ? parentViewMatrix.appended(matrix) : this.getGlobalMatrix().prepend(this.getView()._matrix), tolerance = Math.max(options.tolerance, 1e-12), tolerancePadding = options._tolerancePadding = new Size( Path._getStrokePadding(tolerance, matrix._shiftless().invert())); point = matrix._inverseTransform(point); if (!point || !this._children && !this.getBounds({ internal: true, stroke: true, handle: true }) .expand(tolerancePadding.multiply(2))._containsPoint(point)) { return null; } var checkSelf = !(options.guides && !this._guide || options.selected && !this.isSelected() || options.type && options.type !== Base.hyphenate(this._class) || options.class && !(this instanceof options.class)), match = options.match, that = this, bounds, res; function filter(hit) { if (hit && match && !match(hit)) hit = null; if (hit && options.all) options.all.push(hit); return hit; } function checkPoint(type, part) { var pt = part ? bounds['get' + part]() : that.getPosition(); if (point.subtract(pt).divide(tolerancePadding).length <= 1) { return new HitResult(type, that, { name: part ? Base.hyphenate(part) : type, point: pt }); } } var checkPosition = options.position, checkCenter = options.center, checkBounds = options.bounds; if (checkSelf && this._parent && (checkPosition || checkCenter || checkBounds)) { if (checkCenter || checkBounds) { bounds = this.getInternalBounds(); } res = checkPosition && checkPoint('position') || checkCenter && checkPoint('center', 'Center'); if (!res && checkBounds) { var points = [ 'TopLeft', 'TopRight', 'BottomLeft', 'BottomRight', 'LeftCenter', 'TopCenter', 'RightCenter', 'BottomCenter' ]; for (var i = 0; i < 8 && !res; i++) { res = checkPoint('bounds', points[i]); } } res = filter(res); } if (!res) { res = this._hitTestChildren(point, options, viewMatrix) || checkSelf && filter(this._hitTestSelf(point, options, viewMatrix, this.getStrokeScaling() ? null : viewMatrix._shiftless().invert())) || null; } if (res && res.point) { res.point = matrix.transform(res.point); } return res; }, _hitTestSelf: function(point, options) { if (options.fill && this.hasFill() && this._contains(point)) return new HitResult('fill', this); }, matches: function(name, compare) { function matchObject(obj1, obj2) { for (var i in obj1) { if (obj1.hasOwnProperty(i)) { var val1 = obj1[i], val2 = obj2[i]; if (Base.isPlainObject(val1) && Base.isPlainObject(val2)) { if (!matchObject(val1, val2)) return false; } else if (!Base.equals(val1, val2)) { return false; } } } return true; } var type = typeof name; if (type === 'object') { for (var key in name) { if (name.hasOwnProperty(key) && !this.matches(key, name[key])) return false; } return true; } else if (type === 'function') { return name(this); } else if (name === 'match') { return compare(this); } else { var value = /^(empty|editable)$/.test(name) ? this['is' + Base.capitalize(name)]() : name === 'type' ? Base.hyphenate(this._class) : this[name]; if (name === 'class') { if (typeof compare === 'function') return this instanceof compare; value = this._class; } if (typeof compare === 'function') { return !!compare(value); } else if (compare) { if (compare.test) { return compare.test(value); } else if (Base.isPlainObject(compare)) { return matchObject(compare, value); } } return Base.equals(value, compare); } }, getItems: function(options) { return Item._getItems(this, options, this._matrix); }, getItem: function(options) { return Item._getItems(this, options, this._matrix, null, true)[0] || null; }, statics: { _getItems: function _getItems(item, options, matrix, param, firstOnly) { if (!param) { var obj = typeof options === 'object' && options, overlapping = obj && obj.overlapping, inside = obj && obj.inside, bounds = overlapping || inside, rect = bounds && Rectangle.read([bounds]); param = { items: [], recursive: obj && obj.recursive !== false, inside: !!inside, overlapping: !!overlapping, rect: rect, path: overlapping && new Path.Rectangle({ rectangle: rect, insert: false }) }; if (obj) { options = Base.filter({}, options, { recursive: true, inside: true, overlapping: true }); } } var children = item._children, items = param.items, rect = param.rect; matrix = rect && (matrix || new Matrix()); for (var i = 0, l = children && children.length; i < l; i++) { var child = children[i], childMatrix = matrix && matrix.appended(child._matrix), add = true; if (rect) { var bounds = child.getBounds(childMatrix); if (!rect.intersects(bounds)) continue; if (!(rect.contains(bounds) || param.overlapping && (bounds.contains(rect) || param.path.intersects(child, childMatrix)))) add = false; } if (add && child.matches(options)) { items.push(child); if (firstOnly) break; } if (param.recursive !== false) { _getItems(child, options, childMatrix, param, firstOnly); } if (firstOnly && items.length > 0) break; } return items; } } }, { importJSON: function(json) { var res = Base.importJSON(json, this); return res !== this ? this.addChild(res) : res; }, addChild: function(item) { return this.insertChild(undefined, item); }, insertChild: function(index, item) { var res = item ? this.insertChildren(index, [item]) : null; return res && res[0]; }, addChildren: function(items) { return this.insertChildren(this._children.length, items); }, insertChildren: function(index, items) { var children = this._children; if (children && items && items.length > 0) { items = Base.slice(items); var inserted = {}; for (var i = items.length - 1; i >= 0; i--) { var item = items[i], id = item && item._id; if (!item || inserted[id]) { items.splice(i, 1); } else { item._remove(false, true); inserted[id] = true; } } Base.splice(children, items, index, 0); var project = this._project, notifySelf = project._changes; for (var i = 0, l = items.length; i < l; i++) { var item = items[i], name = item._name; item._parent = this; item._setProject(project, true); if (name) item.setName(name); if (notifySelf) item._changed(5); } this._changed(11); } else { items = null; } return items; }, _insertItem: '#insertChild', _insertAt: function(item, offset) { var owner = item && item._getOwner(), res = item !== this && owner ? this : null; if (res) { res._remove(false, true); owner._insertItem(item._index + offset, res); } return res; }, insertAbove: function(item) { return this._insertAt(item, 1); }, insertBelow: function(item) { return this._insertAt(item, 0); }, sendToBack: function() { var owner = this._getOwner(); return owner ? owner._insertItem(0, this) : null; }, bringToFront: function() { var owner = this._getOwner(); return owner ? owner._insertItem(undefined, this) : null; }, appendTop: '#addChild', appendBottom: function(item) { return this.insertChild(0, item); }, moveAbove: '#insertAbove', moveBelow: '#insertBelow', addTo: function(owner) { return owner._insertItem(undefined, this); }, copyTo: function(owner) { return this.clone(false).addTo(owner); }, reduce: function(options) { var children = this._children; if (children && children.length === 1) { var child = children[0].reduce(options); if (this._parent) { child.insertAbove(this); this.remove(); } else { child.remove(); } return child; } return this; }, _removeNamed: function() { var owner = this._getOwner(); if (owner) { var children = owner._children, namedChildren = owner._namedChildren, name = this._name, namedArray = namedChildren[name], index = namedArray ? namedArray.indexOf(this) : -1; if (index !== -1) { if (children[name] == this) delete children[name]; namedArray.splice(index, 1); if (namedArray.length) { children[name] = namedArray[0]; } else { delete namedChildren[name]; } } } }, _remove: function(notifySelf, notifyParent) { var owner = this._getOwner(), project = this._project, index = this._index; if (this._style) this._style._dispose(); if (owner) { if (this._name) this._removeNamed(); if (index != null) { if (project._activeLayer === this) project._activeLayer = this.getNextSibling() || this.getPreviousSibling(); Base.splice(owner._children, null, index, 1); } this._installEvents(false); if (notifySelf && project._changes) this._changed(5); if (notifyParent) owner._changed(11, this); this._parent = null; return true; } return false; }, remove: function() { return this._remove(true, true); }, replaceWith: function(item) { var ok = item && item.insertBelow(this); if (ok) this.remove(); return ok; }, removeChildren: function(start, end) { if (!this._children) return null; start = start || 0; end = Base.pick(end, this._children.length); var removed = Base.splice(this._children, null, start, end - start); for (var i = removed.length - 1; i >= 0; i--) { removed[i]._remove(true, false); } if (removed.length > 0) this._changed(11); return removed; }, clear: '#removeChildren', reverseChildren: function() { if (this._children) { this._children.reverse(); for (var i = 0, l = this._children.length; i < l; i++) this._children[i]._index = i; this._changed(11); } }, isEmpty: function(recursively) { var children = this._children; var numChildren = children ? children.length : 0; if (recursively) { for (var i = 0; i < numChildren; i++) { if (!children[i].isEmpty(recursively)) { return false; } } return true; } return !numChildren; }, isEditable: function() { var item = this; while (item) { if (!item._visible || item._locked) return false; item = item._parent; } return true; }, hasFill: function() { return this.getStyle().hasFill(); }, hasStroke: function() { return this.getStyle().hasStroke(); }, hasShadow: function() { return this.getStyle().hasShadow(); }, _getOrder: function(item) { function getList(item) { var list = []; do { list.unshift(item); } while (item = item._parent); return list; } var list1 = getList(this), list2 = getList(item); for (var i = 0, l = Math.min(list1.length, list2.length); i < l; i++) { if (list1[i] != list2[i]) { return list1[i]._index < list2[i]._index ? 1 : -1; } } return 0; }, hasChildren: function() { return this._children && this._children.length > 0; }, isInserted: function() { return this._parent ? this._parent.isInserted() : false; }, isAbove: function(item) { return this._getOrder(item) === -1; }, isBelow: function(item) { return this._getOrder(item) === 1; }, isParent: function(item) { return this._parent === item; }, isChild: function(item) { return item && item._parent === this; }, isDescendant: function(item) { var parent = this; while (parent = parent._parent) { if (parent === item) return true; } return false; }, isAncestor: function(item) { return item ? item.isDescendant(this) : false; }, isSibling: function(item) { return this._parent === item._parent; }, isGroupedWith: function(item) { var parent = this._parent; while (parent) { if (parent._parent && /^(Group|Layer|CompoundPath)$/.test(parent._class) && item.isDescendant(parent)) return true; parent = parent._parent; } return false; }, }, Base.each(['rotate', 'scale', 'shear', 'skew'], function(key) { var rotate = key === 'rotate'; this[key] = function() { var args = arguments, value = (rotate ? Base : Point).read(args), center = Point.read(args, 0, { readNull: true }); return this.transform(new Matrix()[key](value, center || this.getPosition(true))); }; }, { translate: function() { var mx = new Matrix(); return this.transform(mx.translate.apply(mx, arguments)); }, transform: function(matrix, _applyRecursively, _setApplyMatrix) { var _matrix = this._matrix, transformMatrix = matrix && !matrix.isIdentity(), applyMatrix = ( _setApplyMatrix && this._canApplyMatrix || this._applyMatrix && ( transformMatrix || !_matrix.isIdentity() || _applyRecursively && this._children ) ); if (!transformMatrix && !applyMatrix) return this; if (transformMatrix) { if (!matrix.isInvertible() && _matrix.isInvertible()) _matrix._backup = _matrix.getValues(); _matrix.prepend(matrix, true); var style = this._style, fillColor = style.getFillColor(true), strokeColor = style.getStrokeColor(true); if (fillColor) fillColor.transform(matrix); if (strokeColor) strokeColor.transform(matrix); } if (applyMatrix && (applyMatrix = this._transformContent( _matrix, _applyRecursively, _setApplyMatrix))) { var pivot = this._pivot; if (pivot) _matrix._transformPoint(pivot, pivot, true); _matrix.reset(true); if (_setApplyMatrix && this._canApplyMatrix) this._applyMatrix = true; } var bounds = this._bounds, position = this._position; if (transformMatrix || applyMatrix) { this._changed(25); } var decomp = transformMatrix && bounds && matrix.decompose(); if (decomp && decomp.skewing.isZero() && decomp.rotation % 90 === 0) { for (var key in bounds) { var cache = bounds[key]; if (cache.nonscaling) { delete bounds[key]; } else if (applyMatrix || !cache.internal) { var rect = cache.rect; matrix._transformBounds(rect, rect); } } this._bounds = bounds; var cached = bounds[this._getBoundsCacheKey( this._boundsOptions || {})]; if (cached) { this._position = this._getPositionFromBounds(cached.rect); } } else if (transformMatrix && position && this._pivot) { this._position = matrix._transformPoint(position, position); } return this; }, _transformContent: function(matrix, applyRecursively, setApplyMatrix) { var children = this._children; if (children) { for (var i = 0, l = children.length; i < l; i++) { children[i].transform(matrix, applyRecursively, setApplyMatrix); } return true; } }, globalToLocal: function() { return this.getGlobalMatrix(true)._inverseTransform( Point.read(arguments)); }, localToGlobal: function() { return this.getGlobalMatrix(true)._transformPoint( Point.read(arguments)); }, parentToLocal: function() { return this._matrix._inverseTransform(Point.read(arguments)); }, localToParent: function() { return this._matrix._transformPoint(Point.read(arguments)); }, fitBounds: function(rectangle, fill) { rectangle = Rectangle.read(arguments); var bounds = this.getBounds(), itemRatio = bounds.height / bounds.width, rectRatio = rectangle.height / rectangle.width, scale = (fill ? itemRatio > rectRatio : itemRatio < rectRatio) ? rectangle.width / bounds.width : rectangle.height / bounds.height, newBounds = new Rectangle(new Point(), new Size(bounds.width * scale, bounds.height * scale)); newBounds.setCenter(rectangle.getCenter()); this.setBounds(newBounds); } }), { _setStyles: function(ctx, param, viewMatrix) { var style = this._style, matrix = this._matrix; if (style.hasFill()) { ctx.fillStyle = style.getFillColor().toCanvasStyle(ctx, matrix); } if (style.hasStroke()) { ctx.strokeStyle = style.getStrokeColor().toCanvasStyle(ctx, matrix); ctx.lineWidth = style.getStrokeWidth(); var strokeJoin = style.getStrokeJoin(), strokeCap = style.getStrokeCap(), miterLimit = style.getMiterLimit(); if (strokeJoin) ctx.lineJoin = strokeJoin; if (strokeCap) ctx.lineCap = strokeCap; if (miterLimit) ctx.miterLimit = miterLimit; if (paper.support.nativeDash) { var dashArray = style.getDashArray(), dashOffset = style.getDashOffset(); if (dashArray && dashArray.length) { if ('setLineDash' in ctx) { ctx.setLineDash(dashArray); ctx.lineDashOffset = dashOffset; } else { ctx.mozDash = dashArray; ctx.mozDashOffset = dashOffset; } } } } if (style.hasShadow()) { var pixelRatio = param.pixelRatio || 1, mx = viewMatrix._shiftless().prepend( new Matrix().scale(pixelRatio, pixelRatio)), blur = mx.transform(new Point(style.getShadowBlur(), 0)), offset = mx.transform(this.getShadowOffset()); ctx.shadowColor = style.getShadowColor().toCanvasStyle(ctx); ctx.shadowBlur = blur.getLength(); ctx.shadowOffsetX = offset.x; ctx.shadowOffsetY = offset.y; } }, draw: function(ctx, param, parentStrokeMatrix) { var updateVersion = this._updateVersion = this._project._updateVersion; if (!this._visible || this._opacity === 0) return; var matrices = param.matrices, viewMatrix = param.viewMatrix, matrix = this._matrix, globalMatrix = matrices[matrices.length - 1].appended(matrix); if (!globalMatrix.isInvertible()) return; viewMatrix = viewMatrix ? viewMatrix.appended(globalMatrix) : globalMatrix; matrices.push(globalMatrix); if (param.updateMatrix) { this._globalMatrix = globalMatrix; } var blendMode = this._blendMode, opacity = Numerical.clamp(this._opacity, 0, 1), normalBlend = blendMode === 'normal', nativeBlend = BlendMode.nativeModes[blendMode], direct = normalBlend && opacity === 1 || param.dontStart || param.clip || (nativeBlend || normalBlend && opacity < 1) && this._canComposite(), pixelRatio = param.pixelRatio || 1, mainCtx, itemOffset, prevOffset; if (!direct) { var bounds = this.getStrokeBounds(viewMatrix); if (!bounds.width || !bounds.height) { matrices.pop(); return; } prevOffset = param.offset; itemOffset = param.offset = bounds.getTopLeft().floor(); mainCtx = ctx; ctx = CanvasProvider.getContext(bounds.getSize().ceil().add(1) .multiply(pixelRatio)); if (pixelRatio !== 1) ctx.scale(pixelRatio, pixelRatio); } ctx.save(); var strokeMatrix = parentStrokeMatrix ? parentStrokeMatrix.appended(matrix) : this._canScaleStroke && !this.getStrokeScaling(true) && viewMatrix, clip = !direct && param.clipItem, transform = !strokeMatrix || clip; if (direct) { ctx.globalAlpha = opacity; if (nativeBlend) ctx.globalCompositeOperation = blendMode; } else if (transform) { ctx.translate(-itemOffset.x, -itemOffset.y); } if (transform) { (direct ? matrix : viewMatrix).applyToContext(ctx); } if (clip) { param.clipItem.draw(ctx, param.extend({ clip: true })); } if (strokeMatrix) { ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0); var offset = param.offset; if (offset) ctx.translate(-offset.x, -offset.y); } this._draw(ctx, param, viewMatrix, strokeMatrix); ctx.restore(); matrices.pop(); if (param.clip && !param.dontFinish) { ctx.clip(this.getFillRule()); } if (!direct) { BlendMode.process(blendMode, ctx, mainCtx, opacity, itemOffset.subtract(prevOffset).multiply(pixelRatio)); CanvasProvider.release(ctx); param.offset = prevOffset; } }, _isUpdated: function(updateVersion) { var parent = this._parent; if (parent instanceof CompoundPath) return parent._isUpdated(updateVersion); var updated = this._updateVersion === updateVersion; if (!updated && parent && parent._visible && parent._isUpdated(updateVersion)) { this._updateVersion = updateVersion; updated = true; } return updated; }, _drawSelection: function(ctx, matrix, size, selectionItems, updateVersion) { var selection = this._selection, itemSelected = selection & 1, boundsSelected = selection & 2 || itemSelected && this._selectBounds, positionSelected = selection & 4; if (!this._drawSelected) itemSelected = false; if ((itemSelected || boundsSelected || positionSelected) && this._isUpdated(updateVersion)) { var layer, color = this.getSelectedColor(true) || (layer = this.getLayer()) && layer.getSelectedColor(true), mx = matrix.appended(this.getGlobalMatrix(true)), half = size / 2; ctx.strokeStyle = ctx.fillStyle = color ? color.toCanvasStyle(ctx) : '#009dec'; if (itemSelected) this._drawSelected(ctx, mx, selectionItems); if (positionSelected) { var pos = this.getPosition(true), parent = this._parent, point = parent ? parent.localToGlobal(pos) : pos, x = point.x, y = point.y; ctx.beginPath(); ctx.arc(x, y, half, 0, Math.PI * 2, true); ctx.stroke(); var deltas = [[0, -1], [1, 0], [0, 1], [-1, 0]], start = half, end = size + 1; for (var i = 0; i < 4; i++) { var delta = deltas[i], dx = delta[0], dy = delta[1]; ctx.moveTo(x + dx * start, y + dy * start); ctx.lineTo(x + dx * end, y + dy * end); ctx.stroke(); } } if (boundsSelected) { var coords = mx._transformCorners(this.getInternalBounds()); ctx.beginPath(); for (var i = 0; i < 8; i++) { ctx[!i ? 'moveTo' : 'lineTo'](coords[i], coords[++i]); } ctx.closePath(); ctx.stroke(); for (var i = 0; i < 8; i++) { ctx.fillRect(coords[i] - half, coords[++i] - half, size, size); } } } }, _canComposite: function() { return false; } }, Base.each(['down', 'drag', 'up', 'move'], function(key) { this['removeOn' + Base.capitalize(key)] = function() { var hash = {}; hash[key] = true; return this.removeOn(hash); }; }, { removeOn: function(obj) { for (var name in obj) { if (obj[name]) { var key = 'mouse' + name, project = this._project, sets = project._removeSets = project._removeSets || {}; sets[key] = sets[key] || {}; sets[key][this._id] = this; } } return this; } }), { tween: function(from, to, options) { if (!options) { options = to; to = from; from = null; if (!options) { options = to; to = null; } } var easing = options && options.easing, start = options && options.start, duration = options != null && ( typeof options === 'number' ? options : options.duration ), tween = new Tween(this, from, to, duration, easing, start); function onFrame(event) { tween._handleFrame(event.time * 1000); if (!tween.running) { this.off('frame', onFrame); } } if (duration) { this.on('frame', onFrame); } return tween; }, tweenTo: function(to, options) { return this.tween(null, to, options); }, tweenFrom: function(from, options) { return this.tween(from, null, options); } }); var Group = Item.extend({ _class: 'Group', _selectBounds: false, _selectChildren: true, _serializeFields: { children: [] }, initialize: function Group(arg) { this._children = []; this._namedChildren = {}; if (!this._initialize(arg)) this.addChildren(Array.isArray(arg) ? arg : arguments); }, _changed: function _changed(flags) { _changed.base.call(this, flags); if (flags & 2050) { this._clipItem = undefined; } }, _getClipItem: function() { var clipItem = this._clipItem; if (clipItem === undefined) { clipItem = null; var children = this._children; for (var i = 0, l = children.length; i < l; i++) { if (children[i]._clipMask) { clipItem = children[i]; break; } } this._clipItem = clipItem; } return clipItem; }, isClipped: function() { return !!this._getClipItem(); }, setClipped: function(clipped) { var child = this.getFirstChild(); if (child) child.setClipMask(clipped); }, _getBounds: function _getBounds(matrix, options) { var clipItem = this._getClipItem(); return clipItem ? clipItem._getCachedBounds(clipItem._matrix.prepended(matrix), Base.set({}, options, { stroke: false })) : _getBounds.base.call(this, matrix, options); }, _hitTestChildren: function _hitTestChildren(point, options, viewMatrix) { var clipItem = this._getClipItem(); return (!clipItem || clipItem.contains(point)) && _hitTestChildren.base.call(this, point, options, viewMatrix, clipItem); }, _draw: function(ctx, param) { var clip = param.clip, clipItem = !clip && this._getClipItem(); param = param.extend({ clipItem: clipItem, clip: false }); if (clip) { ctx.beginPath(); param.dontStart = param.dontFinish = true; } else if (clipItem) { clipItem.draw(ctx, param.extend({ clip: true })); } var children = this._children; for (var i = 0, l = children.length; i < l; i++) { var item = children[i]; if (item !== clipItem) item.draw(ctx, param); } } }); var Layer = Group.extend({ _class: 'Layer', initialize: function Layer() { Group.apply(this, arguments); }, _getOwner: function() { return this._parent || this._index != null && this._project; }, isInserted: function isInserted() { return this._parent ? isInserted.base.call(this) : this._index != null; }, activate: function() { this._project._activeLayer = this; }, _hitTestSelf: function() { } }); var Shape = Item.extend({ _class: 'Shape', _applyMatrix: false, _canApplyMatrix: false, _canScaleStroke: true, _serializeFields: { type: null, size: null, radius: null }, initialize: function Shape(props, point) { this._initialize(props, point); }, _equals: function(item) { return this._type === item._type && this._size.equals(item._size) && Base.equals(this._radius, item._radius); }, copyContent: function(source) { this.setType(source._type); this.setSize(source._size); this.setRadius(source._radius); }, getType: function() { return this._type; }, setType: function(type) { this._type = type; }, getShape: '#getType', setShape: '#setType', getSize: function() { var size = this._size; return new LinkedSize(size.width, size.height, this, 'setSize'); }, setSize: function() { var size = Size.read(arguments); if (!this._size) { this._size = size.clone(); } else if (!this._size.equals(size)) { var type = this._type, width = size.width, height = size.height; if (type === 'rectangle') { this._radius.set(Size.min(this._radius, size.divide(2).abs())); } else if (type === 'circle') { width = height = (width + height) / 2; this._radius = width / 2; } else if (type === 'ellipse') { this._radius._set(width / 2, height / 2); } this._size._set(width, height); this._changed(9); } }, getRadius: function() { var rad = this._radius; return this._type === 'circle' ? rad : new LinkedSize(rad.width, rad.height, this, 'setRadius'); }, setRadius: function(radius) { var type = this._type; if (type === 'circle') { if (radius === this._radius) return; var size = radius * 2; this._radius = radius; this._size._set(size, size); } else { radius = Size.read(arguments); if (!this._radius) { this._radius = radius.clone(); } else { if (this._radius.equals(radius)) return; this._radius.set(radius); if (type === 'rectangle') { var size = Size.max(this._size, radius.multiply(2)); this._size.set(size); } else if (type === 'ellipse') { this._size._set(radius.width * 2, radius.height * 2); } } } this._changed(9); }, isEmpty: function() { return false; }, toPath: function(insert) { var path = new Path[Base.capitalize(this._type)]({ center: new Point(), size: this._size, radius: this._radius, insert: false }); path.copyAttributes(this); if (paper.settings.applyMatrix) path.setApplyMatrix(true); if (insert === undefined || insert) path.insertAbove(this); return path; }, toShape: '#clone', _asPathItem: function() { return this.toPath(false); }, _draw: function(ctx, param, viewMatrix, strokeMatrix) { var style = this._style, hasFill = style.hasFill(), hasStroke = style.hasStroke(), dontPaint = param.dontFinish || param.clip, untransformed = !strokeMatrix; if (hasFill || hasStroke || dontPaint) { var type = this._type, radius = this._radius, isCircle = type === 'circle'; if (!param.dontStart) ctx.beginPath(); if (untransformed && isCircle) { ctx.arc(0, 0, radius, 0, Math.PI * 2, true); } else { var rx = isCircle ? radius : radius.width, ry = isCircle ? radius : radius.height, size = this._size, width = size.width, height = size.height; if (untransformed && type === 'rectangle' && rx === 0 && ry === 0) { ctx.rect(-width / 2, -height / 2, width, height); } else { var x = width / 2, y = height / 2, kappa = 1 - 0.5522847498307936, cx = rx * kappa, cy = ry * kappa, c = [ -x, -y + ry, -x, -y + cy, -x + cx, -y, -x + rx, -y, x - rx, -y, x - cx, -y, x, -y + cy, x, -y + ry, x, y - ry, x, y - cy, x - cx, y, x - rx, y, -x + rx, y, -x + cx, y, -x, y - cy, -x, y - ry ]; if (strokeMatrix) strokeMatrix.transform(c, c, 32); ctx.moveTo(c[0], c[1]); ctx.bezierCurveTo(c[2], c[3], c[4], c[5], c[6], c[7]); if (x !== rx) ctx.lineTo(c[8], c[9]); ctx.bezierCurveTo(c[10], c[11], c[12], c[13], c[14], c[15]); if (y !== ry) ctx.lineTo(c[16], c[17]); ctx.bezierCurveTo(c[18], c[19], c[20], c[21], c[22], c[23]); if (x !== rx) ctx.lineTo(c[24], c[25]); ctx.bezierCurveTo(c[26], c[27], c[28], c[29], c[30], c[31]); } } ctx.closePath(); } if (!dontPaint && (hasFill || hasStroke)) { this._setStyles(ctx, param, viewMatrix); if (hasFill) { ctx.fill(style.getFillRule()); ctx.shadowColor = 'rgba(0,0,0,0)'; } if (hasStroke) ctx.stroke(); } }, _canComposite: function() { return !(this.hasFill() && this.hasStroke()); }, _getBounds: function(matrix, options) { var rect = new Rectangle(this._size).setCenter(0, 0), style = this._style, strokeWidth = options.stroke && style.hasStroke() && style.getStrokeWidth(); if (matrix) rect = matrix._transformBounds(rect); return strokeWidth ? rect.expand(Path._getStrokePadding(strokeWidth, this._getStrokeMatrix(matrix, options))) : rect; } }, new function() { function getCornerCenter(that, point, expand) { var radius = that._radius; if (!radius.isZero()) { var halfSize = that._size.divide(2); for (var q = 1; q <= 4; q++) { var dir = new Point(q > 1 && q < 4 ? -1 : 1, q > 2 ? -1 : 1), corner = dir.multiply(halfSize), center = corner.subtract(dir.multiply(radius)), rect = new Rectangle( expand ? corner.add(dir.multiply(expand)) : corner, center); if (rect.contains(point)) return { point: center, quadrant: q }; } } } function isOnEllipseStroke(point, radius, padding, quadrant) { var vector = point.divide(radius); return (!quadrant || vector.isInQuadrant(quadrant)) && vector.subtract(vector.normalize()).multiply(radius) .divide(padding).length <= 1; } return { _contains: function _contains(point) { if (this._type === 'rectangle') { var center = getCornerCenter(this, point); return center ? point.subtract(center.point).divide(this._radius) .getLength() <= 1 : _contains.base.call(this, point); } else { return point.divide(this.size).getLength() <= 0.5; } }, _hitTestSelf: function _hitTestSelf(point, options, viewMatrix, strokeMatrix) { var hit = false, style = this._style, hitStroke = options.stroke && style.hasStroke(), hitFill = options.fill && style.hasFill(); if (hitStroke || hitFill) { var type = this._type, radius = this._radius, strokeRadius = hitStroke ? style.getStrokeWidth() / 2 : 0, strokePadding = options._tolerancePadding.add( Path._getStrokePadding(strokeRadius, !style.getStrokeScaling() && strokeMatrix)); if (type === 'rectangle') { var padding = strokePadding.multiply(2), center = getCornerCenter(this, point, padding); if (center) { hit = isOnEllipseStroke(point.subtract(center.point), radius, strokePadding, center.quadrant); } else { var rect = new Rectangle(this._size).setCenter(0, 0), outer = rect.expand(padding), inner = rect.expand(padding.negate()); hit = outer._containsPoint(point) && !inner._containsPoint(point); } } else { hit = isOnEllipseStroke(point, radius, strokePadding); } } return hit ? new HitResult(hitStroke ? 'stroke' : 'fill', this) : _hitTestSelf.base.apply(this, arguments); } }; }, { statics: new function() { function createShape(type, point, size, radius, args) { var item = Base.create(Shape.prototype); item._type = type; item._size = size; item._radius = radius; item._initialize(Base.getNamed(args), point); return item; } return { Circle: function() { var args = arguments, center = Point.readNamed(args, 'center'), radius = Base.readNamed(args, 'radius'); return createShape('circle', center, new Size(radius * 2), radius, args); }, Rectangle: function() { var args = arguments, rect = Rectangle.readNamed(args, 'rectangle'), radius = Size.min(Size.readNamed(args, 'radius'), rect.getSize(true).divide(2)); return createShape('rectangle', rect.getCenter(true), rect.getSize(true), radius, args); }, Ellipse: function() { var args = arguments, ellipse = Shape._readEllipse(args), radius = ellipse.radius; return createShape('ellipse', ellipse.center, radius.multiply(2), radius, args); }, _readEllipse: function(args) { var center, radius; if (Base.hasNamed(args, 'radius')) { center = Point.readNamed(args, 'center'); radius = Size.readNamed(args, 'radius'); } else { var rect = Rectangle.readNamed(args, 'rectangle'); center = rect.getCenter(true); radius = rect.getSize(true).divide(2); } return { center: center, radius: radius }; } }; }}); var Raster = Item.extend({ _class: 'Raster', _applyMatrix: false, _canApplyMatrix: false, _boundsOptions: { stroke: false, handle: false }, _serializeFields: { crossOrigin: null, source: null }, _prioritize: ['crossOrigin'], _smoothing: 'low', beans: true, initialize: function Raster(source, position) { if (!this._initialize(source, position !== undefined && Point.read(arguments))) { var image, type = typeof source, object = type === 'string' ? document.getElementById(source) : type === 'object' ? source : null; if (object && object !== Item.NO_INSERT) { if (object.getContext || object.naturalHeight != null) { image = object; } else if (object) { var size = Size.read(arguments); if (!size.isZero()) { image = CanvasProvider.getCanvas(size); } } } if (image) { this.setImage(image); } else { this.setSource(source); } } if (!this._size) { this._size = new Size(); this._loaded = false; } }, _equals: function(item) { return this.getSource() === item.getSource(); }, copyContent: function(source) { var image = source._image, canvas = source._canvas; if (image) { this._setImage(image); } else if (canvas) { var copyCanvas = CanvasProvider.getCanvas(source._size); copyCanvas.getContext('2d').drawImage(canvas, 0, 0); this._setImage(copyCanvas); } this._crossOrigin = source._crossOrigin; }, getSize: function() { var size = this._size; return new LinkedSize(size ? size.width : 0, size ? size.height : 0, this, 'setSize'); }, setSize: function(_size, _clear) { var size = Size.read(arguments); if (!size.equals(this._size)) { if (size.width > 0 && size.height > 0) { var element = !_clear && this.getElement(); this._setImage(CanvasProvider.getCanvas(size)); if (element) { this.getContext(true).drawImage(element, 0, 0, size.width, size.height); } } else { if (this._canvas) CanvasProvider.release(this._canvas); this._size = size.clone(); } } else if (_clear) { this.clear(); } }, getWidth: function() { return this._size ? this._size.width : 0; }, setWidth: function(width) { this.setSize(width, this.getHeight()); }, getHeight: function() { return this._size ? this._size.height : 0; }, setHeight: function(height) { this.setSize(this.getWidth(), height); }, getLoaded: function() { return this._loaded; }, isEmpty: function() { var size = this._size; return !size || size.width === 0 && size.height === 0; }, getResolution: function() { var matrix = this._matrix, orig = new Point(0, 0).transform(matrix), u = new Point(1, 0).transform(matrix).subtract(orig), v = new Point(0, 1).transform(matrix).subtract(orig); return new Size( 72 / u.getLength(), 72 / v.getLength() ); }, getPpi: '#getResolution', getImage: function() { return this._image; }, setImage: function(image) { var that = this; function emit(event) { var view = that.getView(), type = event && event.type || 'load'; if (view && that.responds(type)) { paper = view._scope; that.emit(type, new Event(event)); } } this._setImage(image); if (this._loaded) { setTimeout(emit, 0); } else if (image) { DomEvent.add(image, { load: function(event) { that._setImage(image); emit(event); }, error: emit }); } }, _setImage: function(image) { if (this._canvas) CanvasProvider.release(this._canvas); if (image && image.getContext) { this._image = null; this._canvas = image; this._loaded = true; } else { this._image = image; this._canvas = null; this._loaded = !!(image && image.src && image.complete); } this._size = new Size( image ? image.naturalWidth || image.width : 0, image ? image.naturalHeight || image.height : 0); this._context = null; this._changed(1033); }, getCanvas: function() { if (!this._canvas) { var ctx = CanvasProvider.getContext(this._size); try { if (this._image) ctx.drawImage(this._image, 0, 0); this._canvas = ctx.canvas; } catch (e) { CanvasProvider.release(ctx); } } return this._canvas; }, setCanvas: '#setImage', getContext: function(_change) { if (!this._context) this._context = this.getCanvas().getContext('2d'); if (_change) { this._image = null; this._changed(1025); } return this._context; }, setContext: function(context) { this._context = context; }, getSource: function() { var image = this._image; return image && image.src || this.toDataURL(); }, setSource: function(src) { var image = new self.Image(), crossOrigin = this._crossOrigin; if (crossOrigin) image.crossOrigin = crossOrigin; if (src) image.src = src; this.setImage(image); }, getCrossOrigin: function() { var image = this._image; return image && image.crossOrigin || this._crossOrigin || ''; }, setCrossOrigin: function(crossOrigin) { this._crossOrigin = crossOrigin; var image = this._image; if (image) image.crossOrigin = crossOrigin; }, getSmoothing: function() { return this._smoothing; }, setSmoothing: function(smoothing) { this._smoothing = typeof smoothing === 'string' ? smoothing : smoothing ? 'low' : 'off'; this._changed(257); }, getElement: function() { return this._canvas || this._loaded && this._image; } }, { beans: false, getSubCanvas: function() { var rect = Rectangle.read(arguments), ctx = CanvasProvider.getContext(rect.getSize()); ctx.drawImage(this.getCanvas(), rect.x, rect.y, rect.width, rect.height, 0, 0, rect.width, rect.height); return ctx.canvas; }, getSubRaster: function() { var rect = Rectangle.read(arguments), raster = new Raster(Item.NO_INSERT); raster._setImage(this.getSubCanvas(rect)); raster.translate(rect.getCenter().subtract(this.getSize().divide(2))); raster._matrix.prepend(this._matrix); raster.insertAbove(this); return raster; }, toDataURL: function() { var image = this._image, src = image && image.src; if (/^data:/.test(src)) return src; var canvas = this.getCanvas(); return canvas ? canvas.toDataURL.apply(canvas, arguments) : null; }, drawImage: function(image ) { var point = Point.read(arguments, 1); this.getContext(true).drawImage(image, point.x, point.y); }, getAverageColor: function(object) { var bounds, path; if (!object) { bounds = this.getBounds(); } else if (object instanceof PathItem) { path = object; bounds = object.getBounds(); } else if (typeof object === 'object') { if ('width' in object) { bounds = new Rectangle(object); } else if ('x' in object) { bounds = new Rectangle(object.x - 0.5, object.y - 0.5, 1, 1); } } if (!bounds) return null; var sampleSize = 32, width = Math.min(bounds.width, sampleSize), height = Math.min(bounds.height, sampleSize); var ctx = Raster._sampleContext; if (!ctx) { ctx = Raster._sampleContext = CanvasProvider.getContext( new Size(sampleSize)); } else { ctx.clearRect(0, 0, sampleSize + 1, sampleSize + 1); } ctx.save(); var matrix = new Matrix() .scale(width / bounds.width, height / bounds.height) .translate(-bounds.x, -bounds.y); matrix.applyToContext(ctx); if (path) path.draw(ctx, new Base({ clip: true, matrices: [matrix] })); this._matrix.applyToContext(ctx); var element = this.getElement(), size = this._size; if (element) ctx.drawImage(element, -size.width / 2, -size.height / 2); ctx.restore(); var pixels = ctx.getImageData(0.5, 0.5, Math.ceil(width), Math.ceil(height)).data, channels = [0, 0, 0], total = 0; for (var i = 0, l = pixels.length; i < l; i += 4) { var alpha = pixels[i + 3]; total += alpha; alpha /= 255; channels[0] += pixels[i] * alpha; channels[1] += pixels[i + 1] * alpha; channels[2] += pixels[i + 2] * alpha; } for (var i = 0; i < 3; i++) channels[i] /= total; return total ? Color.read(channels) : null; }, getPixel: function() { var point = Point.read(arguments); var data = this.getContext().getImageData(point.x, point.y, 1, 1).data; return new Color('rgb', [data[0] / 255, data[1] / 255, data[2] / 255], data[3] / 255); }, setPixel: function() { var args = arguments, point = Point.read(args), color = Color.read(args), components = color._convert('rgb'), alpha = color._alpha, ctx = this.getContext(true), imageData = ctx.createImageData(1, 1), data = imageData.data; data[0] = components[0] * 255; data[1] = components[1] * 255; data[2] = components[2] * 255; data[3] = alpha != null ? alpha * 255 : 255; ctx.putImageData(imageData, point.x, point.y); }, clear: function() { var size = this._size; this.getContext(true).clearRect(0, 0, size.width + 1, size.height + 1); }, createImageData: function() { var size = Size.read(arguments); return this.getContext().createImageData(size.width, size.height); }, getImageData: function() { var rect = Rectangle.read(arguments); if (rect.isEmpty()) rect = new Rectangle(this._size); return this.getContext().getImageData(rect.x, rect.y, rect.width, rect.height); }, setImageData: function(data ) { var point = Point.read(arguments, 1); this.getContext(true).putImageData(data, point.x, point.y); }, _getBounds: function(matrix, options) { var rect = new Rectangle(this._size).setCenter(0, 0); return matrix ? matrix._transformBounds(rect) : rect; }, _hitTestSelf: function(point) { if (this._contains(point)) { var that = this; return new HitResult('pixel', that, { offset: point.add(that._size.divide(2)).round(), color: { get: function() { return that.getPixel(this.offset); } } }); } }, _draw: function(ctx, param, viewMatrix) { var element = this.getElement(); if (element && element.width > 0 && element.height > 0) { ctx.globalAlpha = Numerical.clamp(this._opacity, 0, 1); this._setStyles(ctx, param, viewMatrix); var smoothing = this._smoothing, disabled = smoothing === 'off'; DomElement.setPrefixed( ctx, disabled ? 'imageSmoothingEnabled' : 'imageSmoothingQuality', disabled ? false : smoothing ); ctx.drawImage(element, -this._size.width / 2, -this._size.height / 2); } }, _canComposite: function() { return true; } }); var SymbolItem = Item.extend({ _class: 'SymbolItem', _applyMatrix: false, _canApplyMatrix: false, _boundsOptions: { stroke: true }, _serializeFields: { symbol: null }, initialize: function SymbolItem(arg0, arg1) { if (!this._initialize(arg0, arg1 !== undefined && Point.read(arguments, 1))) this.setDefinition(arg0 instanceof SymbolDefinition ? arg0 : new SymbolDefinition(arg0)); }, _equals: function(item) { return this._definition === item._definition; }, copyContent: function(source) { this.setDefinition(source._definition); }, getDefinition: function() { return this._definition; }, setDefinition: function(definition) { this._definition = definition; this._changed(9); }, getSymbol: '#getDefinition', setSymbol: '#setDefinition', isEmpty: function() { return this._definition._item.isEmpty(); }, _getBounds: function(matrix, options) { var item = this._definition._item; return item._getCachedBounds(item._matrix.prepended(matrix), options); }, _hitTestSelf: function(point, options, viewMatrix) { var opts = options.extend({ all: false }); var res = this._definition._item._hitTest(point, opts, viewMatrix); if (res) res.item = this; return res; }, _draw: function(ctx, param) { this._definition._item.draw(ctx, param); } }); var SymbolDefinition = Base.extend({ _class: 'SymbolDefinition', initialize: function SymbolDefinition(item, dontCenter) { this._id = UID.get(); this.project = paper.project; if (item) this.setItem(item, dontCenter); }, _serialize: function(options, dictionary) { return dictionary.add(this, function() { return Base.serialize([this._class, this._item], options, false, dictionary); }); }, _changed: function(flags) { if (flags & 8) Item._clearBoundsCache(this); if (flags & 1) this.project._changed(flags); }, getItem: function() { return this._item; }, setItem: function(item, _dontCenter) { if (item._symbol) item = item.clone(); if (this._item) this._item._symbol = null; this._item = item; item.remove(); item.setSelected(false); if (!_dontCenter) item.setPosition(new Point()); item._symbol = this; this._changed(9); }, getDefinition: '#getItem', setDefinition: '#setItem', place: function(position) { return new SymbolItem(this, position); }, clone: function() { return new SymbolDefinition(this._item.clone(false)); }, equals: function(symbol) { return symbol === this || symbol && this._item.equals(symbol._item) || false; } }); var HitResult = Base.extend({ _class: 'HitResult', initialize: function HitResult(type, item, values) { this.type = type; this.item = item; if (values) this.inject(values); }, statics: { getOptions: function(args) { var options = args && Base.read(args); return new Base({ type: null, tolerance: paper.settings.hitTolerance, fill: !options, stroke: !options, segments: !options, handles: false, ends: false, position: false, center: false, bounds: false, guides: false, selected: false }, options); } } }); var Segment = Base.extend({ _class: 'Segment', beans: true, _selection: 0, initialize: function Segment(arg0, arg1, arg2, arg3, arg4, arg5) { var count = arguments.length, point, handleIn, handleOut, selection; if (count > 0) { if (arg0 == null || typeof arg0 === 'object') { if (count === 1 && arg0 && 'point' in arg0) { point = arg0.point; handleIn = arg0.handleIn; handleOut = arg0.handleOut; selection = arg0.selection; } else { point = arg0; handleIn = arg1; handleOut = arg2; selection = arg3; } } else { point = [ arg0, arg1 ]; handleIn = arg2 !== undefined ? [ arg2, arg3 ] : null; handleOut = arg4 !== undefined ? [ arg4, arg5 ] : null; } } new SegmentPoint(point, this, '_point'); new SegmentPoint(handleIn, this, '_handleIn'); new SegmentPoint(handleOut, this, '_handleOut'); if (selection) this.setSelection(selection); }, _serialize: function(options, dictionary) { var point = this._point, selection = this._selection, obj = selection || this.hasHandles() ? [point, this._handleIn, this._handleOut] : point; if (selection) obj.push(selection); return Base.serialize(obj, options, true, dictionary); }, _changed: function(point) { var path = this._path; if (!path) return; var curves = path._curves, index = this._index, curve; if (curves) { if ((!point || point === this._point || point === this._handleIn) && (curve = index > 0 ? curves[index - 1] : path._closed ? curves[curves.length - 1] : null)) curve._changed(); if ((!point || point === this._point || point === this._handleOut) && (curve = curves[index])) curve._changed(); } path._changed(41); }, getPoint: function() { return this._point; }, setPoint: function() { this._point.set(Point.read(arguments)); }, getHandleIn: function() { return this._handleIn; }, setHandleIn: function() { this._handleIn.set(Point.read(arguments)); }, getHandleOut: function() { return this._handleOut; }, setHandleOut: function() { this._handleOut.set(Point.read(arguments)); }, hasHandles: function() { return !this._handleIn.isZero() || !this._handleOut.isZero(); }, isSmooth: function() { var handleIn = this._handleIn, handleOut = this._handleOut; return !handleIn.isZero() && !handleOut.isZero() && handleIn.isCollinear(handleOut); }, clearHandles: function() { this._handleIn._set(0, 0); this._handleOut._set(0, 0); }, getSelection: function() { return this._selection; }, setSelection: function(selection) { var oldSelection = this._selection, path = this._path; this._selection = selection = selection || 0; if (path && selection !== oldSelection) { path._updateSelection(this, oldSelection, selection); path._changed(257); } }, _changeSelection: function(flag, selected) { var selection = this._selection; this.setSelection(selected ? selection | flag : selection & ~flag); }, isSelected: function() { return !!(this._selection & 7); }, setSelected: function(selected) { this._changeSelection(7, selected); }, getIndex: function() { return this._index !== undefined ? this._index : null; }, getPath: function() { return this._path || null; }, getCurve: function() { var path = this._path, index = this._index; if (path) { if (index > 0 && !path._closed && index === path._segments.length - 1) index--; return path.getCurves()[index] || null; } return null; }, getLocation: function() { var curve = this.getCurve(); return curve ? new CurveLocation(curve, this === curve._segment1 ? 0 : 1) : null; }, getNext: function() { var segments = this._path && this._path._segments; return segments && (segments[this._index + 1] || this._path._closed && segments[0]) || null; }, smooth: function(options, _first, _last) { var opts = options || {}, type = opts.type, factor = opts.factor, prev = this.getPrevious(), next = this.getNext(), p0 = (prev || this)._point, p1 = this._point, p2 = (next || this)._point, d1 = p0.getDistance(p1), d2 = p1.getDistance(p2); if (!type || type === 'catmull-rom') { var a = factor === undefined ? 0.5 : factor, d1_a = Math.pow(d1, a), d1_2a = d1_a * d1_a, d2_a = Math.pow(d2, a), d2_2a = d2_a * d2_a; if (!_first && prev) { var A = 2 * d2_2a + 3 * d2_a * d1_a + d1_2a, N = 3 * d2_a * (d2_a + d1_a); this.setHandleIn(N !== 0 ? new Point( (d2_2a * p0._x + A * p1._x - d1_2a * p2._x) / N - p1._x, (d2_2a * p0._y + A * p1._y - d1_2a * p2._y) / N - p1._y) : new Point()); } if (!_last && next) { var A = 2 * d1_2a + 3 * d1_a * d2_a + d2_2a, N = 3 * d1_a * (d1_a + d2_a); this.setHandleOut(N !== 0 ? new Point( (d1_2a * p2._x + A * p1._x - d2_2a * p0._x) / N - p1._x, (d1_2a * p2._y + A * p1._y - d2_2a * p0._y) / N - p1._y) : new Point()); } } else if (type === 'geometric') { if (prev && next) { var vector = p0.subtract(p2), t = factor === undefined ? 0.4 : factor, k = t * d1 / (d1 + d2); if (!_first) this.setHandleIn(vector.multiply(k)); if (!_last) this.setHandleOut(vector.multiply(k - t)); } } else { throw new Error('Smoothing method \'' + type + '\' not supported.'); } }, getPrevious: function() { var segments = this._path && this._path._segments; return segments && (segments[this._index - 1] || this._path._closed && segments[segments.length - 1]) || null; }, isFirst: function() { return !this._index; }, isLast: function() { var path = this._path; return path && this._index === path._segments.length - 1 || false; }, reverse: function() { var handleIn = this._handleIn, handleOut = this._handleOut, tmp = handleIn.clone(); handleIn.set(handleOut); handleOut.set(tmp); }, reversed: function() { return new Segment(this._point, this._handleOut, this._handleIn); }, remove: function() { return this._path ? !!this._path.removeSegment(this._index) : false; }, clone: function() { return new Segment(this._point, this._handleIn, this._handleOut); }, equals: function(segment) { return segment === this || segment && this._class === segment._class && this._point.equals(segment._point) && this._handleIn.equals(segment._handleIn) && this._handleOut.equals(segment._handleOut) || false; }, toString: function() { var parts = [ 'point: ' + this._point ]; if (!this._handleIn.isZero()) parts.push('handleIn: ' + this._handleIn); if (!this._handleOut.isZero()) parts.push('handleOut: ' + this._handleOut); return '{ ' + parts.join(', ') + ' }'; }, transform: function(matrix) { this._transformCoordinates(matrix, new Array(6), true); this._changed(); }, interpolate: function(from, to, factor) { var u = 1 - factor, v = factor, point1 = from._point, point2 = to._point, handleIn1 = from._handleIn, handleIn2 = to._handleIn, handleOut2 = to._handleOut, handleOut1 = from._handleOut; this._point._set( u * point1._x + v * point2._x, u * point1._y + v * point2._y, true); this._handleIn._set( u * handleIn1._x + v * handleIn2._x, u * handleIn1._y + v * handleIn2._y, true); this._handleOut._set( u * handleOut1._x + v * handleOut2._x, u * handleOut1._y + v * handleOut2._y, true); this._changed(); }, _transformCoordinates: function(matrix, coords, change) { var point = this._point, handleIn = !change || !this._handleIn.isZero() ? this._handleIn : null, handleOut = !change || !this._handleOut.isZero() ? this._handleOut : null, x = point._x, y = point._y, i = 2; coords[0] = x; coords[1] = y; if (handleIn) { coords[i++] = handleIn._x + x; coords[i++] = handleIn._y + y; } if (handleOut) { coords[i++] = handleOut._x + x; coords[i++] = handleOut._y + y; } if (matrix) { matrix._transformCoordinates(coords, coords, i / 2); x = coords[0]; y = coords[1]; if (change) { point._x = x; point._y = y; i = 2; if (handleIn) { handleIn._x = coords[i++] - x; handleIn._y = coords[i++] - y; } if (handleOut) { handleOut._x = coords[i++] - x; handleOut._y = coords[i++] - y; } } else { if (!handleIn) { coords[i++] = x; coords[i++] = y; } if (!handleOut) { coords[i++] = x; coords[i++] = y; } } } return coords; } }); var SegmentPoint = Point.extend({ initialize: function SegmentPoint(point, owner, key) { var x, y, selected; if (!point) { x = y = 0; } else if ((x = point[0]) !== undefined) { y = point[1]; } else { var pt = point; if ((x = pt.x) === undefined) { pt = Point.read(arguments); x = pt.x; } y = pt.y; selected = pt.selected; } this._x = x; this._y = y; this._owner = owner; owner[key] = this; if (selected) this.setSelected(true); }, _set: function(x, y) { this._x = x; this._y = y; this._owner._changed(this); return this; }, getX: function() { return this._x; }, setX: function(x) { this._x = x; this._owner._changed(this); }, getY: function() { return this._y; }, setY: function(y) { this._y = y; this._owner._changed(this); }, isZero: function() { var isZero = Numerical.isZero; return isZero(this._x) && isZero(this._y); }, isSelected: function() { return !!(this._owner._selection & this._getSelection()); }, setSelected: function(selected) { this._owner._changeSelection(this._getSelection(), selected); }, _getSelection: function() { var owner = this._owner; return this === owner._point ? 1 : this === owner._handleIn ? 2 : this === owner._handleOut ? 4 : 0; } }); var Curve = Base.extend({ _class: 'Curve', beans: true, initialize: function Curve(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7) { var count = arguments.length, seg1, seg2, point1, point2, handle1, handle2; if (count === 3) { this._path = arg0; seg1 = arg1; seg2 = arg2; } else if (!count) { seg1 = new Segment(); seg2 = new Segment(); } else if (count === 1) { if ('segment1' in arg0) { seg1 = new Segment(arg0.segment1); seg2 = new Segment(arg0.segment2); } else if ('point1' in arg0) { point1 = arg0.point1; handle1 = arg0.handle1; handle2 = arg0.handle2; point2 = arg0.point2; } else if (Array.isArray(arg0)) { point1 = [arg0[0], arg0[1]]; point2 = [arg0[6], arg0[7]]; handle1 = [arg0[2] - arg0[0], arg0[3] - arg0[1]]; handle2 = [arg0[4] - arg0[6], arg0[5] - arg0[7]]; } } else if (count === 2) { seg1 = new Segment(arg0); seg2 = new Segment(arg1); } else if (count === 4) { point1 = arg0; handle1 = arg1; handle2 = arg2; point2 = arg3; } else if (count === 8) { point1 = [arg0, arg1]; point2 = [arg6, arg7]; handle1 = [arg2 - arg0, arg3 - arg1]; handle2 = [arg4 - arg6, arg5 - arg7]; } this._segment1 = seg1 || new Segment(point1, null, handle1); this._segment2 = seg2 || new Segment(point2, handle2, null); }, _serialize: function(options, dictionary) { return Base.serialize(this.hasHandles() ? [this.getPoint1(), this.getHandle1(), this.getHandle2(), this.getPoint2()] : [this.getPoint1(), this.getPoint2()], options, true, dictionary); }, _changed: function() { this._length = this._bounds = undefined; }, clone: function() { return new Curve(this._segment1, this._segment2); }, toString: function() { var parts = [ 'point1: ' + this._segment1._point ]; if (!this._segment1._handleOut.isZero()) parts.push('handle1: ' + this._segment1._handleOut); if (!this._segment2._handleIn.isZero()) parts.push('handle2: ' + this._segment2._handleIn); parts.push('point2: ' + this._segment2._point); return '{ ' + parts.join(', ') + ' }'; }, classify: function() { return Curve.classify(this.getValues()); }, remove: function() { var removed = false; if (this._path) { var segment2 = this._segment2, handleOut = segment2._handleOut; removed = segment2.remove(); if (removed) this._segment1._handleOut.set(handleOut); } return removed; }, getPoint1: function() { return this._segment1._point; }, setPoint1: function() { this._segment1._point.set(Point.read(arguments)); }, getPoint2: function() { return this._segment2._point; }, setPoint2: function() { this._segment2._point.set(Point.read(arguments)); }, getHandle1: function() { return this._segment1._handleOut; }, setHandle1: function() { this._segment1._handleOut.set(Point.read(arguments)); }, getHandle2: function() { return this._segment2._handleIn; }, setHandle2: function() { this._segment2._handleIn.set(Point.read(arguments)); }, getSegment1: function() { return this._segment1; }, getSegment2: function() { return this._segment2; }, getPath: function() { return this._path; }, getIndex: function() { return this._segment1._index; }, getNext: function() { var curves = this._path && this._path._curves; return curves && (curves[this._segment1._index + 1] || this._path._closed && curves[0]) || null; }, getPrevious: function() { var curves = this._path && this._path._curves; return curves && (curves[this._segment1._index - 1] || this._path._closed && curves[curves.length - 1]) || null; }, isFirst: function() { return !this._segment1._index; }, isLast: function() { var path = this._path; return path && this._segment1._index === path._curves.length - 1 || false; }, isSelected: function() { return this.getPoint1().isSelected() && this.getHandle1().isSelected() && this.getHandle2().isSelected() && this.getPoint2().isSelected(); }, setSelected: function(selected) { this.getPoint1().setSelected(selected); this.getHandle1().setSelected(selected); this.getHandle2().setSelected(selected); this.getPoint2().setSelected(selected); }, getValues: function(matrix) { return Curve.getValues(this._segment1, this._segment2, matrix); }, getPoints: function() { var coords = this.getValues(), points = []; for (var i = 0; i < 8; i += 2) points.push(new Point(coords[i], coords[i + 1])); return points; } }, { getLength: function() { if (this._length == null) this._length = Curve.getLength(this.getValues(), 0, 1); return this._length; }, getArea: function() { return Curve.getArea(this.getValues()); }, getLine: function() { return new Line(this._segment1._point, this._segment2._point); }, getPart: function(from, to) { return new Curve(Curve.getPart(this.getValues(), from, to)); }, getPartLength: function(from, to) { return Curve.getLength(this.getValues(), from, to); }, divideAt: function(location) { return this.divideAtTime(location && location.curve === this ? location.time : this.getTimeAt(location)); }, divideAtTime: function(time, _setHandles) { var tMin = 1e-8, tMax = 1 - tMin, res = null; if (time >= tMin && time <= tMax) { var parts = Curve.subdivide(this.getValues(), time), left = parts[0], right = parts[1], setHandles = _setHandles || this.hasHandles(), seg1 = this._segment1, seg2 = this._segment2, path = this._path; if (setHandles) { seg1._handleOut._set(left[2] - left[0], left[3] - left[1]); seg2._handleIn._set(right[4] - right[6],right[5] - right[7]); } var x = left[6], y = left[7], segment = new Segment(new Point(x, y), setHandles && new Point(left[4] - x, left[5] - y), setHandles && new Point(right[2] - x, right[3] - y)); if (path) { path.insert(seg1._index + 1, segment); res = this.getNext(); } else { this._segment2 = segment; this._changed(); res = new Curve(segment, seg2); } } return res; }, splitAt: function(location) { var path = this._path; return path ? path.splitAt(location) : null; }, splitAtTime: function(time) { return this.splitAt(this.getLocationAtTime(time)); }, divide: function(offset, isTime) { return this.divideAtTime(offset === undefined ? 0.5 : isTime ? offset : this.getTimeAt(offset)); }, split: function(offset, isTime) { return this.splitAtTime(offset === undefined ? 0.5 : isTime ? offset : this.getTimeAt(offset)); }, reversed: function() { return new Curve(this._segment2.reversed(), this._segment1.reversed()); }, clearHandles: function() { this._segment1._handleOut._set(0, 0); this._segment2._handleIn._set(0, 0); }, statics: { getValues: function(segment1, segment2, matrix, straight) { var p1 = segment1._point, h1 = segment1._handleOut, h2 = segment2._handleIn, p2 = segment2._point, x1 = p1.x, y1 = p1.y, x2 = p2.x, y2 = p2.y, values = straight ? [ x1, y1, x1, y1, x2, y2, x2, y2 ] : [ x1, y1, x1 + h1._x, y1 + h1._y, x2 + h2._x, y2 + h2._y, x2, y2 ]; if (matrix) matrix._transformCoordinates(values, values, 4); return values; }, subdivide: function(v, t) { var x0 = v[0], y0 = v[1], x1 = v[2], y1 = v[3], x2 = v[4], y2 = v[5], x3 = v[6], y3 = v[7]; if (t === undefined) t = 0.5; var u = 1 - t, x4 = u * x0 + t * x1, y4 = u * y0 + t * y1, x5 = u * x1 + t * x2, y5 = u * y1 + t * y2, x6 = u * x2 + t * x3, y6 = u * y2 + t * y3, x7 = u * x4 + t * x5, y7 = u * y4 + t * y5, x8 = u * x5 + t * x6, y8 = u * y5 + t * y6, x9 = u * x7 + t * x8, y9 = u * y7 + t * y8; return [ [x0, y0, x4, y4, x7, y7, x9, y9], [x9, y9, x8, y8, x6, y6, x3, y3] ]; }, getMonoCurves: function(v, dir) { var curves = [], io = dir ? 0 : 1, o0 = v[io + 0], o1 = v[io + 2], o2 = v[io + 4], o3 = v[io + 6]; if ((o0 >= o1) === (o1 >= o2) && (o1 >= o2) === (o2 >= o3) || Curve.isStraight(v)) { curves.push(v); } else { var a = 3 * (o1 - o2) - o0 + o3, b = 2 * (o0 + o2) - 4 * o1, c = o1 - o0, tMin = 1e-8, tMax = 1 - tMin, roots = [], n = Numerical.solveQuadratic(a, b, c, roots, tMin, tMax); if (!n) { curves.push(v); } else { roots.sort(); var t = roots[0], parts = Curve.subdivide(v, t); curves.push(parts[0]); if (n > 1) { t = (roots[1] - t) / (1 - t); parts = Curve.subdivide(parts[1], t); curves.push(parts[0]); } curves.push(parts[1]); } } return curves; }, solveCubic: function (v, coord, val, roots, min, max) { var v0 = v[coord], v1 = v[coord + 2], v2 = v[coord + 4], v3 = v[coord + 6], res = 0; if ( !(v0 < val && v3 < val && v1 < val && v2 < val || v0 > val && v3 > val && v1 > val && v2 > val)) { var c = 3 * (v1 - v0), b = 3 * (v2 - v1) - c, a = v3 - v0 - c - b; res = Numerical.solveCubic(a, b, c, v0 - val, roots, min, max); } return res; }, getTimeOf: function(v, point) { var p0 = new Point(v[0], v[1]), p3 = new Point(v[6], v[7]), epsilon = 1e-12, geomEpsilon = 1e-7, t = point.isClose(p0, epsilon) ? 0 : point.isClose(p3, epsilon) ? 1 : null; if (t === null) { var coords = [point.x, point.y], roots = []; for (var c = 0; c < 2; c++) { var count = Curve.solveCubic(v, c, coords[c], roots, 0, 1); for (var i = 0; i < count; i++) { var u = roots[i]; if (point.isClose(Curve.getPoint(v, u), geomEpsilon)) return u; } } } return point.isClose(p0, geomEpsilon) ? 0 : point.isClose(p3, geomEpsilon) ? 1 : null; }, getNearestTime: function(v, point) { if (Curve.isStraight(v)) { var x0 = v[0], y0 = v[1], x3 = v[6], y3 = v[7], vx = x3 - x0, vy = y3 - y0, det = vx * vx + vy * vy; if (det === 0) return 0; var u = ((point.x - x0) * vx + (point.y - y0) * vy) / det; return u < 1e-12 ? 0 : u > 0.999999999999 ? 1 : Curve.getTimeOf(v, new Point(x0 + u * vx, y0 + u * vy)); } var count = 100, minDist = Infinity, minT = 0; function refine(t) { if (t >= 0 && t <= 1) { var dist = point.getDistance(Curve.getPoint(v, t), true); if (dist < minDist) { minDist = dist; minT = t; return true; } } } for (var i = 0; i <= count; i++) refine(i / count); var step = 1 / (count * 2); while (step > 1e-8) { if (!refine(minT - step) && !refine(minT + step)) step /= 2; } return minT; }, getPart: function(v, from, to) { var flip = from > to; if (flip) { var tmp = from; from = to; to = tmp; } if (from > 0) v = Curve.subdivide(v, from)[1]; if (to < 1) v = Curve.subdivide(v, (to - from) / (1 - from))[0]; return flip ? [v[6], v[7], v[4], v[5], v[2], v[3], v[0], v[1]] : v; }, isFlatEnough: function(v, flatness) { var x0 = v[0], y0 = v[1], x1 = v[2], y1 = v[3], x2 = v[4], y2 = v[5], x3 = v[6], y3 = v[7], ux = 3 * x1 - 2 * x0 - x3, uy = 3 * y1 - 2 * y0 - y3, vx = 3 * x2 - 2 * x3 - x0, vy = 3 * y2 - 2 * y3 - y0; return Math.max(ux * ux, vx * vx) + Math.max(uy * uy, vy * vy) <= 16 * flatness * flatness; }, getArea: function(v) { var x0 = v[0], y0 = v[1], x1 = v[2], y1 = v[3], x2 = v[4], y2 = v[5], x3 = v[6], y3 = v[7]; return 3 * ((y3 - y0) * (x1 + x2) - (x3 - x0) * (y1 + y2) + y1 * (x0 - x2) - x1 * (y0 - y2) + y3 * (x2 + x0 / 3) - x3 * (y2 + y0 / 3)) / 20; }, getBounds: function(v) { var min = v.slice(0, 2), max = min.slice(), roots = [0, 0]; for (var i = 0; i < 2; i++) Curve._addBounds(v[i], v[i + 2], v[i + 4], v[i + 6], i, 0, min, max, roots); return new Rectangle(min[0], min[1], max[0] - min[0], max[1] - min[1]); }, _addBounds: function(v0, v1, v2, v3, coord, padding, min, max, roots) { function add(value, padding) { var left = value - padding, right = value + padding; if (left < min[coord]) min[coord] = left; if (right > max[coord]) max[coord] = right; } padding /= 2; var minPad = min[coord] + padding, maxPad = max[coord] - padding; if ( v0 < minPad || v1 < minPad || v2 < minPad || v3 < minPad || v0 > maxPad || v1 > maxPad || v2 > maxPad || v3 > maxPad) { if (v1 < v0 != v1 < v3 && v2 < v0 != v2 < v3) { add(v0, 0); add(v3, 0); } else { var a = 3 * (v1 - v2) - v0 + v3, b = 2 * (v0 + v2) - 4 * v1, c = v1 - v0, count = Numerical.solveQuadratic(a, b, c, roots), tMin = 1e-8, tMax = 1 - tMin; add(v3, 0); for (var i = 0; i < count; i++) { var t = roots[i], u = 1 - t; if (tMin <= t && t <= tMax) add(u * u * u * v0 + 3 * u * u * t * v1 + 3 * u * t * t * v2 + t * t * t * v3, padding); } } } } }}, Base.each( ['getBounds', 'getStrokeBounds', 'getHandleBounds'], function(name) { this[name] = function() { if (!this._bounds) this._bounds = {}; var bounds = this._bounds[name]; if (!bounds) { bounds = this._bounds[name] = Path[name]( [this._segment1, this._segment2], false, this._path); } return bounds.clone(); }; }, { }), Base.each({ isStraight: function(p1, h1, h2, p2) { if (h1.isZero() && h2.isZero()) { return true; } else { var v = p2.subtract(p1); if (v.isZero()) { return false; } else if (v.isCollinear(h1) && v.isCollinear(h2)) { var l = new Line(p1, p2), epsilon = 1e-7; if (l.getDistance(p1.add(h1)) < epsilon && l.getDistance(p2.add(h2)) < epsilon) { var div = v.dot(v), s1 = v.dot(h1) / div, s2 = v.dot(h2) / div; return s1 >= 0 && s1 <= 1 && s2 <= 0 && s2 >= -1; } } } return false; }, isLinear: function(p1, h1, h2, p2) { var third = p2.subtract(p1).divide(3); return h1.equals(third) && h2.negate().equals(third); } }, function(test, name) { this[name] = function(epsilon) { var seg1 = this._segment1, seg2 = this._segment2; return test(seg1._point, seg1._handleOut, seg2._handleIn, seg2._point, epsilon); }; this.statics[name] = function(v, epsilon) { var x0 = v[0], y0 = v[1], x3 = v[6], y3 = v[7]; return test( new Point(x0, y0), new Point(v[2] - x0, v[3] - y0), new Point(v[4] - x3, v[5] - y3), new Point(x3, y3), epsilon); }; }, { statics: {}, hasHandles: function() { return !this._segment1._handleOut.isZero() || !this._segment2._handleIn.isZero(); }, hasLength: function(epsilon) { return (!this.getPoint1().equals(this.getPoint2()) || this.hasHandles()) && this.getLength() > (epsilon || 0); }, isCollinear: function(curve) { return curve && this.isStraight() && curve.isStraight() && this.getLine().isCollinear(curve.getLine()); }, isHorizontal: function() { return this.isStraight() && Math.abs(this.getTangentAtTime(0.5).y) < 1e-8; }, isVertical: function() { return this.isStraight() && Math.abs(this.getTangentAtTime(0.5).x) < 1e-8; } }), { beans: false, getLocationAt: function(offset, _isTime) { return this.getLocationAtTime( _isTime ? offset : this.getTimeAt(offset)); }, getLocationAtTime: function(t) { return t != null && t >= 0 && t <= 1 ? new CurveLocation(this, t) : null; }, getTimeAt: function(offset, start) { return Curve.getTimeAt(this.getValues(), offset, start); }, getParameterAt: '#getTimeAt', getTimesWithTangent: function () { var tangent = Point.read(arguments); return tangent.isZero() ? [] : Curve.getTimesWithTangent(this.getValues(), tangent); }, getOffsetAtTime: function(t) { return this.getPartLength(0, t); }, getLocationOf: function() { return this.getLocationAtTime(this.getTimeOf(Point.read(arguments))); }, getOffsetOf: function() { var loc = this.getLocationOf.apply(this, arguments); return loc ? loc.getOffset() : null; }, getTimeOf: function() { return Curve.getTimeOf(this.getValues(), Point.read(arguments)); }, getParameterOf: '#getTimeOf', getNearestLocation: function() { var point = Point.read(arguments), values = this.getValues(), t = Curve.getNearestTime(values, point), pt = Curve.getPoint(values, t); return new CurveLocation(this, t, pt, null, point.getDistance(pt)); }, getNearestPoint: function() { var loc = this.getNearestLocation.apply(this, arguments); return loc ? loc.getPoint() : loc; } }, new function() { var methods = ['getPoint', 'getTangent', 'getNormal', 'getWeightedTangent', 'getWeightedNormal', 'getCurvature']; return Base.each(methods, function(name) { this[name + 'At'] = function(location, _isTime) { var values = this.getValues(); return Curve[name](values, _isTime ? location : Curve.getTimeAt(values, location)); }; this[name + 'AtTime'] = function(time) { return Curve[name](this.getValues(), time); }; }, { statics: { _evaluateMethods: methods } } ); }, new function() { function getLengthIntegrand(v) { var x0 = v[0], y0 = v[1], x1 = v[2], y1 = v[3], x2 = v[4], y2 = v[5], x3 = v[6], y3 = v[7], ax = 9 * (x1 - x2) + 3 * (x3 - x0), bx = 6 * (x0 + x2) - 12 * x1, cx = 3 * (x1 - x0), ay = 9 * (y1 - y2) + 3 * (y3 - y0), by = 6 * (y0 + y2) - 12 * y1, cy = 3 * (y1 - y0); return function(t) { var dx = (ax * t + bx) * t + cx, dy = (ay * t + by) * t + cy; return Math.sqrt(dx * dx + dy * dy); }; } function getIterations(a, b) { return Math.max(2, Math.min(16, Math.ceil(Math.abs(b - a) * 32))); } function evaluate(v, t, type, normalized) { if (t == null || t < 0 || t > 1) return null; var x0 = v[0], y0 = v[1], x1 = v[2], y1 = v[3], x2 = v[4], y2 = v[5], x3 = v[6], y3 = v[7], isZero = Numerical.isZero; if (isZero(x1 - x0) && isZero(y1 - y0)) { x1 = x0; y1 = y0; } if (isZero(x2 - x3) && isZero(y2 - y3)) { x2 = x3; y2 = y3; } var cx = 3 * (x1 - x0), bx = 3 * (x2 - x1) - cx, ax = x3 - x0 - cx - bx, cy = 3 * (y1 - y0), by = 3 * (y2 - y1) - cy, ay = y3 - y0 - cy - by, x, y; if (type === 0) { x = t === 0 ? x0 : t === 1 ? x3 : ((ax * t + bx) * t + cx) * t + x0; y = t === 0 ? y0 : t === 1 ? y3 : ((ay * t + by) * t + cy) * t + y0; } else { var tMin = 1e-8, tMax = 1 - tMin; if (t < tMin) { x = cx; y = cy; } else if (t > tMax) { x = 3 * (x3 - x2); y = 3 * (y3 - y2); } else { x = (3 * ax * t + 2 * bx) * t + cx; y = (3 * ay * t + 2 * by) * t + cy; } if (normalized) { if (x === 0 && y === 0 && (t < tMin || t > tMax)) { x = x2 - x1; y = y2 - y1; } var len = Math.sqrt(x * x + y * y); if (len) { x /= len; y /= len; } } if (type === 3) { var x2 = 6 * ax * t + 2 * bx, y2 = 6 * ay * t + 2 * by, d = Math.pow(x * x + y * y, 3 / 2); x = d !== 0 ? (x * y2 - y * x2) / d : 0; y = 0; } } return type === 2 ? new Point(y, -x) : new Point(x, y); } return { statics: { classify: function(v) { var x0 = v[0], y0 = v[1], x1 = v[2], y1 = v[3], x2 = v[4], y2 = v[5], x3 = v[6], y3 = v[7], a1 = x0 * (y3 - y2) + y0 * (x2 - x3) + x3 * y2 - y3 * x2, a2 = x1 * (y0 - y3) + y1 * (x3 - x0) + x0 * y3 - y0 * x3, a3 = x2 * (y1 - y0) + y2 * (x0 - x1) + x1 * y0 - y1 * x0, d3 = 3 * a3, d2 = d3 - a2, d1 = d2 - a2 + a1, l = Math.sqrt(d1 * d1 + d2 * d2 + d3 * d3), s = l !== 0 ? 1 / l : 0, isZero = Numerical.isZero, serpentine = 'serpentine'; d1 *= s; d2 *= s; d3 *= s; function type(type, t1, t2) { var hasRoots = t1 !== undefined, t1Ok = hasRoots && t1 > 0 && t1 < 1, t2Ok = hasRoots && t2 > 0 && t2 < 1; if (hasRoots && (!(t1Ok || t2Ok) || type === 'loop' && !(t1Ok && t2Ok))) { type = 'arch'; t1Ok = t2Ok = false; } return { type: type, roots: t1Ok || t2Ok ? t1Ok && t2Ok ? t1 < t2 ? [t1, t2] : [t2, t1] : [t1Ok ? t1 : t2] : null }; } if (isZero(d1)) { return isZero(d2) ? type(isZero(d3) ? 'line' : 'quadratic') : type(serpentine, d3 / (3 * d2)); } var d = 3 * d2 * d2 - 4 * d1 * d3; if (isZero(d)) { return type('cusp', d2 / (2 * d1)); } var f1 = d > 0 ? Math.sqrt(d / 3) : Math.sqrt(-d), f2 = 2 * d1; return type(d > 0 ? serpentine : 'loop', (d2 + f1) / f2, (d2 - f1) / f2); }, getLength: function(v, a, b, ds) { if (a === undefined) a = 0; if (b === undefined) b = 1; if (Curve.isStraight(v)) { var c = v; if (b < 1) { c = Curve.subdivide(c, b)[0]; a /= b; } if (a > 0) { c = Curve.subdivide(c, a)[1]; } var dx = c[6] - c[0], dy = c[7] - c[1]; return Math.sqrt(dx * dx + dy * dy); } return Numerical.integrate(ds || getLengthIntegrand(v), a, b, getIterations(a, b)); }, getTimeAt: function(v, offset, start) { if (start === undefined) start = offset < 0 ? 1 : 0; if (offset === 0) return start; var abs = Math.abs, epsilon = 1e-12, forward = offset > 0, a = forward ? start : 0, b = forward ? 1 : start, ds = getLengthIntegrand(v), rangeLength = Curve.getLength(v, a, b, ds), diff = abs(offset) - rangeLength; if (abs(diff) < epsilon) { return forward ? b : a; } else if (diff > epsilon) { return null; } var guess = offset / rangeLength, length = 0; function f(t) { length += Numerical.integrate(ds, start, t, getIterations(start, t)); start = t; return length - offset; } return Numerical.findRoot(f, ds, start + guess, a, b, 32, 1e-12); }, getPoint: function(v, t) { return evaluate(v, t, 0, false); }, getTangent: function(v, t) { return evaluate(v, t, 1, true); }, getWeightedTangent: function(v, t) { return evaluate(v, t, 1, false); }, getNormal: function(v, t) { return evaluate(v, t, 2, true); }, getWeightedNormal: function(v, t) { return evaluate(v, t, 2, false); }, getCurvature: function(v, t) { return evaluate(v, t, 3, false).x; }, getPeaks: function(v) { var x0 = v[0], y0 = v[1], x1 = v[2], y1 = v[3], x2 = v[4], y2 = v[5], x3 = v[6], y3 = v[7], ax = -x0 + 3 * x1 - 3 * x2 + x3, bx = 3 * x0 - 6 * x1 + 3 * x2, cx = -3 * x0 + 3 * x1, ay = -y0 + 3 * y1 - 3 * y2 + y3, by = 3 * y0 - 6 * y1 + 3 * y2, cy = -3 * y0 + 3 * y1, tMin = 1e-8, tMax = 1 - tMin, roots = []; Numerical.solveCubic( 9 * (ax * ax + ay * ay), 9 * (ax * bx + by * ay), 2 * (bx * bx + by * by) + 3 * (cx * ax + cy * ay), (cx * bx + by * cy), roots, tMin, tMax); return roots.sort(); } }}; }, new function() { function addLocation(locations, include, c1, t1, c2, t2, overlap) { var excludeStart = !overlap && c1.getPrevious() === c2, excludeEnd = !overlap && c1 !== c2 && c1.getNext() === c2, tMin = 1e-8, tMax = 1 - tMin; if (t1 !== null && t1 >= (excludeStart ? tMin : 0) && t1 <= (excludeEnd ? tMax : 1)) { if (t2 !== null && t2 >= (excludeEnd ? tMin : 0) && t2 <= (excludeStart ? tMax : 1)) { var loc1 = new CurveLocation(c1, t1, null, overlap), loc2 = new CurveLocation(c2, t2, null, overlap); loc1._intersection = loc2; loc2._intersection = loc1; if (!include || include(loc1)) { CurveLocation.insert(locations, loc1, true); } } } } function addCurveIntersections(v1, v2, c1, c2, locations, include, flip, recursion, calls, tMin, tMax, uMin, uMax) { if (++calls >= 4096 || ++recursion >= 40) return calls; var fatLineEpsilon = 1e-9, q0x = v2[0], q0y = v2[1], q3x = v2[6], q3y = v2[7], getSignedDistance = Line.getSignedDistance, d1 = getSignedDistance(q0x, q0y, q3x, q3y, v2[2], v2[3]), d2 = getSignedDistance(q0x, q0y, q3x, q3y, v2[4], v2[5]), factor = d1 * d2 > 0 ? 3 / 4 : 4 / 9, dMin = factor * Math.min(0, d1, d2), dMax = factor * Math.max(0, d1, d2), dp0 = getSignedDistance(q0x, q0y, q3x, q3y, v1[0], v1[1]), dp1 = getSignedDistance(q0x, q0y, q3x, q3y, v1[2], v1[3]), dp2 = getSignedDistance(q0x, q0y, q3x, q3y, v1[4], v1[5]), dp3 = getSignedDistance(q0x, q0y, q3x, q3y, v1[6], v1[7]), hull = getConvexHull(dp0, dp1, dp2, dp3), top = hull[0], bottom = hull[1], tMinClip, tMaxClip; if (d1 === 0 && d2 === 0 && dp0 === 0 && dp1 === 0 && dp2 === 0 && dp3 === 0 || (tMinClip = clipConvexHull(top, bottom, dMin, dMax)) == null || (tMaxClip = clipConvexHull(top.reverse(), bottom.reverse(), dMin, dMax)) == null) return calls; var tMinNew = tMin + (tMax - tMin) * tMinClip, tMaxNew = tMin + (tMax - tMin) * tMaxClip; if (Math.max(uMax - uMin, tMaxNew - tMinNew) < fatLineEpsilon) { var t = (tMinNew + tMaxNew) / 2, u = (uMin + uMax) / 2; addLocation(locations, include, flip ? c2 : c1, flip ? u : t, flip ? c1 : c2, flip ? t : u); } else { v1 = Curve.getPart(v1, tMinClip, tMaxClip); var uDiff = uMax - uMin; if (tMaxClip - tMinClip > 0.8) { if (tMaxNew - tMinNew > uDiff) { var parts = Curve.subdivide(v1, 0.5), t = (tMinNew + tMaxNew) / 2; calls = addCurveIntersections( v2, parts[0], c2, c1, locations, include, !flip, recursion, calls, uMin, uMax, tMinNew, t); calls = addCurveIntersections( v2, parts[1], c2, c1, locations, include, !flip, recursion, calls, uMin, uMax, t, tMaxNew); } else { var parts = Curve.subdivide(v2, 0.5), u = (uMin + uMax) / 2; calls = addCurveIntersections( parts[0], v1, c2, c1, locations, include, !flip, recursion, calls, uMin, u, tMinNew, tMaxNew); calls = addCurveIntersections( parts[1], v1, c2, c1, locations, include, !flip, recursion, calls, u, uMax, tMinNew, tMaxNew); } } else { if (uDiff === 0 || uDiff >= fatLineEpsilon) { calls = addCurveIntersections( v2, v1, c2, c1, locations, include, !flip, recursion, calls, uMin, uMax, tMinNew, tMaxNew); } else { calls = addCurveIntersections( v1, v2, c1, c2, locations, include, flip, recursion, calls, tMinNew, tMaxNew, uMin, uMax); } } } return calls; } function getConvexHull(dq0, dq1, dq2, dq3) { var p0 = [ 0, dq0 ], p1 = [ 1 / 3, dq1 ], p2 = [ 2 / 3, dq2 ], p3 = [ 1, dq3 ], dist1 = dq1 - (2 * dq0 + dq3) / 3, dist2 = dq2 - (dq0 + 2 * dq3) / 3, hull; if (dist1 * dist2 < 0) { hull = [[p0, p1, p3], [p0, p2, p3]]; } else { var distRatio = dist1 / dist2; hull = [ distRatio >= 2 ? [p0, p1, p3] : distRatio <= 0.5 ? [p0, p2, p3] : [p0, p1, p2, p3], [p0, p3] ]; } return (dist1 || dist2) < 0 ? hull.reverse() : hull; } function clipConvexHull(hullTop, hullBottom, dMin, dMax) { if (hullTop[0][1] < dMin) { return clipConvexHullPart(hullTop, true, dMin); } else if (hullBottom[0][1] > dMax) { return clipConvexHullPart(hullBottom, false, dMax); } else { return hullTop[0][0]; } } function clipConvexHullPart(part, top, threshold) { var px = part[0][0], py = part[0][1]; for (var i = 1, l = part.length; i < l; i++) { var qx = part[i][0], qy = part[i][1]; if (top ? qy >= threshold : qy <= threshold) { return qy === threshold ? qx : px + (threshold - py) * (qx - px) / (qy - py); } px = qx; py = qy; } return null; } function getCurveLineIntersections(v, px, py, vx, vy) { var isZero = Numerical.isZero; if (isZero(vx) && isZero(vy)) { var t = Curve.getTimeOf(v, new Point(px, py)); return t === null ? [] : [t]; } var angle = Math.atan2(-vy, vx), sin = Math.sin(angle), cos = Math.cos(angle), rv = [], roots = []; for (var i = 0; i < 8; i += 2) { var x = v[i] - px, y = v[i + 1] - py; rv.push( x * cos - y * sin, x * sin + y * cos); } Curve.solveCubic(rv, 1, 0, roots, 0, 1); return roots; } function addCurveLineIntersections(v1, v2, c1, c2, locations, include, flip) { var x1 = v2[0], y1 = v2[1], x2 = v2[6], y2 = v2[7], roots = getCurveLineIntersections(v1, x1, y1, x2 - x1, y2 - y1); for (var i = 0, l = roots.length; i < l; i++) { var t1 = roots[i], p1 = Curve.getPoint(v1, t1), t2 = Curve.getTimeOf(v2, p1); if (t2 !== null) { addLocation(locations, include, flip ? c2 : c1, flip ? t2 : t1, flip ? c1 : c2, flip ? t1 : t2); } } } function addLineIntersection(v1, v2, c1, c2, locations, include) { var pt = Line.intersect( v1[0], v1[1], v1[6], v1[7], v2[0], v2[1], v2[6], v2[7]); if (pt) { addLocation(locations, include, c1, Curve.getTimeOf(v1, pt), c2, Curve.getTimeOf(v2, pt)); } } function getCurveIntersections(v1, v2, c1, c2, locations, include) { var epsilon = 1e-12, min = Math.min, max = Math.max; if (max(v1[0], v1[2], v1[4], v1[6]) + epsilon > min(v2[0], v2[2], v2[4], v2[6]) && min(v1[0], v1[2], v1[4], v1[6]) - epsilon < max(v2[0], v2[2], v2[4], v2[6]) && max(v1[1], v1[3], v1[5], v1[7]) + epsilon > min(v2[1], v2[3], v2[5], v2[7]) && min(v1[1], v1[3], v1[5], v1[7]) - epsilon < max(v2[1], v2[3], v2[5], v2[7])) { var overlaps = getOverlaps(v1, v2); if (overlaps) { for (var i = 0; i < 2; i++) { var overlap = overlaps[i]; addLocation(locations, include, c1, overlap[0], c2, overlap[1], true); } } else { var straight1 = Curve.isStraight(v1), straight2 = Curve.isStraight(v2), straight = straight1 && straight2, flip = straight1 && !straight2, before = locations.length; (straight ? addLineIntersection : straight1 || straight2 ? addCurveLineIntersections : addCurveIntersections)( flip ? v2 : v1, flip ? v1 : v2, flip ? c2 : c1, flip ? c1 : c2, locations, include, flip, 0, 0, 0, 1, 0, 1); if (!straight || locations.length === before) { for (var i = 0; i < 4; i++) { var t1 = i >> 1, t2 = i & 1, i1 = t1 * 6, i2 = t2 * 6, p1 = new Point(v1[i1], v1[i1 + 1]), p2 = new Point(v2[i2], v2[i2 + 1]); if (p1.isClose(p2, epsilon)) { addLocation(locations, include, c1, t1, c2, t2); } } } } } return locations; } function getSelfIntersection(v1, c1, locations, include) { var info = Curve.classify(v1); if (info.type === 'loop') { var roots = info.roots; addLocation(locations, include, c1, roots[0], c1, roots[1]); } return locations; } function getIntersections(curves1, curves2, include, matrix1, matrix2, _returnFirst) { var epsilon = 1e-7, self = !curves2; if (self) curves2 = curves1; var length1 = curves1.length, length2 = curves2.length, values1 = new Array(length1), values2 = self ? values1 : new Array(length2), locations = []; for (var i = 0; i < length1; i++) { values1[i] = curves1[i].getValues(matrix1); } if (!self) { for (var i = 0; i < length2; i++) { values2[i] = curves2[i].getValues(matrix2); } } var boundsCollisions = CollisionDetection.findCurveBoundsCollisions( values1, values2, epsilon); for (var index1 = 0; index1 < length1; index1++) { var curve1 = curves1[index1], v1 = values1[index1]; if (self) { getSelfIntersection(v1, curve1, locations, include); } var collisions1 = boundsCollisions[index1]; if (collisions1) { for (var j = 0; j < collisions1.length; j++) { if (_returnFirst && locations.length) return locations; var index2 = collisions1[j]; if (!self || index2 > index1) { var curve2 = curves2[index2], v2 = values2[index2]; getCurveIntersections( v1, v2, curve1, curve2, locations, include); } } } } return locations; } function getOverlaps(v1, v2) { function getSquaredLineLength(v) { var x = v[6] - v[0], y = v[7] - v[1]; return x * x + y * y; } var abs = Math.abs, getDistance = Line.getDistance, timeEpsilon = 1e-8, geomEpsilon = 1e-7, straight1 = Curve.isStraight(v1), straight2 = Curve.isStraight(v2), straightBoth = straight1 && straight2, flip = getSquaredLineLength(v1) < getSquaredLineLength(v2), l1 = flip ? v2 : v1, l2 = flip ? v1 : v2, px = l1[0], py = l1[1], vx = l1[6] - px, vy = l1[7] - py; if (getDistance(px, py, vx, vy, l2[0], l2[1], true) < geomEpsilon && getDistance(px, py, vx, vy, l2[6], l2[7], true) < geomEpsilon) { if (!straightBoth && getDistance(px, py, vx, vy, l1[2], l1[3], true) < geomEpsilon && getDistance(px, py, vx, vy, l1[4], l1[5], true) < geomEpsilon && getDistance(px, py, vx, vy, l2[2], l2[3], true) < geomEpsilon && getDistance(px, py, vx, vy, l2[4], l2[5], true) < geomEpsilon) { straight1 = straight2 = straightBoth = true; } } else if (straightBoth) { return null; } if (straight1 ^ straight2) { return null; } var v = [v1, v2], pairs = []; for (var i = 0; i < 4 && pairs.length < 2; i++) { var i1 = i & 1, i2 = i1 ^ 1, t1 = i >> 1, t2 = Curve.getTimeOf(v[i1], new Point( v[i2][t1 ? 6 : 0], v[i2][t1 ? 7 : 1])); if (t2 != null) { var pair = i1 ? [t1, t2] : [t2, t1]; if (!pairs.length || abs(pair[0] - pairs[0][0]) > timeEpsilon && abs(pair[1] - pairs[0][1]) > timeEpsilon) { pairs.push(pair); } } if (i > 2 && !pairs.length) break; } if (pairs.length !== 2) { pairs = null; } else if (!straightBoth) { var o1 = Curve.getPart(v1, pairs[0][0], pairs[1][0]), o2 = Curve.getPart(v2, pairs[0][1], pairs[1][1]); if (abs(o2[2] - o1[2]) > geomEpsilon || abs(o2[3] - o1[3]) > geomEpsilon || abs(o2[4] - o1[4]) > geomEpsilon || abs(o2[5] - o1[5]) > geomEpsilon) pairs = null; } return pairs; } function getTimesWithTangent(v, tangent) { var x0 = v[0], y0 = v[1], x1 = v[2], y1 = v[3], x2 = v[4], y2 = v[5], x3 = v[6], y3 = v[7], normalized = tangent.normalize(), tx = normalized.x, ty = normalized.y, ax = 3 * x3 - 9 * x2 + 9 * x1 - 3 * x0, ay = 3 * y3 - 9 * y2 + 9 * y1 - 3 * y0, bx = 6 * x2 - 12 * x1 + 6 * x0, by = 6 * y2 - 12 * y1 + 6 * y0, cx = 3 * x1 - 3 * x0, cy = 3 * y1 - 3 * y0, den = 2 * ax * ty - 2 * ay * tx, times = []; if (Math.abs(den) < Numerical.CURVETIME_EPSILON) { var num = ax * cy - ay * cx, den = ax * by - ay * bx; if (den != 0) { var t = -num / den; if (t >= 0 && t <= 1) times.push(t); } } else { var delta = (bx * bx - 4 * ax * cx) * ty * ty + (-2 * bx * by + 4 * ay * cx + 4 * ax * cy) * tx * ty + (by * by - 4 * ay * cy) * tx * tx, k = bx * ty - by * tx; if (delta >= 0 && den != 0) { var d = Math.sqrt(delta), t0 = -(k + d) / den, t1 = (-k + d) / den; if (t0 >= 0 && t0 <= 1) times.push(t0); if (t1 >= 0 && t1 <= 1) times.push(t1); } } return times; } return { getIntersections: function(curve) { var v1 = this.getValues(), v2 = curve && curve !== this && curve.getValues(); return v2 ? getCurveIntersections(v1, v2, this, curve, []) : getSelfIntersection(v1, this, []); }, statics: { getOverlaps: getOverlaps, getIntersections: getIntersections, getCurveLineIntersections: getCurveLineIntersections, getTimesWithTangent: getTimesWithTangent } }; }); var CurveLocation = Base.extend({ _class: 'CurveLocation', initialize: function CurveLocation(curve, time, point, _overlap, _distance) { if (time >= 0.99999999) { var next = curve.getNext(); if (next) { time = 0; curve = next; } } this._setCurve(curve); this._time = time; this._point = point || curve.getPointAtTime(time); this._overlap = _overlap; this._distance = _distance; this._intersection = this._next = this._previous = null; }, _setPath: function(path) { this._path = path; this._version = path ? path._version : 0; }, _setCurve: function(curve) { this._setPath(curve._path); this._curve = curve; this._segment = null; this._segment1 = curve._segment1; this._segment2 = curve._segment2; }, _setSegment: function(segment) { var curve = segment.getCurve(); if (curve) { this._setCurve(curve); } else { this._setPath(segment._path); this._segment1 = segment; this._segment2 = null; } this._segment = segment; this._time = segment === this._segment1 ? 0 : 1; this._point = segment._point.clone(); }, getSegment: function() { var segment = this._segment; if (!segment) { var curve = this.getCurve(), time = this.getTime(); if (time === 0) { segment = curve._segment1; } else if (time === 1) { segment = curve._segment2; } else if (time != null) { segment = curve.getPartLength(0, time) < curve.getPartLength(time, 1) ? curve._segment1 : curve._segment2; } this._segment = segment; } return segment; }, getCurve: function() { var path = this._path, that = this; if (path && path._version !== this._version) { this._time = this._offset = this._curveOffset = this._curve = null; } function trySegment(segment) { var curve = segment && segment.getCurve(); if (curve && (that._time = curve.getTimeOf(that._point)) != null) { that._setCurve(curve); return curve; } } return this._curve || trySegment(this._segment) || trySegment(this._segment1) || trySegment(this._segment2.getPrevious()); }, getPath: function() { var curve = this.getCurve(); return curve && curve._path; }, getIndex: function() { var curve = this.getCurve(); return curve && curve.getIndex(); }, getTime: function() { var curve = this.getCurve(), time = this._time; return curve && time == null ? this._time = curve.getTimeOf(this._point) : time; }, getParameter: '#getTime', getPoint: function() { return this._point; }, getOffset: function() { var offset = this._offset; if (offset == null) { offset = 0; var path = this.getPath(), index = this.getIndex(); if (path && index != null) { var curves = path.getCurves(); for (var i = 0; i < index; i++) offset += curves[i].getLength(); } this._offset = offset += this.getCurveOffset(); } return offset; }, getCurveOffset: function() { var offset = this._curveOffset; if (offset == null) { var curve = this.getCurve(), time = this.getTime(); this._curveOffset = offset = time != null && curve && curve.getPartLength(0, time); } return offset; }, getIntersection: function() { return this._intersection; }, getDistance: function() { return this._distance; }, divide: function() { var curve = this.getCurve(), res = curve && curve.divideAtTime(this.getTime()); if (res) { this._setSegment(res._segment1); } return res; }, split: function() { var curve = this.getCurve(), path = curve._path, res = curve && curve.splitAtTime(this.getTime()); if (res) { this._setSegment(path.getLastSegment()); } return res; }, equals: function(loc, _ignoreOther) { var res = this === loc; if (!res && loc instanceof CurveLocation) { var c1 = this.getCurve(), c2 = loc.getCurve(), p1 = c1._path, p2 = c2._path; if (p1 === p2) { var abs = Math.abs, epsilon = 1e-7, diff = abs(this.getOffset() - loc.getOffset()), i1 = !_ignoreOther && this._intersection, i2 = !_ignoreOther && loc._intersection; res = (diff < epsilon || p1 && abs(p1.getLength() - diff) < epsilon) && (!i1 && !i2 || i1 && i2 && i1.equals(i2, true)); } } return res; }, toString: function() { var parts = [], point = this.getPoint(), f = Formatter.instance; if (point) parts.push('point: ' + point); var index = this.getIndex(); if (index != null) parts.push('index: ' + index); var time = this.getTime(); if (time != null) parts.push('time: ' + f.number(time)); if (this._distance != null) parts.push('distance: ' + f.number(this._distance)); return '{ ' + parts.join(', ') + ' }'; }, isTouching: function() { var inter = this._intersection; if (inter && this.getTangent().isCollinear(inter.getTangent())) { var curve1 = this.getCurve(), curve2 = inter.getCurve(); return !(curve1.isStraight() && curve2.isStraight() && curve1.getLine().intersect(curve2.getLine())); } return false; }, isCrossing: function() { var inter = this._intersection; if (!inter) return false; var t1 = this.getTime(), t2 = inter.getTime(), tMin = 1e-8, tMax = 1 - tMin, t1Inside = t1 >= tMin && t1 <= tMax, t2Inside = t2 >= tMin && t2 <= tMax; if (t1Inside && t2Inside) return !this.isTouching(); var c2 = this.getCurve(), c1 = c2 && t1 < tMin ? c2.getPrevious() : c2, c4 = inter.getCurve(), c3 = c4 && t2 < tMin ? c4.getPrevious() : c4; if (t1 > tMax) c2 = c2.getNext(); if (t2 > tMax) c4 = c4.getNext(); if (!c1 || !c2 || !c3 || !c4) return false; var offsets = []; function addOffsets(curve, end) { var v = curve.getValues(), roots = Curve.classify(v).roots || Curve.getPeaks(v), count = roots.length, offset = Curve.getLength(v, end && count ? roots[count - 1] : 0, !end && count ? roots[0] : 1); offsets.push(count ? offset : offset / 32); } function isInRange(angle, min, max) { return min < max ? angle > min && angle < max : angle > min || angle < max; } if (!t1Inside) { addOffsets(c1, true); addOffsets(c2, false); } if (!t2Inside) { addOffsets(c3, true); addOffsets(c4, false); } var pt = this.getPoint(), offset = Math.min.apply(Math, offsets), v2 = t1Inside ? c2.getTangentAtTime(t1) : c2.getPointAt(offset).subtract(pt), v1 = t1Inside ? v2.negate() : c1.getPointAt(-offset).subtract(pt), v4 = t2Inside ? c4.getTangentAtTime(t2) : c4.getPointAt(offset).subtract(pt), v3 = t2Inside ? v4.negate() : c3.getPointAt(-offset).subtract(pt), a1 = v1.getAngle(), a2 = v2.getAngle(), a3 = v3.getAngle(), a4 = v4.getAngle(); return !!(t1Inside ? (isInRange(a1, a3, a4) ^ isInRange(a2, a3, a4)) && (isInRange(a1, a4, a3) ^ isInRange(a2, a4, a3)) : (isInRange(a3, a1, a2) ^ isInRange(a4, a1, a2)) && (isInRange(a3, a2, a1) ^ isInRange(a4, a2, a1))); }, hasOverlap: function() { return !!this._overlap; } }, Base.each(Curve._evaluateMethods, function(name) { var get = name + 'At'; this[name] = function() { var curve = this.getCurve(), time = this.getTime(); return time != null && curve && curve[get](time, true); }; }, { preserve: true }), new function() { function insert(locations, loc, merge) { var length = locations.length, l = 0, r = length - 1; function search(index, dir) { for (var i = index + dir; i >= -1 && i <= length; i += dir) { var loc2 = locations[((i % length) + length) % length]; if (!loc.getPoint().isClose(loc2.getPoint(), 1e-7)) break; if (loc.equals(loc2)) return loc2; } return null; } while (l <= r) { var m = (l + r) >>> 1, loc2 = locations[m], found; if (merge && (found = loc.equals(loc2) ? loc2 : (search(m, -1) || search(m, 1)))) { if (loc._overlap) { found._overlap = found._intersection._overlap = true; } return found; } var path1 = loc.getPath(), path2 = loc2.getPath(), diff = path1 !== path2 ? path1._id - path2._id : (loc.getIndex() + loc.getTime()) - (loc2.getIndex() + loc2.getTime()); if (diff < 0) { r = m - 1; } else { l = m + 1; } } locations.splice(l, 0, loc); return loc; } return { statics: { insert: insert, expand: function(locations) { var expanded = locations.slice(); for (var i = locations.length - 1; i >= 0; i--) { insert(expanded, locations[i]._intersection, false); } return expanded; } }}; }); var PathItem = Item.extend({ _class: 'PathItem', _selectBounds: false, _canScaleStroke: true, beans: true, initialize: function PathItem() { }, statics: { create: function(arg) { var data, segments, compound; if (Base.isPlainObject(arg)) { segments = arg.segments; data = arg.pathData; } else if (Array.isArray(arg)) { segments = arg; } else if (typeof arg === 'string') { data = arg; } if (segments) { var first = segments[0]; compound = first && Array.isArray(first[0]); } else if (data) { compound = (data.match(/m/gi) || []).length > 1 || /z\s*\S+/i.test(data); } var ctor = compound ? CompoundPath : Path; return new ctor(arg); } }, _asPathItem: function() { return this; }, isClockwise: function() { return this.getArea() >= 0; }, setClockwise: function(clockwise) { if (this.isClockwise() != (clockwise = !!clockwise)) this.reverse(); }, setPathData: function(data) { var parts = data && data.match(/[mlhvcsqtaz][^mlhvcsqtaz]*/ig), coords, relative = false, previous, control, current = new Point(), start = new Point(); function getCoord(index, coord) { var val = +coords[index]; if (relative) val += current[coord]; return val; } function getPoint(index) { return new Point( getCoord(index, 'x'), getCoord(index + 1, 'y') ); } this.clear(); for (var i = 0, l = parts && parts.length; i < l; i++) { var part = parts[i], command = part[0], lower = command.toLowerCase(); coords = part.match(/[+-]?(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g); var length = coords && coords.length; relative = command === lower; if (previous === 'z' && !/[mz]/.test(lower)) this.moveTo(current); switch (lower) { case 'm': case 'l': var move = lower === 'm'; for (var j = 0; j < length; j += 2) { this[move ? 'moveTo' : 'lineTo'](current = getPoint(j)); if (move) { start = current; move = false; } } control = current; break; case 'h': case 'v': var coord = lower === 'h' ? 'x' : 'y'; current = current.clone(); for (var j = 0; j < length; j++) { current[coord] = getCoord(j, coord); this.lineTo(current); } control = current; break; case 'c': for (var j = 0; j < length; j += 6) { this.cubicCurveTo( getPoint(j), control = getPoint(j + 2), current = getPoint(j + 4)); } break; case 's': for (var j = 0; j < length; j += 4) { this.cubicCurveTo( /[cs]/.test(previous) ? current.multiply(2).subtract(control) : current, control = getPoint(j), current = getPoint(j + 2)); previous = lower; } break; case 'q': for (var j = 0; j < length; j += 4) { this.quadraticCurveTo( control = getPoint(j), current = getPoint(j + 2)); } break; case 't': for (var j = 0; j < length; j += 2) { this.quadraticCurveTo( control = (/[qt]/.test(previous) ? current.multiply(2).subtract(control) : current), current = getPoint(j)); previous = lower; } break; case 'a': for (var j = 0; j < length; j += 7) { this.arcTo(current = getPoint(j + 5), new Size(+coords[j], +coords[j + 1]), +coords[j + 2], +coords[j + 4], +coords[j + 3]); } break; case 'z': this.closePath(1e-12); current = start; break; } previous = lower; } }, _canComposite: function() { return !(this.hasFill() && this.hasStroke()); }, _contains: function(point) { var winding = point.isInside( this.getBounds({ internal: true, handle: true })) ? this._getWinding(point) : {}; return winding.onPath || !!(this.getFillRule() === 'evenodd' ? winding.windingL & 1 || winding.windingR & 1 : winding.winding); }, getIntersections: function(path, include, _matrix, _returnFirst) { var self = this === path || !path, matrix1 = this._matrix._orNullIfIdentity(), matrix2 = self ? matrix1 : (_matrix || path._matrix)._orNullIfIdentity(); return self || this.getBounds(matrix1).intersects( path.getBounds(matrix2), 1e-12) ? Curve.getIntersections( this.getCurves(), !self && path.getCurves(), include, matrix1, matrix2, _returnFirst) : []; }, getCrossings: function(path) { return this.getIntersections(path, function(inter) { return inter.isCrossing(); }); }, getNearestLocation: function() { var point = Point.read(arguments), curves = this.getCurves(), minDist = Infinity, minLoc = null; for (var i = 0, l = curves.length; i < l; i++) { var loc = curves[i].getNearestLocation(point); if (loc._distance < minDist) { minDist = loc._distance; minLoc = loc; } } return minLoc; }, getNearestPoint: function() { var loc = this.getNearestLocation.apply(this, arguments); return loc ? loc.getPoint() : loc; }, interpolate: function(from, to, factor) { var isPath = !this._children, name = isPath ? '_segments' : '_children', itemsFrom = from[name], itemsTo = to[name], items = this[name]; if (!itemsFrom || !itemsTo || itemsFrom.length !== itemsTo.length) { throw new Error('Invalid operands in interpolate() call: ' + from + ', ' + to); } var current = items.length, length = itemsTo.length; if (current < length) { var ctor = isPath ? Segment : Path; for (var i = current; i < length; i++) { this.add(new ctor()); } } else if (current > length) { this[isPath ? 'removeSegments' : 'removeChildren'](length, current); } for (var i = 0; i < length; i++) { items[i].interpolate(itemsFrom[i], itemsTo[i], factor); } if (isPath) { this.setClosed(from._closed); this._changed(9); } }, compare: function(path) { var ok = false; if (path) { var paths1 = this._children || [this], paths2 = path._children ? path._children.slice() : [path], length1 = paths1.length, length2 = paths2.length, matched = [], count = 0; ok = true; var boundsOverlaps = CollisionDetection.findItemBoundsCollisions(paths1, paths2, Numerical.GEOMETRIC_EPSILON); for (var i1 = length1 - 1; i1 >= 0 && ok; i1--) { var path1 = paths1[i1]; ok = false; var pathBoundsOverlaps = boundsOverlaps[i1]; if (pathBoundsOverlaps) { for (var i2 = pathBoundsOverlaps.length - 1; i2 >= 0 && !ok; i2--) { if (path1.compare(paths2[pathBoundsOverlaps[i2]])) { if (!matched[pathBoundsOverlaps[i2]]) { matched[pathBoundsOverlaps[i2]] = true; count++; } ok = true; } } } } ok = ok && count === length2; } return ok; }, }); var Path = PathItem.extend({ _class: 'Path', _serializeFields: { segments: [], closed: false }, initialize: function Path(arg) { this._closed = false; this._segments = []; this._version = 0; var args = arguments, segments = Array.isArray(arg) ? typeof arg[0] === 'object' ? arg : args : arg && (arg.size === undefined && (arg.x !== undefined || arg.point !== undefined)) ? args : null; if (segments && segments.length > 0) { this.setSegments(segments); } else { this._curves = undefined; this._segmentSelection = 0; if (!segments && typeof arg === 'string') { this.setPathData(arg); arg = null; } } this._initialize(!segments && arg); }, _equals: function(item) { return this._closed === item._closed && Base.equals(this._segments, item._segments); }, copyContent: function(source) { this.setSegments(source._segments); this._closed = source._closed; }, _changed: function _changed(flags) { _changed.base.call(this, flags); if (flags & 8) { this._length = this._area = undefined; if (flags & 32) { this._version++; } else if (this._curves) { for (var i = 0, l = this._curves.length; i < l; i++) this._curves[i]._changed(); } } else if (flags & 64) { this._bounds = undefined; } }, getStyle: function() { var parent = this._parent; return (parent instanceof CompoundPath ? parent : this)._style; }, getSegments: function() { return this._segments; }, setSegments: function(segments) { var fullySelected = this.isFullySelected(), length = segments && segments.length; this._segments.length = 0; this._segmentSelection = 0; this._curves = undefined; if (length) { var last = segments[length - 1]; if (typeof last === 'boolean') { this.setClosed(last); length--; } this._add(Segment.readList(segments, 0, {}, length)); } if (fullySelected) this.setFullySelected(true); }, getFirstSegment: function() { return this._segments[0]; }, getLastSegment: function() { return this._segments[this._segments.length - 1]; }, getCurves: function() { var curves = this._curves, segments = this._segments; if (!curves) { var length = this._countCurves(); curves = this._curves = new Array(length); for (var i = 0; i < length; i++) curves[i] = new Curve(this, segments[i], segments[i + 1] || segments[0]); } return curves; }, getFirstCurve: function() { return this.getCurves()[0]; }, getLastCurve: function() { var curves = this.getCurves(); return curves[curves.length - 1]; }, isClosed: function() { return this._closed; }, setClosed: function(closed) { if (this._closed != (closed = !!closed)) { this._closed = closed; if (this._curves) { var length = this._curves.length = this._countCurves(); if (closed) this._curves[length - 1] = new Curve(this, this._segments[length - 1], this._segments[0]); } this._changed(41); } } }, { beans: true, getPathData: function(_matrix, _precision) { var segments = this._segments, length = segments.length, f = new Formatter(_precision), coords = new Array(6), first = true, curX, curY, prevX, prevY, inX, inY, outX, outY, parts = []; function addSegment(segment, skipLine) { segment._transformCoordinates(_matrix, coords); curX = coords[0]; curY = coords[1]; if (first) { parts.push('M' + f.pair(curX, curY)); first = false; } else { inX = coords[2]; inY = coords[3]; if (inX === curX && inY === curY && outX === prevX && outY === prevY) { if (!skipLine) { var dx = curX - prevX, dy = curY - prevY; parts.push( dx === 0 ? 'v' + f.number(dy) : dy === 0 ? 'h' + f.number(dx) : 'l' + f.pair(dx, dy)); } } else { parts.push('c' + f.pair(outX - prevX, outY - prevY) + ' ' + f.pair( inX - prevX, inY - prevY) + ' ' + f.pair(curX - prevX, curY - prevY)); } } prevX = curX; prevY = curY; outX = coords[4]; outY = coords[5]; } if (!length) return ''; for (var i = 0; i < length; i++) addSegment(segments[i]); if (this._closed && length > 0) { addSegment(segments[0], true); parts.push('z'); } return parts.join(''); }, isEmpty: function() { return !this._segments.length; }, _transformContent: function(matrix) { var segments = this._segments, coords = new Array(6); for (var i = 0, l = segments.length; i < l; i++) segments[i]._transformCoordinates(matrix, coords, true); return true; }, _add: function(segs, index) { var segments = this._segments, curves = this._curves, amount = segs.length, append = index == null, index = append ? segments.length : index; for (var i = 0; i < amount; i++) { var segment = segs[i]; if (segment._path) segment = segs[i] = segment.clone(); segment._path = this; segment._index = index + i; if (segment._selection) this._updateSelection(segment, 0, segment._selection); } if (append) { Base.push(segments, segs); } else { segments.splice.apply(segments, [index, 0].concat(segs)); for (var i = index + amount, l = segments.length; i < l; i++) segments[i]._index = i; } if (curves) { var total = this._countCurves(), start = index > 0 && index + amount - 1 === total ? index - 1 : index, insert = start, end = Math.min(start + amount, total); if (segs._curves) { curves.splice.apply(curves, [start, 0].concat(segs._curves)); insert += segs._curves.length; } for (var i = insert; i < end; i++) curves.splice(i, 0, new Curve(this, null, null)); this._adjustCurves(start, end); } this._changed(41); return segs; }, _adjustCurves: function(start, end) { var segments = this._segments, curves = this._curves, curve; for (var i = start; i < end; i++) { curve = curves[i]; curve._path = this; curve._segment1 = segments[i]; curve._segment2 = segments[i + 1] || segments[0]; curve._changed(); } if (curve = curves[this._closed && !start ? segments.length - 1 : start - 1]) { curve._segment2 = segments[start] || segments[0]; curve._changed(); } if (curve = curves[end]) { curve._segment1 = segments[end]; curve._changed(); } }, _countCurves: function() { var length = this._segments.length; return !this._closed && length > 0 ? length - 1 : length; }, add: function(segment1 ) { var args = arguments; return args.length > 1 && typeof segment1 !== 'number' ? this._add(Segment.readList(args)) : this._add([ Segment.read(args) ])[0]; }, insert: function(index, segment1 ) { var args = arguments; return args.length > 2 && typeof segment1 !== 'number' ? this._add(Segment.readList(args, 1), index) : this._add([ Segment.read(args, 1) ], index)[0]; }, addSegment: function() { return this._add([ Segment.read(arguments) ])[0]; }, insertSegment: function(index ) { return this._add([ Segment.read(arguments, 1) ], index)[0]; }, addSegments: function(segments) { return this._add(Segment.readList(segments)); }, insertSegments: function(index, segments) { return this._add(Segment.readList(segments), index); }, removeSegment: function(index) { return this.removeSegments(index, index + 1)[0] || null; }, removeSegments: function(start, end, _includeCurves) { start = start || 0; end = Base.pick(end, this._segments.length); var segments = this._segments, curves = this._curves, count = segments.length, removed = segments.splice(start, end - start), amount = removed.length; if (!amount) return removed; for (var i = 0; i < amount; i++) { var segment = removed[i]; if (segment._selection) this._updateSelection(segment, segment._selection, 0); segment._index = segment._path = null; } for (var i = start, l = segments.length; i < l; i++) segments[i]._index = i; if (curves) { var index = start > 0 && end === count + (this._closed ? 1 : 0) ? start - 1 : start, curves = curves.splice(index, amount); for (var i = curves.length - 1; i >= 0; i--) curves[i]._path = null; if (_includeCurves) removed._curves = curves.slice(1); this._adjustCurves(index, index); } this._changed(41); return removed; }, clear: '#removeSegments', hasHandles: function() { var segments = this._segments; for (var i = 0, l = segments.length; i < l; i++) { if (segments[i].hasHandles()) return true; } return false; }, clearHandles: function() { var segments = this._segments; for (var i = 0, l = segments.length; i < l; i++) segments[i].clearHandles(); }, getLength: function() { if (this._length == null) { var curves = this.getCurves(), length = 0; for (var i = 0, l = curves.length; i < l; i++) length += curves[i].getLength(); this._length = length; } return this._length; }, getArea: function() { var area = this._area; if (area == null) { var segments = this._segments, closed = this._closed; area = 0; for (var i = 0, l = segments.length; i < l; i++) { var last = i + 1 === l; area += Curve.getArea(Curve.getValues( segments[i], segments[last ? 0 : i + 1], null, last && !closed)); } this._area = area; } return area; }, isFullySelected: function() { var length = this._segments.length; return this.isSelected() && length > 0 && this._segmentSelection === length * 7; }, setFullySelected: function(selected) { if (selected) this._selectSegments(true); this.setSelected(selected); }, setSelection: function setSelection(selection) { if (!(selection & 1)) this._selectSegments(false); setSelection.base.call(this, selection); }, _selectSegments: function(selected) { var segments = this._segments, length = segments.length, selection = selected ? 7 : 0; this._segmentSelection = selection * length; for (var i = 0; i < length; i++) segments[i]._selection = selection; }, _updateSelection: function(segment, oldSelection, newSelection) { segment._selection = newSelection; var selection = this._segmentSelection += newSelection - oldSelection; if (selection > 0) this.setSelected(true); }, divideAt: function(location) { var loc = this.getLocationAt(location), curve; return loc && (curve = loc.getCurve().divideAt(loc.getCurveOffset())) ? curve._segment1 : null; }, splitAt: function(location) { var loc = this.getLocationAt(location), index = loc && loc.index, time = loc && loc.time, tMin = 1e-8, tMax = 1 - tMin; if (time > tMax) { index++; time = 0; } var curves = this.getCurves(); if (index >= 0 && index < curves.length) { if (time >= tMin) { curves[index++].divideAtTime(time); } var segs = this.removeSegments(index, this._segments.length, true), path; if (this._closed) { this.setClosed(false); path = this; } else { path = new Path(Item.NO_INSERT); path.insertAbove(this); path.copyAttributes(this); } path._add(segs, 0); this.addSegment(segs[0]); return path; } return null; }, split: function(index, time) { var curve, location = time === undefined ? index : (curve = this.getCurves()[index]) && curve.getLocationAtTime(time); return location != null ? this.splitAt(location) : null; }, join: function(path, tolerance) { var epsilon = tolerance || 0; if (path && path !== this) { var segments = path._segments, last1 = this.getLastSegment(), last2 = path.getLastSegment(); if (!last2) return this; if (last1 && last1._point.isClose(last2._point, epsilon)) path.reverse(); var first2 = path.getFirstSegment(); if (last1 && last1._point.isClose(first2._point, epsilon)) { last1.setHandleOut(first2._handleOut); this._add(segments.slice(1)); } else { var first1 = this.getFirstSegment(); if (first1 && first1._point.isClose(first2._point, epsilon)) path.reverse(); last2 = path.getLastSegment(); if (first1 && first1._point.isClose(last2._point, epsilon)) { first1.setHandleIn(last2._handleIn); this._add(segments.slice(0, segments.length - 1), 0); } else { this._add(segments.slice()); } } if (path._closed) this._add([segments[0]]); path.remove(); } var first = this.getFirstSegment(), last = this.getLastSegment(); if (first !== last && first._point.isClose(last._point, epsilon)) { first.setHandleIn(last._handleIn); last.remove(); this.setClosed(true); } return this; }, reduce: function(options) { var curves = this.getCurves(), simplify = options && options.simplify, tolerance = simplify ? 1e-7 : 0; for (var i = curves.length - 1; i >= 0; i--) { var curve = curves[i]; if (!curve.hasHandles() && (!curve.hasLength(tolerance) || simplify && curve.isCollinear(curve.getNext()))) curve.remove(); } return this; }, reverse: function() { this._segments.reverse(); for (var i = 0, l = this._segments.length; i < l; i++) { var segment = this._segments[i]; var handleIn = segment._handleIn; segment._handleIn = segment._handleOut; segment._handleOut = handleIn; segment._index = i; } this._curves = null; this._changed(9); }, flatten: function(flatness) { var flattener = new PathFlattener(this, flatness || 0.25, 256, true), parts = flattener.parts, length = parts.length, segments = []; for (var i = 0; i < length; i++) { segments.push(new Segment(parts[i].curve.slice(0, 2))); } if (!this._closed && length > 0) { segments.push(new Segment(parts[length - 1].curve.slice(6))); } this.setSegments(segments); }, simplify: function(tolerance) { var segments = new PathFitter(this).fit(tolerance || 2.5); if (segments) this.setSegments(segments); return !!segments; }, smooth: function(options) { var that = this, opts = options || {}, type = opts.type || 'asymmetric', segments = this._segments, length = segments.length, closed = this._closed; function getIndex(value, _default) { var index = value && value.index; if (index != null) { var path = value.path; if (path && path !== that) throw new Error(value._class + ' ' + index + ' of ' + path + ' is not part of ' + that); if (_default && value instanceof Curve) index++; } else { index = typeof value === 'number' ? value : _default; } return Math.min(index < 0 && closed ? index % length : index < 0 ? index + length : index, length - 1); } var loop = closed && opts.from === undefined && opts.to === undefined, from = getIndex(opts.from, 0), to = getIndex(opts.to, length - 1); if (from > to) { if (closed) { from -= length; } else { var tmp = from; from = to; to = tmp; } } if (/^(?:asymmetric|continuous)$/.test(type)) { var asymmetric = type === 'asymmetric', min = Math.min, amount = to - from + 1, n = amount - 1, padding = loop ? min(amount, 4) : 1, paddingLeft = padding, paddingRight = padding, knots = []; if (!closed) { paddingLeft = min(1, from); paddingRight = min(1, length - to - 1); } n += paddingLeft + paddingRight; if (n <= 1) return; for (var i = 0, j = from - paddingLeft; i <= n; i++, j++) { knots[i] = segments[(j < 0 ? j + length : j) % length]._point; } var x = knots[0]._x + 2 * knots[1]._x, y = knots[0]._y + 2 * knots[1]._y, f = 2, n_1 = n - 1, rx = [x], ry = [y], rf = [f], px = [], py = []; for (var i = 1; i < n; i++) { var internal = i < n_1, a = internal ? 1 : asymmetric ? 1 : 2, b = internal ? 4 : asymmetric ? 2 : 7, u = internal ? 4 : asymmetric ? 3 : 8, v = internal ? 2 : asymmetric ? 0 : 1, m = a / f; f = rf[i] = b - m; x = rx[i] = u * knots[i]._x + v * knots[i + 1]._x - m * x; y = ry[i] = u * knots[i]._y + v * knots[i + 1]._y - m * y; } px[n_1] = rx[n_1] / rf[n_1]; py[n_1] = ry[n_1] / rf[n_1]; for (var i = n - 2; i >= 0; i--) { px[i] = (rx[i] - px[i + 1]) / rf[i]; py[i] = (ry[i] - py[i + 1]) / rf[i]; } px[n] = (3 * knots[n]._x - px[n_1]) / 2; py[n] = (3 * knots[n]._y - py[n_1]) / 2; for (var i = paddingLeft, max = n - paddingRight, j = from; i <= max; i++, j++) { var segment = segments[j < 0 ? j + length : j], pt = segment._point, hx = px[i] - pt._x, hy = py[i] - pt._y; if (loop || i < max) segment.setHandleOut(hx, hy); if (loop || i > paddingLeft) segment.setHandleIn(-hx, -hy); } } else { for (var i = from; i <= to; i++) { segments[i < 0 ? i + length : i].smooth(opts, !loop && i === from, !loop && i === to); } } }, toShape: function(insert) { if (!this._closed) return null; var segments = this._segments, type, size, radius, topCenter; function isCollinear(i, j) { var seg1 = segments[i], seg2 = seg1.getNext(), seg3 = segments[j], seg4 = seg3.getNext(); return seg1._handleOut.isZero() && seg2._handleIn.isZero() && seg3._handleOut.isZero() && seg4._handleIn.isZero() && seg2._point.subtract(seg1._point).isCollinear( seg4._point.subtract(seg3._point)); } function isOrthogonal(i) { var seg2 = segments[i], seg1 = seg2.getPrevious(), seg3 = seg2.getNext(); return seg1._handleOut.isZero() && seg2._handleIn.isZero() && seg2._handleOut.isZero() && seg3._handleIn.isZero() && seg2._point.subtract(seg1._point).isOrthogonal( seg3._point.subtract(seg2._point)); } function isArc(i) { var seg1 = segments[i], seg2 = seg1.getNext(), handle1 = seg1._handleOut, handle2 = seg2._handleIn, kappa = 0.5522847498307936; if (handle1.isOrthogonal(handle2)) { var pt1 = seg1._point, pt2 = seg2._point, corner = new Line(pt1, handle1, true).intersect( new Line(pt2, handle2, true), true); return corner && Numerical.isZero(handle1.getLength() / corner.subtract(pt1).getLength() - kappa) && Numerical.isZero(handle2.getLength() / corner.subtract(pt2).getLength() - kappa); } return false; } function getDistance(i, j) { return segments[i]._point.getDistance(segments[j]._point); } if (!this.hasHandles() && segments.length === 4 && isCollinear(0, 2) && isCollinear(1, 3) && isOrthogonal(1)) { type = Shape.Rectangle; size = new Size(getDistance(0, 3), getDistance(0, 1)); topCenter = segments[1]._point.add(segments[2]._point).divide(2); } else if (segments.length === 8 && isArc(0) && isArc(2) && isArc(4) && isArc(6) && isCollinear(1, 5) && isCollinear(3, 7)) { type = Shape.Rectangle; size = new Size(getDistance(1, 6), getDistance(0, 3)); radius = size.subtract(new Size(getDistance(0, 7), getDistance(1, 2))).divide(2); topCenter = segments[3]._point.add(segments[4]._point).divide(2); } else if (segments.length === 4 && isArc(0) && isArc(1) && isArc(2) && isArc(3)) { if (Numerical.isZero(getDistance(0, 2) - getDistance(1, 3))) { type = Shape.Circle; radius = getDistance(0, 2) / 2; } else { type = Shape.Ellipse; radius = new Size(getDistance(2, 0) / 2, getDistance(3, 1) / 2); } topCenter = segments[1]._point; } if (type) { var center = this.getPosition(true), shape = new type({ center: center, size: size, radius: radius, insert: false }); shape.copyAttributes(this, true); shape._matrix.prepend(this._matrix); shape.rotate(topCenter.subtract(center).getAngle() + 90); if (insert === undefined || insert) shape.insertAbove(this); return shape; } return null; }, toPath: '#clone', compare: function compare(path) { if (!path || path instanceof CompoundPath) return compare.base.call(this, path); var curves1 = this.getCurves(), curves2 = path.getCurves(), length1 = curves1.length, length2 = curves2.length; if (!length1 || !length2) { return length1 == length2; } var v1 = curves1[0].getValues(), values2 = [], pos1 = 0, pos2, end1 = 0, end2; for (var i = 0; i < length2; i++) { var v2 = curves2[i].getValues(); values2.push(v2); var overlaps = Curve.getOverlaps(v1, v2); if (overlaps) { pos2 = !i && overlaps[0][0] > 0 ? length2 - 1 : i; end2 = overlaps[0][1]; break; } } var abs = Math.abs, epsilon = 1e-8, v2 = values2[pos2], start2; while (v1 && v2) { var overlaps = Curve.getOverlaps(v1, v2); if (overlaps) { var t1 = overlaps[0][0]; if (abs(t1 - end1) < epsilon) { end1 = overlaps[1][0]; if (end1 === 1) { v1 = ++pos1 < length1 ? curves1[pos1].getValues() : null; end1 = 0; } var t2 = overlaps[0][1]; if (abs(t2 - end2) < epsilon) { if (!start2) start2 = [pos2, t2]; end2 = overlaps[1][1]; if (end2 === 1) { if (++pos2 >= length2) pos2 = 0; v2 = values2[pos2] || curves2[pos2].getValues(); end2 = 0; } if (!v1) { return start2[0] === pos2 && start2[1] === end2; } continue; } } } break; } return false; }, _hitTestSelf: function(point, options, viewMatrix, strokeMatrix) { var that = this, style = this.getStyle(), segments = this._segments, numSegments = segments.length, closed = this._closed, tolerancePadding = options._tolerancePadding, strokePadding = tolerancePadding, join, cap, miterLimit, area, loc, res, hitStroke = options.stroke && style.hasStroke(), hitFill = options.fill && style.hasFill(), hitCurves = options.curves, strokeRadius = hitStroke ? style.getStrokeWidth() / 2 : hitFill && options.tolerance > 0 || hitCurves ? 0 : null; if (strokeRadius !== null) { if (strokeRadius > 0) { join = style.getStrokeJoin(); cap = style.getStrokeCap(); miterLimit = style.getMiterLimit(); strokePadding = strokePadding.add( Path._getStrokePadding(strokeRadius, strokeMatrix)); } else { join = cap = 'round'; } } function isCloseEnough(pt, padding) { return point.subtract(pt).divide(padding).length <= 1; } function checkSegmentPoint(seg, pt, name) { if (!options.selected || pt.isSelected()) { var anchor = seg._point; if (pt !== anchor) pt = pt.add(anchor); if (isCloseEnough(pt, strokePadding)) { return new HitResult(name, that, { segment: seg, point: pt }); } } } function checkSegmentPoints(seg, ends) { return (ends || options.segments) && checkSegmentPoint(seg, seg._point, 'segment') || (!ends && options.handles) && ( checkSegmentPoint(seg, seg._handleIn, 'handle-in') || checkSegmentPoint(seg, seg._handleOut, 'handle-out')); } function addToArea(point) { area.add(point); } function checkSegmentStroke(segment) { var isJoin = closed || segment._index > 0 && segment._index < numSegments - 1; if ((isJoin ? join : cap) === 'round') { return isCloseEnough(segment._point, strokePadding); } else { area = new Path({ internal: true, closed: true }); if (isJoin) { if (!segment.isSmooth()) { Path._addBevelJoin(segment, join, strokeRadius, miterLimit, null, strokeMatrix, addToArea, true); } } else if (cap === 'square') { Path._addSquareCap(segment, cap, strokeRadius, null, strokeMatrix, addToArea, true); } if (!area.isEmpty()) { var loc; return area.contains(point) || (loc = area.getNearestLocation(point)) && isCloseEnough(loc.getPoint(), tolerancePadding); } } } if (options.ends && !options.segments && !closed) { if (res = checkSegmentPoints(segments[0], true) || checkSegmentPoints(segments[numSegments - 1], true)) return res; } else if (options.segments || options.handles) { for (var i = 0; i < numSegments; i++) if (res = checkSegmentPoints(segments[i])) return res; } if (strokeRadius !== null) { loc = this.getNearestLocation(point); if (loc) { var time = loc.getTime(); if (time === 0 || time === 1 && numSegments > 1) { if (!checkSegmentStroke(loc.getSegment())) loc = null; } else if (!isCloseEnough(loc.getPoint(), strokePadding)) { loc = null; } } if (!loc && join === 'miter' && numSegments > 1) { for (var i = 0; i < numSegments; i++) { var segment = segments[i]; if (point.getDistance(segment._point) <= miterLimit * strokeRadius && checkSegmentStroke(segment)) { loc = segment.getLocation(); break; } } } } return !loc && hitFill && this._contains(point) || loc && !hitStroke && !hitCurves ? new HitResult('fill', this) : loc ? new HitResult(hitStroke ? 'stroke' : 'curve', this, { location: loc, point: loc.getPoint() }) : null; } }, Base.each(Curve._evaluateMethods, function(name) { this[name + 'At'] = function(offset) { var loc = this.getLocationAt(offset); return loc && loc[name](); }; }, { beans: false, getLocationOf: function() { var point = Point.read(arguments), curves = this.getCurves(); for (var i = 0, l = curves.length; i < l; i++) { var loc = curves[i].getLocationOf(point); if (loc) return loc; } return null; }, getOffsetOf: function() { var loc = this.getLocationOf.apply(this, arguments); return loc ? loc.getOffset() : null; }, getLocationAt: function(offset) { if (typeof offset === 'number') { var curves = this.getCurves(), length = 0; for (var i = 0, l = curves.length; i < l; i++) { var start = length, curve = curves[i]; length += curve.getLength(); if (length > offset) { return curve.getLocationAt(offset - start); } } if (curves.length > 0 && offset <= this.getLength()) { return new CurveLocation(curves[curves.length - 1], 1); } } else if (offset && offset.getPath && offset.getPath() === this) { return offset; } return null; }, getOffsetsWithTangent: function() { var tangent = Point.read(arguments); if (tangent.isZero()) { return []; } var offsets = []; var curveStart = 0; var curves = this.getCurves(); for (var i = 0, l = curves.length; i < l; i++) { var curve = curves[i]; var curveTimes = curve.getTimesWithTangent(tangent); for (var j = 0, m = curveTimes.length; j < m; j++) { var offset = curveStart + curve.getOffsetAtTime(curveTimes[j]); if (offsets.indexOf(offset) < 0) { offsets.push(offset); } } curveStart += curve.length; } return offsets; } }), new function() { function drawHandles(ctx, segments, matrix, size) { if (size <= 0) return; var half = size / 2, miniSize = size - 2, miniHalf = half - 1, coords = new Array(6), pX, pY; function drawHandle(index) { var hX = coords[index], hY = coords[index + 1]; if (pX != hX || pY != hY) { ctx.beginPath(); ctx.moveTo(pX, pY); ctx.lineTo(hX, hY); ctx.stroke(); ctx.beginPath(); ctx.arc(hX, hY, half, 0, Math.PI * 2, true); ctx.fill(); } } for (var i = 0, l = segments.length; i < l; i++) { var segment = segments[i], selection = segment._selection; segment._transformCoordinates(matrix, coords); pX = coords[0]; pY = coords[1]; if (selection & 2) drawHandle(2); if (selection & 4) drawHandle(4); ctx.fillRect(pX - half, pY - half, size, size); if (miniSize > 0 && !(selection & 1)) { var fillStyle = ctx.fillStyle; ctx.fillStyle = '#ffffff'; ctx.fillRect(pX - miniHalf, pY - miniHalf, miniSize, miniSize); ctx.fillStyle = fillStyle; } } } function drawSegments(ctx, path, matrix) { var segments = path._segments, length = segments.length, coords = new Array(6), first = true, curX, curY, prevX, prevY, inX, inY, outX, outY; function drawSegment(segment) { if (matrix) { segment._transformCoordinates(matrix, coords); curX = coords[0]; curY = coords[1]; } else { var point = segment._point; curX = point._x; curY = point._y; } if (first) { ctx.moveTo(curX, curY); first = false; } else { if (matrix) { inX = coords[2]; inY = coords[3]; } else { var handle = segment._handleIn; inX = curX + handle._x; inY = curY + handle._y; } if (inX === curX && inY === curY && outX === prevX && outY === prevY) { ctx.lineTo(curX, curY); } else { ctx.bezierCurveTo(outX, outY, inX, inY, curX, curY); } } prevX = curX; prevY = curY; if (matrix) { outX = coords[4]; outY = coords[5]; } else { var handle = segment._handleOut; outX = prevX + handle._x; outY = prevY + handle._y; } } for (var i = 0; i < length; i++) drawSegment(segments[i]); if (path._closed && length > 0) drawSegment(segments[0]); } return { _draw: function(ctx, param, viewMatrix, strokeMatrix) { var dontStart = param.dontStart, dontPaint = param.dontFinish || param.clip, style = this.getStyle(), hasFill = style.hasFill(), hasStroke = style.hasStroke(), dashArray = style.getDashArray(), dashLength = !paper.support.nativeDash && hasStroke && dashArray && dashArray.length; if (!dontStart) ctx.beginPath(); if (hasFill || hasStroke && !dashLength || dontPaint) { drawSegments(ctx, this, strokeMatrix); if (this._closed) ctx.closePath(); } function getOffset(i) { return dashArray[((i % dashLength) + dashLength) % dashLength]; } if (!dontPaint && (hasFill || hasStroke)) { this._setStyles(ctx, param, viewMatrix); if (hasFill) { ctx.fill(style.getFillRule()); ctx.shadowColor = 'rgba(0,0,0,0)'; } if (hasStroke) { if (dashLength) { if (!dontStart) ctx.beginPath(); var flattener = new PathFlattener(this, 0.25, 32, false, strokeMatrix), length = flattener.length, from = -style.getDashOffset(), to, i = 0; while (from > 0) { from -= getOffset(i--) + getOffset(i--); } while (from < length) { to = from + getOffset(i++); if (from > 0 || to > 0) flattener.drawPart(ctx, Math.max(from, 0), Math.max(to, 0)); from = to + getOffset(i++); } } ctx.stroke(); } } }, _drawSelected: function(ctx, matrix) { ctx.beginPath(); drawSegments(ctx, this, matrix); ctx.stroke(); drawHandles(ctx, this._segments, matrix, paper.settings.handleSize); } }; }, new function() { function getCurrentSegment(that) { var segments = that._segments; if (!segments.length) throw new Error('Use a moveTo() command first'); return segments[segments.length - 1]; } return { moveTo: function() { var segments = this._segments; if (segments.length === 1) this.removeSegment(0); if (!segments.length) this._add([ new Segment(Point.read(arguments)) ]); }, moveBy: function() { throw new Error('moveBy() is unsupported on Path items.'); }, lineTo: function() { this._add([ new Segment(Point.read(arguments)) ]); }, cubicCurveTo: function() { var args = arguments, handle1 = Point.read(args), handle2 = Point.read(args), to = Point.read(args), current = getCurrentSegment(this); current.setHandleOut(handle1.subtract(current._point)); this._add([ new Segment(to, handle2.subtract(to)) ]); }, quadraticCurveTo: function() { var args = arguments, handle = Point.read(args), to = Point.read(args), current = getCurrentSegment(this)._point; this.cubicCurveTo( handle.add(current.subtract(handle).multiply(1 / 3)), handle.add(to.subtract(handle).multiply(1 / 3)), to ); }, curveTo: function() { var args = arguments, through = Point.read(args), to = Point.read(args), t = Base.pick(Base.read(args), 0.5), t1 = 1 - t, current = getCurrentSegment(this)._point, handle = through.subtract(current.multiply(t1 * t1)) .subtract(to.multiply(t * t)).divide(2 * t * t1); if (handle.isNaN()) throw new Error( 'Cannot put a curve through points with parameter = ' + t); this.quadraticCurveTo(handle, to); }, arcTo: function() { var args = arguments, abs = Math.abs, sqrt = Math.sqrt, current = getCurrentSegment(this), from = current._point, to = Point.read(args), through, peek = Base.peek(args), clockwise = Base.pick(peek, true), center, extent, vector, matrix; if (typeof clockwise === 'boolean') { var middle = from.add(to).divide(2), through = middle.add(middle.subtract(from).rotate( clockwise ? -90 : 90)); } else if (Base.remain(args) <= 2) { through = to; to = Point.read(args); } else if (!from.equals(to)) { var radius = Size.read(args), isZero = Numerical.isZero; if (isZero(radius.width) || isZero(radius.height)) return this.lineTo(to); var rotation = Base.read(args), clockwise = !!Base.read(args), large = !!Base.read(args), middle = from.add(to).divide(2), pt = from.subtract(middle).rotate(-rotation), x = pt.x, y = pt.y, rx = abs(radius.width), ry = abs(radius.height), rxSq = rx * rx, rySq = ry * ry, xSq = x * x, ySq = y * y; var factor = sqrt(xSq / rxSq + ySq / rySq); if (factor > 1) { rx *= factor; ry *= factor; rxSq = rx * rx; rySq = ry * ry; } factor = (rxSq * rySq - rxSq * ySq - rySq * xSq) / (rxSq * ySq + rySq * xSq); if (abs(factor) < 1e-12) factor = 0; if (factor < 0) throw new Error( 'Cannot create an arc with the given arguments'); center = new Point(rx * y / ry, -ry * x / rx) .multiply((large === clockwise ? -1 : 1) * sqrt(factor)) .rotate(rotation).add(middle); matrix = new Matrix().translate(center).rotate(rotation) .scale(rx, ry); vector = matrix._inverseTransform(from); extent = vector.getDirectedAngle(matrix._inverseTransform(to)); if (!clockwise && extent > 0) extent -= 360; else if (clockwise && extent < 0) extent += 360; } if (through) { var l1 = new Line(from.add(through).divide(2), through.subtract(from).rotate(90), true), l2 = new Line(through.add(to).divide(2), to.subtract(through).rotate(90), true), line = new Line(from, to), throughSide = line.getSide(through); center = l1.intersect(l2, true); if (!center) { if (!throughSide) return this.lineTo(to); throw new Error( 'Cannot create an arc with the given arguments'); } vector = from.subtract(center); extent = vector.getDirectedAngle(to.subtract(center)); var centerSide = line.getSide(center, true); if (centerSide === 0) { extent = throughSide * abs(extent); } else if (throughSide === centerSide) { extent += extent < 0 ? 360 : -360; } } if (extent) { var epsilon = 1e-7, ext = abs(extent), count = ext >= 360 ? 4 : Math.ceil((ext - epsilon) / 90), inc = extent / count, half = inc * Math.PI / 360, z = 4 / 3 * Math.sin(half) / (1 + Math.cos(half)), segments = []; for (var i = 0; i <= count; i++) { var pt = to, out = null; if (i < count) { out = vector.rotate(90).multiply(z); if (matrix) { pt = matrix._transformPoint(vector); out = matrix._transformPoint(vector.add(out)) .subtract(pt); } else { pt = center.add(vector); } } if (!i) { current.setHandleOut(out); } else { var _in = vector.rotate(-90).multiply(z); if (matrix) { _in = matrix._transformPoint(vector.add(_in)) .subtract(pt); } segments.push(new Segment(pt, _in, out)); } vector = vector.rotate(inc); } this._add(segments); } }, lineBy: function() { var to = Point.read(arguments), current = getCurrentSegment(this)._point; this.lineTo(current.add(to)); }, curveBy: function() { var args = arguments, through = Point.read(args), to = Point.read(args), parameter = Base.read(args), current = getCurrentSegment(this)._point; this.curveTo(current.add(through), current.add(to), parameter); }, cubicCurveBy: function() { var args = arguments, handle1 = Point.read(args), handle2 = Point.read(args), to = Point.read(args), current = getCurrentSegment(this)._point; this.cubicCurveTo(current.add(handle1), current.add(handle2), current.add(to)); }, quadraticCurveBy: function() { var args = arguments, handle = Point.read(args), to = Point.read(args), current = getCurrentSegment(this)._point; this.quadraticCurveTo(current.add(handle), current.add(to)); }, arcBy: function() { var args = arguments, current = getCurrentSegment(this)._point, point = current.add(Point.read(args)), clockwise = Base.pick(Base.peek(args), true); if (typeof clockwise === 'boolean') { this.arcTo(point, clockwise); } else { this.arcTo(point, current.add(Point.read(args))); } }, closePath: function(tolerance) { this.setClosed(true); this.join(this, tolerance); } }; }, { _getBounds: function(matrix, options) { var method = options.handle ? 'getHandleBounds' : options.stroke ? 'getStrokeBounds' : 'getBounds'; return Path[method](this._segments, this._closed, this, matrix, options); }, statics: { getBounds: function(segments, closed, path, matrix, options, strokePadding) { var first = segments[0]; if (!first) return new Rectangle(); var coords = new Array(6), prevCoords = first._transformCoordinates(matrix, new Array(6)), min = prevCoords.slice(0, 2), max = min.slice(), roots = new Array(2); function processSegment(segment) { segment._transformCoordinates(matrix, coords); for (var i = 0; i < 2; i++) { Curve._addBounds( prevCoords[i], prevCoords[i + 4], coords[i + 2], coords[i], i, strokePadding ? strokePadding[i] : 0, min, max, roots); } var tmp = prevCoords; prevCoords = coords; coords = tmp; } for (var i = 1, l = segments.length; i < l; i++) processSegment(segments[i]); if (closed) processSegment(first); return new Rectangle(min[0], min[1], max[0] - min[0], max[1] - min[1]); }, getStrokeBounds: function(segments, closed, path, matrix, options) { var style = path.getStyle(), stroke = style.hasStroke(), strokeWidth = style.getStrokeWidth(), strokeMatrix = stroke && path._getStrokeMatrix(matrix, options), strokePadding = stroke && Path._getStrokePadding(strokeWidth, strokeMatrix), bounds = Path.getBounds(segments, closed, path, matrix, options, strokePadding); if (!stroke) return bounds; var strokeRadius = strokeWidth / 2, join = style.getStrokeJoin(), cap = style.getStrokeCap(), miterLimit = style.getMiterLimit(), joinBounds = new Rectangle(new Size(strokePadding)); function addPoint(point) { bounds = bounds.include(point); } function addRound(segment) { bounds = bounds.unite( joinBounds.setCenter(segment._point.transform(matrix))); } function addJoin(segment, join) { if (join === 'round' || segment.isSmooth()) { addRound(segment); } else { Path._addBevelJoin(segment, join, strokeRadius, miterLimit, matrix, strokeMatrix, addPoint); } } function addCap(segment, cap) { if (cap === 'round') { addRound(segment); } else { Path._addSquareCap(segment, cap, strokeRadius, matrix, strokeMatrix, addPoint); } } var length = segments.length - (closed ? 0 : 1); if (length > 0) { for (var i = 1; i < length; i++) { addJoin(segments[i], join); } if (closed) { addJoin(segments[0], join); } else { addCap(segments[0], cap); addCap(segments[segments.length - 1], cap); } } return bounds; }, _getStrokePadding: function(radius, matrix) { if (!matrix) return [radius, radius]; var hor = new Point(radius, 0).transform(matrix), ver = new Point(0, radius).transform(matrix), phi = hor.getAngleInRadians(), a = hor.getLength(), b = ver.getLength(); var sin = Math.sin(phi), cos = Math.cos(phi), tan = Math.tan(phi), tx = Math.atan2(b * tan, a), ty = Math.atan2(b, tan * a); return [Math.abs(a * Math.cos(tx) * cos + b * Math.sin(tx) * sin), Math.abs(b * Math.sin(ty) * cos + a * Math.cos(ty) * sin)]; }, _addBevelJoin: function(segment, join, radius, miterLimit, matrix, strokeMatrix, addPoint, isArea) { var curve2 = segment.getCurve(), curve1 = curve2.getPrevious(), point = curve2.getPoint1().transform(matrix), normal1 = curve1.getNormalAtTime(1).multiply(radius) .transform(strokeMatrix), normal2 = curve2.getNormalAtTime(0).multiply(radius) .transform(strokeMatrix), angle = normal1.getDirectedAngle(normal2); if (angle < 0 || angle >= 180) { normal1 = normal1.negate(); normal2 = normal2.negate(); } if (isArea) addPoint(point); addPoint(point.add(normal1)); if (join === 'miter') { var corner = new Line(point.add(normal1), new Point(-normal1.y, normal1.x), true ).intersect(new Line(point.add(normal2), new Point(-normal2.y, normal2.x), true ), true); if (corner && point.getDistance(corner) <= miterLimit * radius) { addPoint(corner); } } addPoint(point.add(normal2)); }, _addSquareCap: function(segment, cap, radius, matrix, strokeMatrix, addPoint, isArea) { var point = segment._point.transform(matrix), loc = segment.getLocation(), normal = loc.getNormal() .multiply(loc.getTime() === 0 ? radius : -radius) .transform(strokeMatrix); if (cap === 'square') { if (isArea) { addPoint(point.subtract(normal)); addPoint(point.add(normal)); } point = point.add(normal.rotate(-90)); } addPoint(point.add(normal)); addPoint(point.subtract(normal)); }, getHandleBounds: function(segments, closed, path, matrix, options) { var style = path.getStyle(), stroke = options.stroke && style.hasStroke(), strokePadding, joinPadding; if (stroke) { var strokeMatrix = path._getStrokeMatrix(matrix, options), strokeRadius = style.getStrokeWidth() / 2, joinRadius = strokeRadius; if (style.getStrokeJoin() === 'miter') joinRadius = strokeRadius * style.getMiterLimit(); if (style.getStrokeCap() === 'square') joinRadius = Math.max(joinRadius, strokeRadius * Math.SQRT2); strokePadding = Path._getStrokePadding(strokeRadius, strokeMatrix); joinPadding = Path._getStrokePadding(joinRadius, strokeMatrix); } var coords = new Array(6), x1 = Infinity, x2 = -x1, y1 = x1, y2 = x2; for (var i = 0, l = segments.length; i < l; i++) { var segment = segments[i]; segment._transformCoordinates(matrix, coords); for (var j = 0; j < 6; j += 2) { var padding = !j ? joinPadding : strokePadding, paddingX = padding ? padding[0] : 0, paddingY = padding ? padding[1] : 0, x = coords[j], y = coords[j + 1], xn = x - paddingX, xx = x + paddingX, yn = y - paddingY, yx = y + paddingY; if (xn < x1) x1 = xn; if (xx > x2) x2 = xx; if (yn < y1) y1 = yn; if (yx > y2) y2 = yx; } } return new Rectangle(x1, y1, x2 - x1, y2 - y1); } }}); Path.inject({ statics: new function() { var kappa = 0.5522847498307936, ellipseSegments = [ new Segment([-1, 0], [0, kappa ], [0, -kappa]), new Segment([0, -1], [-kappa, 0], [kappa, 0 ]), new Segment([1, 0], [0, -kappa], [0, kappa ]), new Segment([0, 1], [kappa, 0 ], [-kappa, 0]) ]; function createPath(segments, closed, args) { var props = Base.getNamed(args), path = new Path(props && props.insert == false && Item.NO_INSERT); path._add(segments); path._closed = closed; return path.set(props, { insert: true }); } function createEllipse(center, radius, args) { var segments = new Array(4); for (var i = 0; i < 4; i++) { var segment = ellipseSegments[i]; segments[i] = new Segment( segment._point.multiply(radius).add(center), segment._handleIn.multiply(radius), segment._handleOut.multiply(radius) ); } return createPath(segments, true, args); } return { Line: function() { var args = arguments; return createPath([ new Segment(Point.readNamed(args, 'from')), new Segment(Point.readNamed(args, 'to')) ], false, args); }, Circle: function() { var args = arguments, center = Point.readNamed(args, 'center'), radius = Base.readNamed(args, 'radius'); return createEllipse(center, new Size(radius), args); }, Rectangle: function() { var args = arguments, rect = Rectangle.readNamed(args, 'rectangle'), radius = Size.readNamed(args, 'radius', 0, { readNull: true }), bl = rect.getBottomLeft(true), tl = rect.getTopLeft(true), tr = rect.getTopRight(true), br = rect.getBottomRight(true), segments; if (!radius || radius.isZero()) { segments = [ new Segment(bl), new Segment(tl), new Segment(tr), new Segment(br) ]; } else { radius = Size.min(radius, rect.getSize(true).divide(2)); var rx = radius.width, ry = radius.height, hx = rx * kappa, hy = ry * kappa; segments = [ new Segment(bl.add(rx, 0), null, [-hx, 0]), new Segment(bl.subtract(0, ry), [0, hy]), new Segment(tl.add(0, ry), null, [0, -hy]), new Segment(tl.add(rx, 0), [-hx, 0], null), new Segment(tr.subtract(rx, 0), null, [hx, 0]), new Segment(tr.add(0, ry), [0, -hy], null), new Segment(br.subtract(0, ry), null, [0, hy]), new Segment(br.subtract(rx, 0), [hx, 0]) ]; } return createPath(segments, true, args); }, RoundRectangle: '#Rectangle', Ellipse: function() { var args = arguments, ellipse = Shape._readEllipse(args); return createEllipse(ellipse.center, ellipse.radius, args); }, Oval: '#Ellipse', Arc: function() { var args = arguments, from = Point.readNamed(args, 'from'), through = Point.readNamed(args, 'through'), to = Point.readNamed(args, 'to'), props = Base.getNamed(args), path = new Path(props && props.insert == false && Item.NO_INSERT); path.moveTo(from); path.arcTo(through, to); return path.set(props); }, RegularPolygon: function() { var args = arguments, center = Point.readNamed(args, 'center'), sides = Base.readNamed(args, 'sides'), radius = Base.readNamed(args, 'radius'), step = 360 / sides, three = sides % 3 === 0, vector = new Point(0, three ? -radius : radius), offset = three ? -1 : 0.5, segments = new Array(sides); for (var i = 0; i < sides; i++) segments[i] = new Segment(center.add( vector.rotate((i + offset) * step))); return createPath(segments, true, args); }, Star: function() { var args = arguments, center = Point.readNamed(args, 'center'), points = Base.readNamed(args, 'points') * 2, radius1 = Base.readNamed(args, 'radius1'), radius2 = Base.readNamed(args, 'radius2'), step = 360 / points, vector = new Point(0, -1), segments = new Array(points); for (var i = 0; i < points; i++) segments[i] = new Segment(center.add(vector.rotate(step * i) .multiply(i % 2 ? radius2 : radius1))); return createPath(segments, true, args); } }; }}); var CompoundPath = PathItem.extend({ _class: 'CompoundPath', _serializeFields: { children: [] }, beans: true, initialize: function CompoundPath(arg) { this._children = []; this._namedChildren = {}; if (!this._initialize(arg)) { if (typeof arg === 'string') { this.setPathData(arg); } else { this.addChildren(Array.isArray(arg) ? arg : arguments); } } }, insertChildren: function insertChildren(index, items) { var list = items, first = list[0]; if (first && typeof first[0] === 'number') list = [list]; for (var i = items.length - 1; i >= 0; i--) { var item = list[i]; if (list === items && !(item instanceof Path)) list = Base.slice(list); if (Array.isArray(item)) { list[i] = new Path({ segments: item, insert: false }); } else if (item instanceof CompoundPath) { list.splice.apply(list, [i, 1].concat(item.removeChildren())); item.remove(); } } return insertChildren.base.call(this, index, list); }, reduce: function reduce(options) { var children = this._children; for (var i = children.length - 1; i >= 0; i--) { var path = children[i].reduce(options); if (path.isEmpty()) path.remove(); } if (!children.length) { var path = new Path(Item.NO_INSERT); path.copyAttributes(this); path.insertAbove(this); this.remove(); return path; } return reduce.base.call(this); }, isClosed: function() { var children = this._children; for (var i = 0, l = children.length; i < l; i++) { if (!children[i]._closed) return false; } return true; }, setClosed: function(closed) { var children = this._children; for (var i = 0, l = children.length; i < l; i++) { children[i].setClosed(closed); } }, getFirstSegment: function() { var first = this.getFirstChild(); return first && first.getFirstSegment(); }, getLastSegment: function() { var last = this.getLastChild(); return last && last.getLastSegment(); }, getCurves: function() { var children = this._children, curves = []; for (var i = 0, l = children.length; i < l; i++) { Base.push(curves, children[i].getCurves()); } return curves; }, getFirstCurve: function() { var first = this.getFirstChild(); return first && first.getFirstCurve(); }, getLastCurve: function() { var last = this.getLastChild(); return last && last.getLastCurve(); }, getArea: function() { var children = this._children, area = 0; for (var i = 0, l = children.length; i < l; i++) area += children[i].getArea(); return area; }, getLength: function() { var children = this._children, length = 0; for (var i = 0, l = children.length; i < l; i++) length += children[i].getLength(); return length; }, getPathData: function(_matrix, _precision) { var children = this._children, paths = []; for (var i = 0, l = children.length; i < l; i++) { var child = children[i], mx = child._matrix; paths.push(child.getPathData(_matrix && !mx.isIdentity() ? _matrix.appended(mx) : _matrix, _precision)); } return paths.join(''); }, _hitTestChildren: function _hitTestChildren(point, options, viewMatrix) { return _hitTestChildren.base.call(this, point, options.class === Path || options.type === 'path' ? options : Base.set({}, options, { fill: false }), viewMatrix); }, _draw: function(ctx, param, viewMatrix, strokeMatrix) { var children = this._children; if (!children.length) return; param = param.extend({ dontStart: true, dontFinish: true }); ctx.beginPath(); for (var i = 0, l = children.length; i < l; i++) children[i].draw(ctx, param, strokeMatrix); if (!param.clip) { this._setStyles(ctx, param, viewMatrix); var style = this._style; if (style.hasFill()) { ctx.fill(style.getFillRule()); ctx.shadowColor = 'rgba(0,0,0,0)'; } if (style.hasStroke()) ctx.stroke(); } }, _drawSelected: function(ctx, matrix, selectionItems) { var children = this._children; for (var i = 0, l = children.length; i < l; i++) { var child = children[i], mx = child._matrix; if (!selectionItems[child._id]) { child._drawSelected(ctx, mx.isIdentity() ? matrix : matrix.appended(mx)); } } } }, new function() { function getCurrentPath(that, check) { var children = that._children; if (check && !children.length) throw new Error('Use a moveTo() command first'); return children[children.length - 1]; } return Base.each(['lineTo', 'cubicCurveTo', 'quadraticCurveTo', 'curveTo', 'arcTo', 'lineBy', 'cubicCurveBy', 'quadraticCurveBy', 'curveBy', 'arcBy'], function(key) { this[key] = function() { var path = getCurrentPath(this, true); path[key].apply(path, arguments); }; }, { moveTo: function() { var current = getCurrentPath(this), path = current && current.isEmpty() ? current : new Path(Item.NO_INSERT); if (path !== current) this.addChild(path); path.moveTo.apply(path, arguments); }, moveBy: function() { var current = getCurrentPath(this, true), last = current && current.getLastSegment(), point = Point.read(arguments); this.moveTo(last ? point.add(last._point) : point); }, closePath: function(tolerance) { getCurrentPath(this, true).closePath(tolerance); } } ); }, Base.each(['reverse', 'flatten', 'simplify', 'smooth'], function(key) { this[key] = function(param) { var children = this._children, res; for (var i = 0, l = children.length; i < l; i++) { res = children[i][key](param) || res; } return res; }; }, {})); PathItem.inject(new function() { var min = Math.min, max = Math.max, abs = Math.abs, operators = { unite: { '1': true, '2': true }, intersect: { '2': true }, subtract: { '1': true }, exclude: { '1': true, '-1': true } }; function getPaths(path) { return path._children || [path]; } function preparePath(path, resolve) { var res = path .clone(false) .reduce({ simplify: true }) .transform(null, true, true); if (resolve) { var paths = getPaths(res); for (var i = 0, l = paths.length; i < l; i++) { var path = paths[i]; if (!path._closed && !path.isEmpty()) { path.closePath(1e-12); path.getFirstSegment().setHandleIn(0, 0); path.getLastSegment().setHandleOut(0, 0); } } res = res .resolveCrossings() .reorient(res.getFillRule() === 'nonzero', true); } return res; } function createResult(paths, simplify, path1, path2, options) { var result = new CompoundPath(Item.NO_INSERT); result.addChildren(paths, true); result = result.reduce({ simplify: simplify }); if (!(options && options.insert == false)) { result.insertAbove(path2 && path1.isSibling(path2) && path1.getIndex() < path2.getIndex() ? path2 : path1); } result.copyAttributes(path1, true); return result; } function filterIntersection(inter) { return inter.hasOverlap() || inter.isCrossing(); } function traceBoolean(path1, path2, operation, options) { if (options && (options.trace == false || options.stroke) && /^(subtract|intersect)$/.test(operation)) return splitBoolean(path1, path2, operation); var _path1 = preparePath(path1, true), _path2 = path2 && path1 !== path2 && preparePath(path2, true), operator = operators[operation]; operator[operation] = true; if (_path2 && (operator.subtract || operator.exclude) ^ (_path2.isClockwise() ^ _path1.isClockwise())) _path2.reverse(); var crossings = divideLocations(CurveLocation.expand( _path1.getIntersections(_path2, filterIntersection))), paths1 = getPaths(_path1), paths2 = _path2 && getPaths(_path2), segments = [], curves = [], paths; function collectPaths(paths) { for (var i = 0, l = paths.length; i < l; i++) { var path = paths[i]; Base.push(segments, path._segments); Base.push(curves, path.getCurves()); path._overlapsOnly = true; } } function getCurves(indices) { var list = []; for (var i = 0, l = indices && indices.length; i < l; i++) { list.push(curves[indices[i]]); } return list; } if (crossings.length) { collectPaths(paths1); if (paths2) collectPaths(paths2); var curvesValues = new Array(curves.length); for (var i = 0, l = curves.length; i < l; i++) { curvesValues[i] = curves[i].getValues(); } var curveCollisions = CollisionDetection.findCurveBoundsCollisions( curvesValues, curvesValues, 0, true); var curveCollisionsMap = {}; for (var i = 0; i < curves.length; i++) { var curve = curves[i], id = curve._path._id, map = curveCollisionsMap[id] = curveCollisionsMap[id] || {}; map[curve.getIndex()] = { hor: getCurves(curveCollisions[i].hor), ver: getCurves(curveCollisions[i].ver) }; } for (var i = 0, l = crossings.length; i < l; i++) { propagateWinding(crossings[i]._segment, _path1, _path2, curveCollisionsMap, operator); } for (var i = 0, l = segments.length; i < l; i++) { var segment = segments[i], inter = segment._intersection; if (!segment._winding) { propagateWinding(segment, _path1, _path2, curveCollisionsMap, operator); } if (!(inter && inter._overlap)) segment._path._overlapsOnly = false; } paths = tracePaths(segments, operator); } else { paths = reorientPaths( paths2 ? paths1.concat(paths2) : paths1.slice(), function(w) { return !!operator[w]; }); } return createResult(paths, true, path1, path2, options); } function splitBoolean(path1, path2, operation) { var _path1 = preparePath(path1), _path2 = preparePath(path2), crossings = _path1.getIntersections(_path2, filterIntersection), subtract = operation === 'subtract', divide = operation === 'divide', added = {}, paths = []; function addPath(path) { if (!added[path._id] && (divide || _path2.contains(path.getPointAt(path.getLength() / 2)) ^ subtract)) { paths.unshift(path); return added[path._id] = true; } } for (var i = crossings.length - 1; i >= 0; i--) { var path = crossings[i].split(); if (path) { if (addPath(path)) path.getFirstSegment().setHandleIn(0, 0); _path1.getLastSegment().setHandleOut(0, 0); } } addPath(_path1); return createResult(paths, false, path1, path2); } function linkIntersections(from, to) { var prev = from; while (prev) { if (prev === to) return; prev = prev._previous; } while (from._next && from._next !== to) from = from._next; if (!from._next) { while (to._previous) to = to._previous; from._next = to; to._previous = from; } } function clearCurveHandles(curves) { for (var i = curves.length - 1; i >= 0; i--) curves[i].clearHandles(); } function reorientPaths(paths, isInside, clockwise) { var length = paths && paths.length; if (length) { var lookup = Base.each(paths, function (path, i) { this[path._id] = { container: null, winding: path.isClockwise() ? 1 : -1, index: i }; }, {}), sorted = paths.slice().sort(function (a, b) { return abs(b.getArea()) - abs(a.getArea()); }), first = sorted[0]; var collisions = CollisionDetection.findItemBoundsCollisions(sorted, null, Numerical.GEOMETRIC_EPSILON); if (clockwise == null) clockwise = first.isClockwise(); for (var i = 0; i < length; i++) { var path1 = sorted[i], entry1 = lookup[path1._id], containerWinding = 0, indices = collisions[i]; if (indices) { var point = null; for (var j = indices.length - 1; j >= 0; j--) { if (indices[j] < i) { point = point || path1.getInteriorPoint(); var path2 = sorted[indices[j]]; if (path2.contains(point)) { var entry2 = lookup[path2._id]; containerWinding = entry2.winding; entry1.winding += containerWinding; entry1.container = entry2.exclude ? entry2.container : path2; break; } } } } if (isInside(entry1.winding) === isInside(containerWinding)) { entry1.exclude = true; paths[entry1.index] = null; } else { var container = entry1.container; path1.setClockwise( container ? !container.isClockwise() : clockwise); } } } return paths; } function divideLocations(locations, include, clearLater) { var results = include && [], tMin = 1e-8, tMax = 1 - tMin, clearHandles = false, clearCurves = clearLater || [], clearLookup = clearLater && {}, renormalizeLocs, prevCurve, prevTime; function getId(curve) { return curve._path._id + '.' + curve._segment1._index; } for (var i = (clearLater && clearLater.length) - 1; i >= 0; i--) { var curve = clearLater[i]; if (curve._path) clearLookup[getId(curve)] = true; } for (var i = locations.length - 1; i >= 0; i--) { var loc = locations[i], time = loc._time, origTime = time, exclude = include && !include(loc), curve = loc._curve, segment; if (curve) { if (curve !== prevCurve) { clearHandles = !curve.hasHandles() || clearLookup && clearLookup[getId(curve)]; renormalizeLocs = []; prevTime = null; prevCurve = curve; } else if (prevTime >= tMin) { time /= prevTime; } } if (exclude) { if (renormalizeLocs) renormalizeLocs.push(loc); continue; } else if (include) { results.unshift(loc); } prevTime = origTime; if (time < tMin) { segment = curve._segment1; } else if (time > tMax) { segment = curve._segment2; } else { var newCurve = curve.divideAtTime(time, true); if (clearHandles) clearCurves.push(curve, newCurve); segment = newCurve._segment1; for (var j = renormalizeLocs.length - 1; j >= 0; j--) { var l = renormalizeLocs[j]; l._time = (l._time - time) / (1 - time); } } loc._setSegment(segment); var inter = segment._intersection, dest = loc._intersection; if (inter) { linkIntersections(inter, dest); var other = inter; while (other) { linkIntersections(other._intersection, inter); other = other._next; } } else { segment._intersection = dest; } } if (!clearLater) clearCurveHandles(clearCurves); return results || locations; } function getWinding(point, curves, dir, closed, dontFlip) { var curvesList = Array.isArray(curves) ? curves : curves[dir ? 'hor' : 'ver']; var ia = dir ? 1 : 0, io = ia ^ 1, pv = [point.x, point.y], pa = pv[ia], po = pv[io], windingEpsilon = 1e-9, qualityEpsilon = 1e-6, paL = pa - windingEpsilon, paR = pa + windingEpsilon, windingL = 0, windingR = 0, pathWindingL = 0, pathWindingR = 0, onPath = false, onAnyPath = false, quality = 1, roots = [], vPrev, vClose; function addWinding(v) { var o0 = v[io + 0], o3 = v[io + 6]; if (po < min(o0, o3) || po > max(o0, o3)) { return; } var a0 = v[ia + 0], a1 = v[ia + 2], a2 = v[ia + 4], a3 = v[ia + 6]; if (o0 === o3) { if (a0 < paR && a3 > paL || a3 < paR && a0 > paL) { onPath = true; } return; } var t = po === o0 ? 0 : po === o3 ? 1 : paL > max(a0, a1, a2, a3) || paR < min(a0, a1, a2, a3) ? 1 : Curve.solveCubic(v, io, po, roots, 0, 1) > 0 ? roots[0] : 1, a = t === 0 ? a0 : t === 1 ? a3 : Curve.getPoint(v, t)[dir ? 'y' : 'x'], winding = o0 > o3 ? 1 : -1, windingPrev = vPrev[io] > vPrev[io + 6] ? 1 : -1, a3Prev = vPrev[ia + 6]; if (po !== o0) { if (a < paL) { pathWindingL += winding; } else if (a > paR) { pathWindingR += winding; } else { onPath = true; } if (a > pa - qualityEpsilon && a < pa + qualityEpsilon) quality /= 2; } else { if (winding !== windingPrev) { if (a0 < paL) { pathWindingL += winding; } else if (a0 > paR) { pathWindingR += winding; } } else if (a0 != a3Prev) { if (a3Prev < paR && a > paR) { pathWindingR += winding; onPath = true; } else if (a3Prev > paL && a < paL) { pathWindingL += winding; onPath = true; } } quality /= 4; } vPrev = v; return !dontFlip && a > paL && a < paR && Curve.getTangent(v, t)[dir ? 'x' : 'y'] === 0 && getWinding(point, curves, !dir, closed, true); } function handleCurve(v) { var o0 = v[io + 0], o1 = v[io + 2], o2 = v[io + 4], o3 = v[io + 6]; if (po <= max(o0, o1, o2, o3) && po >= min(o0, o1, o2, o3)) { var a0 = v[ia + 0], a1 = v[ia + 2], a2 = v[ia + 4], a3 = v[ia + 6], monoCurves = paL > max(a0, a1, a2, a3) || paR < min(a0, a1, a2, a3) ? [v] : Curve.getMonoCurves(v, dir), res; for (var i = 0, l = monoCurves.length; i < l; i++) { if (res = addWinding(monoCurves[i])) return res; } } } for (var i = 0, l = curvesList.length; i < l; i++) { var curve = curvesList[i], path = curve._path, v = curve.getValues(), res; if (!i || curvesList[i - 1]._path !== path) { vPrev = null; if (!path._closed) { vClose = Curve.getValues( path.getLastCurve().getSegment2(), curve.getSegment1(), null, !closed); if (vClose[io] !== vClose[io + 6]) { vPrev = vClose; } } if (!vPrev) { vPrev = v; var prev = path.getLastCurve(); while (prev && prev !== curve) { var v2 = prev.getValues(); if (v2[io] !== v2[io + 6]) { vPrev = v2; break; } prev = prev.getPrevious(); } } } if (res = handleCurve(v)) return res; if (i + 1 === l || curvesList[i + 1]._path !== path) { if (vClose && (res = handleCurve(vClose))) return res; if (onPath && !pathWindingL && !pathWindingR) { pathWindingL = pathWindingR = path.isClockwise(closed) ^ dir ? 1 : -1; } windingL += pathWindingL; windingR += pathWindingR; pathWindingL = pathWindingR = 0; if (onPath) { onAnyPath = true; onPath = false; } vClose = null; } } windingL = abs(windingL); windingR = abs(windingR); return { winding: max(windingL, windingR), windingL: windingL, windingR: windingR, quality: quality, onPath: onAnyPath }; } function propagateWinding(segment, path1, path2, curveCollisionsMap, operator) { var chain = [], start = segment, totalLength = 0, winding; do { var curve = segment.getCurve(); if (curve) { var length = curve.getLength(); chain.push({ segment: segment, curve: curve, length: length }); totalLength += length; } segment = segment.getNext(); } while (segment && !segment._intersection && segment !== start); var offsets = [0.5, 0.25, 0.75], winding = { winding: 0, quality: -1 }, tMin = 1e-3, tMax = 1 - tMin; for (var i = 0; i < offsets.length && winding.quality < 0.5; i++) { var length = totalLength * offsets[i]; for (var j = 0, l = chain.length; j < l; j++) { var entry = chain[j], curveLength = entry.length; if (length <= curveLength) { var curve = entry.curve, path = curve._path, parent = path._parent, operand = parent instanceof CompoundPath ? parent : path, t = Numerical.clamp(curve.getTimeAt(length), tMin, tMax), pt = curve.getPointAtTime(t), dir = abs(curve.getTangentAtTime(t).y) < Math.SQRT1_2; var wind = null; if (operator.subtract && path2) { var otherPath = operand === path1 ? path2 : path1, pathWinding = otherPath._getWinding(pt, dir, true); if (operand === path1 && pathWinding.winding || operand === path2 && !pathWinding.winding) { if (pathWinding.quality < 1) { continue; } else { wind = { winding: 0, quality: 1 }; } } } wind = wind || getWinding( pt, curveCollisionsMap[path._id][curve.getIndex()], dir, true); if (wind.quality > winding.quality) winding = wind; break; } length -= curveLength; } } for (var j = chain.length - 1; j >= 0; j--) { chain[j].segment._winding = winding; } } function tracePaths(segments, operator) { var paths = [], starts; function isValid(seg) { var winding; return !!(seg && !seg._visited && (!operator || operator[(winding = seg._winding || {}).winding] && !(operator.unite && winding.winding === 2 && winding.windingL && winding.windingR))); } function isStart(seg) { if (seg) { for (var i = 0, l = starts.length; i < l; i++) { if (seg === starts[i]) return true; } } return false; } function visitPath(path) { var segments = path._segments; for (var i = 0, l = segments.length; i < l; i++) { segments[i]._visited = true; } } function getCrossingSegments(segment, collectStarts) { var inter = segment._intersection, start = inter, crossings = []; if (collectStarts) starts = [segment]; function collect(inter, end) { while (inter && inter !== end) { var other = inter._segment, path = other && other._path; if (path) { var next = other.getNext() || path.getFirstSegment(), nextInter = next._intersection; if (other !== segment && (isStart(other) || isStart(next) || next && (isValid(other) && (isValid(next) || nextInter && isValid(nextInter._segment)))) ) { crossings.push(other); } if (collectStarts) starts.push(other); } inter = inter._next; } } if (inter) { collect(inter); while (inter && inter._previous) inter = inter._previous; collect(inter, start); } return crossings; } segments.sort(function(seg1, seg2) { var inter1 = seg1._intersection, inter2 = seg2._intersection, over1 = !!(inter1 && inter1._overlap), over2 = !!(inter2 && inter2._overlap), path1 = seg1._path, path2 = seg2._path; return over1 ^ over2 ? over1 ? 1 : -1 : !inter1 ^ !inter2 ? inter1 ? 1 : -1 : path1 !== path2 ? path1._id - path2._id : seg1._index - seg2._index; }); for (var i = 0, l = segments.length; i < l; i++) { var seg = segments[i], valid = isValid(seg), path = null, finished = false, closed = true, branches = [], branch, visited, handleIn; if (valid && seg._path._overlapsOnly) { var path1 = seg._path, path2 = seg._intersection._segment._path; if (path1.compare(path2)) { if (path1.getArea()) paths.push(path1.clone(false)); visitPath(path1); visitPath(path2); valid = false; } } while (valid) { var first = !path, crossings = getCrossingSegments(seg, first), other = crossings.shift(), finished = !first && (isStart(seg) || isStart(other)), cross = !finished && other; if (first) { path = new Path(Item.NO_INSERT); branch = null; } if (finished) { if (seg.isFirst() || seg.isLast()) closed = seg._path._closed; seg._visited = true; break; } if (cross && branch) { branches.push(branch); branch = null; } if (!branch) { if (cross) crossings.push(seg); branch = { start: path._segments.length, crossings: crossings, visited: visited = [], handleIn: handleIn }; } if (cross) seg = other; if (!isValid(seg)) { path.removeSegments(branch.start); for (var j = 0, k = visited.length; j < k; j++) { visited[j]._visited = false; } visited.length = 0; do { seg = branch && branch.crossings.shift(); if (!seg || !seg._path) { seg = null; branch = branches.pop(); if (branch) { visited = branch.visited; handleIn = branch.handleIn; } } } while (branch && !isValid(seg)); if (!seg) break; } var next = seg.getNext(); path.add(new Segment(seg._point, handleIn, next && seg._handleOut)); seg._visited = true; visited.push(seg); seg = next || seg._path.getFirstSegment(); handleIn = next && next._handleIn; } if (finished) { if (closed) { path.getFirstSegment().setHandleIn(handleIn); path.setClosed(closed); } if (path.getArea() !== 0) { paths.push(path); } } } return paths; } return { _getWinding: function(point, dir, closed) { return getWinding(point, this.getCurves(), dir, closed); }, unite: function(path, options) { return traceBoolean(this, path, 'unite', options); }, intersect: function(path, options) { return traceBoolean(this, path, 'intersect', options); }, subtract: function(path, options) { return traceBoolean(this, path, 'subtract', options); }, exclude: function(path, options) { return traceBoolean(this, path, 'exclude', options); }, divide: function(path, options) { return options && (options.trace == false || options.stroke) ? splitBoolean(this, path, 'divide') : createResult([ this.subtract(path, options), this.intersect(path, options) ], true, this, path, options); }, resolveCrossings: function() { var children = this._children, paths = children || [this]; function hasOverlap(seg, path) { var inter = seg && seg._intersection; return inter && inter._overlap && inter._path === path; } var hasOverlaps = false, hasCrossings = false, intersections = this.getIntersections(null, function(inter) { return inter.hasOverlap() && (hasOverlaps = true) || inter.isCrossing() && (hasCrossings = true); }), clearCurves = hasOverlaps && hasCrossings && []; intersections = CurveLocation.expand(intersections); if (hasOverlaps) { var overlaps = divideLocations(intersections, function(inter) { return inter.hasOverlap(); }, clearCurves); for (var i = overlaps.length - 1; i >= 0; i--) { var overlap = overlaps[i], path = overlap._path, seg = overlap._segment, prev = seg.getPrevious(), next = seg.getNext(); if (hasOverlap(prev, path) && hasOverlap(next, path)) { seg.remove(); prev._handleOut._set(0, 0); next._handleIn._set(0, 0); if (prev !== seg && !prev.getCurve().hasLength()) { next._handleIn.set(prev._handleIn); prev.remove(); } } } } if (hasCrossings) { divideLocations(intersections, hasOverlaps && function(inter) { var curve1 = inter.getCurve(), seg1 = inter.getSegment(), other = inter._intersection, curve2 = other._curve, seg2 = other._segment; if (curve1 && curve2 && curve1._path && curve2._path) return true; if (seg1) seg1._intersection = null; if (seg2) seg2._intersection = null; }, clearCurves); if (clearCurves) clearCurveHandles(clearCurves); paths = tracePaths(Base.each(paths, function(path) { Base.push(this, path._segments); }, [])); } var length = paths.length, item; if (length > 1 && children) { if (paths !== children) this.setChildren(paths); item = this; } else if (length === 1 && !children) { if (paths[0] !== this) this.setSegments(paths[0].removeSegments()); item = this; } if (!item) { item = new CompoundPath(Item.NO_INSERT); item.addChildren(paths); item = item.reduce(); item.copyAttributes(this); this.replaceWith(item); } return item; }, reorient: function(nonZero, clockwise) { var children = this._children; if (children && children.length) { this.setChildren(reorientPaths(this.removeChildren(), function(w) { return !!(nonZero ? w : w & 1); }, clockwise)); } else if (clockwise !== undefined) { this.setClockwise(clockwise); } return this; }, getInteriorPoint: function() { var bounds = this.getBounds(), point = bounds.getCenter(true); if (!this.contains(point)) { var curves = this.getCurves(), y = point.y, intercepts = [], roots = []; for (var i = 0, l = curves.length; i < l; i++) { var v = curves[i].getValues(), o0 = v[1], o1 = v[3], o2 = v[5], o3 = v[7]; if (y >= min(o0, o1, o2, o3) && y <= max(o0, o1, o2, o3)) { var monoCurves = Curve.getMonoCurves(v); for (var j = 0, m = monoCurves.length; j < m; j++) { var mv = monoCurves[j], mo0 = mv[1], mo3 = mv[7]; if ((mo0 !== mo3) && (y >= mo0 && y <= mo3 || y >= mo3 && y <= mo0)){ var x = y === mo0 ? mv[0] : y === mo3 ? mv[6] : Curve.solveCubic(mv, 1, y, roots, 0, 1) === 1 ? Curve.getPoint(mv, roots[0]).x : (mv[0] + mv[6]) / 2; intercepts.push(x); } } } } if (intercepts.length > 1) { intercepts.sort(function(a, b) { return a - b; }); point.x = (intercepts[0] + intercepts[1]) / 2; } } return point; } }; }); var PathFlattener = Base.extend({ _class: 'PathFlattener', initialize: function(path, flatness, maxRecursion, ignoreStraight, matrix) { var curves = [], parts = [], length = 0, minSpan = 1 / (maxRecursion || 32), segments = path._segments, segment1 = segments[0], segment2; function addCurve(segment1, segment2) { var curve = Curve.getValues(segment1, segment2, matrix); curves.push(curve); computeParts(curve, segment1._index, 0, 1); } function computeParts(curve, index, t1, t2) { if ((t2 - t1) > minSpan && !(ignoreStraight && Curve.isStraight(curve)) && !Curve.isFlatEnough(curve, flatness || 0.25)) { var halves = Curve.subdivide(curve, 0.5), tMid = (t1 + t2) / 2; computeParts(halves[0], index, t1, tMid); computeParts(halves[1], index, tMid, t2); } else { var dx = curve[6] - curve[0], dy = curve[7] - curve[1], dist = Math.sqrt(dx * dx + dy * dy); if (dist > 0) { length += dist; parts.push({ offset: length, curve: curve, index: index, time: t2, }); } } } for (var i = 1, l = segments.length; i < l; i++) { segment2 = segments[i]; addCurve(segment1, segment2); segment1 = segment2; } if (path._closed) addCurve(segment2 || segment1, segments[0]); this.curves = curves; this.parts = parts; this.length = length; this.index = 0; }, _get: function(offset) { var parts = this.parts, length = parts.length, start, i, j = this.index; for (;;) { i = j; if (!j || parts[--j].offset < offset) break; } for (; i < length; i++) { var part = parts[i]; if (part.offset >= offset) { this.index = i; var prev = parts[i - 1], prevTime = prev && prev.index === part.index ? prev.time : 0, prevOffset = prev ? prev.offset : 0; return { index: part.index, time: prevTime + (part.time - prevTime) * (offset - prevOffset) / (part.offset - prevOffset) }; } } return { index: parts[length - 1].index, time: 1 }; }, drawPart: function(ctx, from, to) { var start = this._get(from), end = this._get(to); for (var i = start.index, l = end.index; i <= l; i++) { var curve = Curve.getPart(this.curves[i], i === start.index ? start.time : 0, i === end.index ? end.time : 1); if (i === start.index) ctx.moveTo(curve[0], curve[1]); ctx.bezierCurveTo.apply(ctx, curve.slice(2)); } } }, Base.each(Curve._evaluateMethods, function(name) { this[name + 'At'] = function(offset) { var param = this._get(offset); return Curve[name](this.curves[param.index], param.time); }; }, {}) ); var PathFitter = Base.extend({ initialize: function(path) { var points = this.points = [], segments = path._segments, closed = path._closed; for (var i = 0, prev, l = segments.length; i < l; i++) { var point = segments[i].point; if (!prev || !prev.equals(point)) { points.push(prev = point.clone()); } } if (closed) { points.unshift(points[points.length - 1]); points.push(points[1]); } this.closed = closed; }, fit: function(error) { var points = this.points, length = points.length, segments = null; if (length > 0) { segments = [new Segment(points[0])]; if (length > 1) { this.fitCubic(segments, error, 0, length - 1, points[1].subtract(points[0]), points[length - 2].subtract(points[length - 1])); if (this.closed) { segments.shift(); segments.pop(); } } } return segments; }, fitCubic: function(segments, error, first, last, tan1, tan2) { var points = this.points; if (last - first === 1) { var pt1 = points[first], pt2 = points[last], dist = pt1.getDistance(pt2) / 3; this.addCurve(segments, [pt1, pt1.add(tan1.normalize(dist)), pt2.add(tan2.normalize(dist)), pt2]); return; } var uPrime = this.chordLengthParameterize(first, last), maxError = Math.max(error, error * error), split, parametersInOrder = true; for (var i = 0; i <= 4; i++) { var curve = this.generateBezier(first, last, uPrime, tan1, tan2); var max = this.findMaxError(first, last, curve, uPrime); if (max.error < error && parametersInOrder) { this.addCurve(segments, curve); return; } split = max.index; if (max.error >= maxError) break; parametersInOrder = this.reparameterize(first, last, uPrime, curve); maxError = max.error; } var tanCenter = points[split - 1].subtract(points[split + 1]); this.fitCubic(segments, error, first, split, tan1, tanCenter); this.fitCubic(segments, error, split, last, tanCenter.negate(), tan2); }, addCurve: function(segments, curve) { var prev = segments[segments.length - 1]; prev.setHandleOut(curve[1].subtract(curve[0])); segments.push(new Segment(curve[3], curve[2].subtract(curve[3]))); }, generateBezier: function(first, last, uPrime, tan1, tan2) { var epsilon = 1e-12, abs = Math.abs, points = this.points, pt1 = points[first], pt2 = points[last], C = [[0, 0], [0, 0]], X = [0, 0]; for (var i = 0, l = last - first + 1; i < l; i++) { var u = uPrime[i], t = 1 - u, b = 3 * u * t, b0 = t * t * t, b1 = b * t, b2 = b * u, b3 = u * u * u, a1 = tan1.normalize(b1), a2 = tan2.normalize(b2), tmp = points[first + i] .subtract(pt1.multiply(b0 + b1)) .subtract(pt2.multiply(b2 + b3)); C[0][0] += a1.dot(a1); C[0][1] += a1.dot(a2); C[1][0] = C[0][1]; C[1][1] += a2.dot(a2); X[0] += a1.dot(tmp); X[1] += a2.dot(tmp); } var detC0C1 = C[0][0] * C[1][1] - C[1][0] * C[0][1], alpha1, alpha2; if (abs(detC0C1) > epsilon) { var detC0X = C[0][0] * X[1] - C[1][0] * X[0], detXC1 = X[0] * C[1][1] - X[1] * C[0][1]; alpha1 = detXC1 / detC0C1; alpha2 = detC0X / detC0C1; } else { var c0 = C[0][0] + C[0][1], c1 = C[1][0] + C[1][1]; alpha1 = alpha2 = abs(c0) > epsilon ? X[0] / c0 : abs(c1) > epsilon ? X[1] / c1 : 0; } var segLength = pt2.getDistance(pt1), eps = epsilon * segLength, handle1, handle2; if (alpha1 < eps || alpha2 < eps) { alpha1 = alpha2 = segLength / 3; } else { var line = pt2.subtract(pt1); handle1 = tan1.normalize(alpha1); handle2 = tan2.normalize(alpha2); if (handle1.dot(line) - handle2.dot(line) > segLength * segLength) { alpha1 = alpha2 = segLength / 3; handle1 = handle2 = null; } } return [pt1, pt1.add(handle1 || tan1.normalize(alpha1)), pt2.add(handle2 || tan2.normalize(alpha2)), pt2]; }, reparameterize: function(first, last, u, curve) { for (var i = first; i <= last; i++) { u[i - first] = this.findRoot(curve, this.points[i], u[i - first]); } for (var i = 1, l = u.length; i < l; i++) { if (u[i] <= u[i - 1]) return false; } return true; }, findRoot: function(curve, point, u) { var curve1 = [], curve2 = []; for (var i = 0; i <= 2; i++) { curve1[i] = curve[i + 1].subtract(curve[i]).multiply(3); } for (var i = 0; i <= 1; i++) { curve2[i] = curve1[i + 1].subtract(curve1[i]).multiply(2); } var pt = this.evaluate(3, curve, u), pt1 = this.evaluate(2, curve1, u), pt2 = this.evaluate(1, curve2, u), diff = pt.subtract(point), df = pt1.dot(pt1) + diff.dot(pt2); return Numerical.isMachineZero(df) ? u : u - diff.dot(pt1) / df; }, evaluate: function(degree, curve, t) { var tmp = curve.slice(); for (var i = 1; i <= degree; i++) { for (var j = 0; j <= degree - i; j++) { tmp[j] = tmp[j].multiply(1 - t).add(tmp[j + 1].multiply(t)); } } return tmp[0]; }, chordLengthParameterize: function(first, last) { var u = [0]; for (var i = first + 1; i <= last; i++) { u[i - first] = u[i - first - 1] + this.points[i].getDistance(this.points[i - 1]); } for (var i = 1, m = last - first; i <= m; i++) { u[i] /= u[m]; } return u; }, findMaxError: function(first, last, curve, u) { var index = Math.floor((last - first + 1) / 2), maxDist = 0; for (var i = first + 1; i < last; i++) { var P = this.evaluate(3, curve, u[i - first]); var v = P.subtract(this.points[i]); var dist = v.x * v.x + v.y * v.y; if (dist >= maxDist) { maxDist = dist; index = i; } } return { error: maxDist, index: index }; } }); var TextItem = Item.extend({ _class: 'TextItem', _applyMatrix: false, _canApplyMatrix: false, _serializeFields: { content: null }, _boundsOptions: { stroke: false, handle: false }, initialize: function TextItem(arg) { this._content = ''; this._lines = []; var hasProps = arg && Base.isPlainObject(arg) && arg.x === undefined && arg.y === undefined; this._initialize(hasProps && arg, !hasProps && Point.read(arguments)); }, _equals: function(item) { return this._content === item._content; }, copyContent: function(source) { this.setContent(source._content); }, getContent: function() { return this._content; }, setContent: function(content) { this._content = '' + content; this._lines = this._content.split(/\r\n|\n|\r/mg); this._changed(521); }, isEmpty: function() { return !this._content; }, getCharacterStyle: '#getStyle', setCharacterStyle: '#setStyle', getParagraphStyle: '#getStyle', setParagraphStyle: '#setStyle' }); var PointText = TextItem.extend({ _class: 'PointText', initialize: function PointText() { TextItem.apply(this, arguments); }, getPoint: function() { var point = this._matrix.getTranslation(); return new LinkedPoint(point.x, point.y, this, 'setPoint'); }, setPoint: function() { var point = Point.read(arguments); this.translate(point.subtract(this._matrix.getTranslation())); }, _draw: function(ctx, param, viewMatrix) { if (!this._content) return; this._setStyles(ctx, param, viewMatrix); var lines = this._lines, style = this._style, hasFill = style.hasFill(), hasStroke = style.hasStroke(), leading = style.getLeading(), shadowColor = ctx.shadowColor; ctx.font = style.getFontStyle(); ctx.textAlign = style.getJustification(); for (var i = 0, l = lines.length; i < l; i++) { ctx.shadowColor = shadowColor; var line = lines[i]; if (hasFill) { ctx.fillText(line, 0, 0); ctx.shadowColor = 'rgba(0,0,0,0)'; } if (hasStroke) ctx.strokeText(line, 0, 0); ctx.translate(0, leading); } }, _getBounds: function(matrix, options) { var style = this._style, lines = this._lines, numLines = lines.length, justification = style.getJustification(), leading = style.getLeading(), width = this.getView().getTextWidth(style.getFontStyle(), lines), x = 0; if (justification !== 'left') x -= width / (justification === 'center' ? 2: 1); var rect = new Rectangle(x, numLines ? - 0.75 * leading : 0, width, numLines * leading); return matrix ? matrix._transformBounds(rect, rect) : rect; } }); var Color = Base.extend(new function() { var types = { gray: ['gray'], rgb: ['red', 'green', 'blue'], hsb: ['hue', 'saturation', 'brightness'], hsl: ['hue', 'saturation', 'lightness'], gradient: ['gradient', 'origin', 'destination', 'highlight'] }; var componentParsers = {}, namedColors = { transparent: [0, 0, 0, 0] }, colorCtx; function fromCSS(string) { var match = string.match( /^#([\da-f]{2})([\da-f]{2})([\da-f]{2})([\da-f]{2})?$/i ) || string.match( /^#([\da-f])([\da-f])([\da-f])([\da-f])?$/i ), type = 'rgb', components; if (match) { var amount = match[4] ? 4 : 3; components = new Array(amount); for (var i = 0; i < amount; i++) { var value = match[i + 1]; components[i] = parseInt(value.length == 1 ? value + value : value, 16) / 255; } } else if (match = string.match(/^(rgb|hsl)a?\((.*)\)$/)) { type = match[1]; components = match[2].trim().split(/[,\s]+/g); var isHSL = type === 'hsl'; for (var i = 0, l = Math.min(components.length, 4); i < l; i++) { var component = components[i]; var value = parseFloat(component); if (isHSL) { if (i === 0) { var unit = component.match(/([a-z]*)$/)[1]; value *= ({ turn: 360, rad: 180 / Math.PI, grad: 0.9 }[unit] || 1); } else if (i < 3) { value /= 100; } } else if (i < 3) { value /= /%$/.test(component) ? 100 : 255; } components[i] = value; } } else { var color = namedColors[string]; if (!color) { if (window) { if (!colorCtx) { colorCtx = CanvasProvider.getContext(1, 1); colorCtx.globalCompositeOperation = 'copy'; } colorCtx.fillStyle = 'rgba(0,0,0,0)'; colorCtx.fillStyle = string; colorCtx.fillRect(0, 0, 1, 1); var data = colorCtx.getImageData(0, 0, 1, 1).data; color = namedColors[string] = [ data[0] / 255, data[1] / 255, data[2] / 255 ]; } else { color = [0, 0, 0]; } } components = color.slice(); } return [type, components]; } var hsbIndices = [ [0, 3, 1], [2, 0, 1], [1, 0, 3], [1, 2, 0], [3, 1, 0], [0, 1, 2] ]; var converters = { 'rgb-hsb': function(r, g, b) { var max = Math.max(r, g, b), min = Math.min(r, g, b), delta = max - min, h = delta === 0 ? 0 : ( max == r ? (g - b) / delta + (g < b ? 6 : 0) : max == g ? (b - r) / delta + 2 : (r - g) / delta + 4) * 60; return [h, max === 0 ? 0 : delta / max, max]; }, 'hsb-rgb': function(h, s, b) { h = (((h / 60) % 6) + 6) % 6; var i = Math.floor(h), f = h - i, i = hsbIndices[i], v = [ b, b * (1 - s), b * (1 - s * f), b * (1 - s * (1 - f)) ]; return [v[i[0]], v[i[1]], v[i[2]]]; }, 'rgb-hsl': function(r, g, b) { var max = Math.max(r, g, b), min = Math.min(r, g, b), delta = max - min, achromatic = delta === 0, h = achromatic ? 0 : ( max == r ? (g - b) / delta + (g < b ? 6 : 0) : max == g ? (b - r) / delta + 2 : (r - g) / delta + 4) * 60, l = (max + min) / 2, s = achromatic ? 0 : l < 0.5 ? delta / (max + min) : delta / (2 - max - min); return [h, s, l]; }, 'hsl-rgb': function(h, s, l) { h = (((h / 360) % 1) + 1) % 1; if (s === 0) return [l, l, l]; var t3s = [ h + 1 / 3, h, h - 1 / 3 ], t2 = l < 0.5 ? l * (1 + s) : l + s - l * s, t1 = 2 * l - t2, c = []; for (var i = 0; i < 3; i++) { var t3 = t3s[i]; if (t3 < 0) t3 += 1; if (t3 > 1) t3 -= 1; c[i] = 6 * t3 < 1 ? t1 + (t2 - t1) * 6 * t3 : 2 * t3 < 1 ? t2 : 3 * t3 < 2 ? t1 + (t2 - t1) * ((2 / 3) - t3) * 6 : t1; } return c; }, 'rgb-gray': function(r, g, b) { return [r * 0.2989 + g * 0.587 + b * 0.114]; }, 'gray-rgb': function(g) { return [g, g, g]; }, 'gray-hsb': function(g) { return [0, 0, g]; }, 'gray-hsl': function(g) { return [0, 0, g]; }, 'gradient-rgb': function() { return []; }, 'rgb-gradient': function() { return []; } }; return Base.each(types, function(properties, type) { componentParsers[type] = []; Base.each(properties, function(name, index) { var part = Base.capitalize(name), hasOverlap = /^(hue|saturation)$/.test(name), parser = componentParsers[type][index] = type === 'gradient' ? name === 'gradient' ? function(value) { var current = this._components[0]; value = Gradient.read( Array.isArray(value) ? value : arguments, 0, { readNull: true } ); if (current !== value) { if (current) current._removeOwner(this); if (value) value._addOwner(this); } return value; } : function() { return Point.read(arguments, 0, { readNull: name === 'highlight', clone: true }); } : function(value) { return value == null || isNaN(value) ? 0 : +value; }; this['get' + part] = function() { return this._type === type || hasOverlap && /^hs[bl]$/.test(this._type) ? this._components[index] : this._convert(type)[index]; }; this['set' + part] = function(value) { if (this._type !== type && !(hasOverlap && /^hs[bl]$/.test(this._type))) { this._components = this._convert(type); this._properties = types[type]; this._type = type; } this._components[index] = parser.call(this, value); this._changed(); }; }, this); }, { _class: 'Color', _readIndex: true, initialize: function Color(arg) { var args = arguments, reading = this.__read, read = 0, type, components, alpha, values; if (Array.isArray(arg)) { args = arg; arg = args[0]; } var argType = arg != null && typeof arg; if (argType === 'string' && arg in types) { type = arg; arg = args[1]; if (Array.isArray(arg)) { components = arg; alpha = args[2]; } else { if (reading) read = 1; args = Base.slice(args, 1); argType = typeof arg; } } if (!components) { values = argType === 'number' ? args : argType === 'object' && arg.length != null ? arg : null; if (values) { if (!type) type = values.length >= 3 ? 'rgb' : 'gray'; var length = types[type].length; alpha = values[length]; if (reading) { read += values === arguments ? length + (alpha != null ? 1 : 0) : 1; } if (values.length > length) values = Base.slice(values, 0, length); } else if (argType === 'string') { var converted = fromCSS(arg); type = converted[0]; components = converted[1]; if (components.length === 4) { alpha = components[3]; components.length--; } } else if (argType === 'object') { if (arg.constructor === Color) { type = arg._type; components = arg._components.slice(); alpha = arg._alpha; if (type === 'gradient') { for (var i = 1, l = components.length; i < l; i++) { var point = components[i]; if (point) components[i] = point.clone(); } } } else if (arg.constructor === Gradient) { type = 'gradient'; values = args; } else { type = 'hue' in arg ? 'lightness' in arg ? 'hsl' : 'hsb' : 'gradient' in arg || 'stops' in arg || 'radial' in arg ? 'gradient' : 'gray' in arg ? 'gray' : 'rgb'; var properties = types[type], parsers = componentParsers[type]; this._components = components = []; for (var i = 0, l = properties.length; i < l; i++) { var value = arg[properties[i]]; if (value == null && !i && type === 'gradient' && 'stops' in arg) { value = { stops: arg.stops, radial: arg.radial }; } value = parsers[i].call(this, value); if (value != null) components[i] = value; } alpha = arg.alpha; } } if (reading && type) read = 1; } this._type = type || 'rgb'; if (!components) { this._components = components = []; var parsers = componentParsers[this._type]; for (var i = 0, l = parsers.length; i < l; i++) { var value = parsers[i].call(this, values && values[i]); if (value != null) components[i] = value; } } this._components = components; this._properties = types[this._type]; this._alpha = alpha; if (reading) this.__read = read; return this; }, set: '#initialize', _serialize: function(options, dictionary) { var components = this.getComponents(); return Base.serialize( /^(gray|rgb)$/.test(this._type) ? components : [this._type].concat(components), options, true, dictionary); }, _changed: function() { this._canvasStyle = null; if (this._owner) { if (this._setter) { this._owner[this._setter](this); } else { this._owner._changed(129); } } }, _convert: function(type) { var converter; return this._type === type ? this._components.slice() : (converter = converters[this._type + '-' + type]) ? converter.apply(this, this._components) : converters['rgb-' + type].apply(this, converters[this._type + '-rgb'].apply(this, this._components)); }, convert: function(type) { return new Color(type, this._convert(type), this._alpha); }, getType: function() { return this._type; }, setType: function(type) { this._components = this._convert(type); this._properties = types[type]; this._type = type; }, getComponents: function() { var components = this._components.slice(); if (this._alpha != null) components.push(this._alpha); return components; }, getAlpha: function() { return this._alpha != null ? this._alpha : 1; }, setAlpha: function(alpha) { this._alpha = alpha == null ? null : Math.min(Math.max(alpha, 0), 1); this._changed(); }, hasAlpha: function() { return this._alpha != null; }, equals: function(color) { var col = Base.isPlainValue(color, true) ? Color.read(arguments) : color; return col === this || col && this._class === col._class && this._type === col._type && this.getAlpha() === col.getAlpha() && Base.equals(this._components, col._components) || false; }, toString: function() { var properties = this._properties, parts = [], isGradient = this._type === 'gradient', f = Formatter.instance; for (var i = 0, l = properties.length; i < l; i++) { var value = this._components[i]; if (value != null) parts.push(properties[i] + ': ' + (isGradient ? value : f.number(value))); } if (this._alpha != null) parts.push('alpha: ' + f.number(this._alpha)); return '{ ' + parts.join(', ') + ' }'; }, toCSS: function(hex) { var components = this._convert('rgb'), alpha = hex || this._alpha == null ? 1 : this._alpha; function convert(val) { return Math.round((val < 0 ? 0 : val > 1 ? 1 : val) * 255); } components = [ convert(components[0]), convert(components[1]), convert(components[2]) ]; if (alpha < 1) components.push(alpha < 0 ? 0 : alpha); return hex ? '#' + ((1 << 24) + (components[0] << 16) + (components[1] << 8) + components[2]).toString(16).slice(1) : (components.length == 4 ? 'rgba(' : 'rgb(') + components.join(',') + ')'; }, toCanvasStyle: function(ctx, matrix) { if (this._canvasStyle) return this._canvasStyle; if (this._type !== 'gradient') return this._canvasStyle = this.toCSS(); var components = this._components, gradient = components[0], stops = gradient._stops, origin = components[1], destination = components[2], highlight = components[3], inverse = matrix && matrix.inverted(), canvasGradient; if (inverse) { origin = inverse._transformPoint(origin); destination = inverse._transformPoint(destination); if (highlight) highlight = inverse._transformPoint(highlight); } if (gradient._radial) { var radius = destination.getDistance(origin); if (highlight) { var vector = highlight.subtract(origin); if (vector.getLength() > radius) highlight = origin.add(vector.normalize(radius - 0.1)); } var start = highlight || origin; canvasGradient = ctx.createRadialGradient(start.x, start.y, 0, origin.x, origin.y, radius); } else { canvasGradient = ctx.createLinearGradient(origin.x, origin.y, destination.x, destination.y); } for (var i = 0, l = stops.length; i < l; i++) { var stop = stops[i], offset = stop._offset; canvasGradient.addColorStop( offset == null ? i / (l - 1) : offset, stop._color.toCanvasStyle()); } return this._canvasStyle = canvasGradient; }, transform: function(matrix) { if (this._type === 'gradient') { var components = this._components; for (var i = 1, l = components.length; i < l; i++) { var point = components[i]; matrix._transformPoint(point, point, true); } this._changed(); } }, statics: { _types: types, random: function() { var random = Math.random; return new Color(random(), random(), random()); }, _setOwner: function(color, owner, setter) { if (color) { if (color._owner && owner && color._owner !== owner) { color = color.clone(); } if (!color._owner ^ !owner) { color._owner = owner || null; color._setter = setter || null; } } return color; } } }); }, new function() { var operators = { add: function(a, b) { return a + b; }, subtract: function(a, b) { return a - b; }, multiply: function(a, b) { return a * b; }, divide: function(a, b) { return a / b; } }; return Base.each(operators, function(operator, name) { this[name] = function(color) { color = Color.read(arguments); var type = this._type, components1 = this._components, components2 = color._convert(type); for (var i = 0, l = components1.length; i < l; i++) components2[i] = operator(components1[i], components2[i]); return new Color(type, components2, this._alpha != null ? operator(this._alpha, color.getAlpha()) : null); }; }, { }); }); var Gradient = Base.extend({ _class: 'Gradient', initialize: function Gradient(stops, radial) { this._id = UID.get(); if (stops && Base.isPlainObject(stops)) { this.set(stops); stops = radial = null; } if (this._stops == null) { this.setStops(stops || ['white', 'black']); } if (this._radial == null) { this.setRadial(typeof radial === 'string' && radial === 'radial' || radial || false); } }, _serialize: function(options, dictionary) { return dictionary.add(this, function() { return Base.serialize([this._stops, this._radial], options, true, dictionary); }); }, _changed: function() { for (var i = 0, l = this._owners && this._owners.length; i < l; i++) { this._owners[i]._changed(); } }, _addOwner: function(color) { if (!this._owners) this._owners = []; this._owners.push(color); }, _removeOwner: function(color) { var index = this._owners ? this._owners.indexOf(color) : -1; if (index != -1) { this._owners.splice(index, 1); if (!this._owners.length) this._owners = undefined; } }, clone: function() { var stops = []; for (var i = 0, l = this._stops.length; i < l; i++) { stops[i] = this._stops[i].clone(); } return new Gradient(stops, this._radial); }, getStops: function() { return this._stops; }, setStops: function(stops) { if (stops.length < 2) { throw new Error( 'Gradient stop list needs to contain at least two stops.'); } var _stops = this._stops; if (_stops) { for (var i = 0, l = _stops.length; i < l; i++) _stops[i]._owner = undefined; } _stops = this._stops = GradientStop.readList(stops, 0, { clone: true }); for (var i = 0, l = _stops.length; i < l; i++) _stops[i]._owner = this; this._changed(); }, getRadial: function() { return this._radial; }, setRadial: function(radial) { this._radial = radial; this._changed(); }, equals: function(gradient) { if (gradient === this) return true; if (gradient && this._class === gradient._class) { var stops1 = this._stops, stops2 = gradient._stops, length = stops1.length; if (length === stops2.length) { for (var i = 0; i < length; i++) { if (!stops1[i].equals(stops2[i])) return false; } return true; } } return false; } }); var GradientStop = Base.extend({ _class: 'GradientStop', initialize: function GradientStop(arg0, arg1) { var color = arg0, offset = arg1; if (typeof arg0 === 'object' && arg1 === undefined) { if (Array.isArray(arg0) && typeof arg0[0] !== 'number') { color = arg0[0]; offset = arg0[1]; } else if ('color' in arg0 || 'offset' in arg0 || 'rampPoint' in arg0) { color = arg0.color; offset = arg0.offset || arg0.rampPoint || 0; } } this.setColor(color); this.setOffset(offset); }, clone: function() { return new GradientStop(this._color.clone(), this._offset); }, _serialize: function(options, dictionary) { var color = this._color, offset = this._offset; return Base.serialize(offset == null ? [color] : [color, offset], options, true, dictionary); }, _changed: function() { if (this._owner) this._owner._changed(129); }, getOffset: function() { return this._offset; }, setOffset: function(offset) { this._offset = offset; this._changed(); }, getRampPoint: '#getOffset', setRampPoint: '#setOffset', getColor: function() { return this._color; }, setColor: function() { Color._setOwner(this._color, null); this._color = Color._setOwner(Color.read(arguments, 0), this, 'setColor'); this._changed(); }, equals: function(stop) { return stop === this || stop && this._class === stop._class && this._color.equals(stop._color) && this._offset == stop._offset || false; } }); var Style = Base.extend(new function() { var itemDefaults = { fillColor: null, fillRule: 'nonzero', strokeColor: null, strokeWidth: 1, strokeCap: 'butt', strokeJoin: 'miter', strokeScaling: true, miterLimit: 10, dashOffset: 0, dashArray: [], shadowColor: null, shadowBlur: 0, shadowOffset: new Point(), selectedColor: null }, groupDefaults = Base.set({}, itemDefaults, { fontFamily: 'sans-serif', fontWeight: 'normal', fontSize: 12, leading: null, justification: 'left' }), textDefaults = Base.set({}, groupDefaults, { fillColor: new Color() }), flags = { strokeWidth: 193, strokeCap: 193, strokeJoin: 193, strokeScaling: 201, miterLimit: 193, fontFamily: 9, fontWeight: 9, fontSize: 9, font: 9, leading: 9, justification: 9 }, item = { beans: true }, fields = { _class: 'Style', beans: true, initialize: function Style(style, _owner, _project) { this._values = {}; this._owner = _owner; this._project = _owner && _owner._project || _project || paper.project; this._defaults = !_owner || _owner instanceof Group ? groupDefaults : _owner instanceof TextItem ? textDefaults : itemDefaults; if (style) this.set(style); } }; Base.each(groupDefaults, function(value, key) { var isColor = /Color$/.test(key), isPoint = key === 'shadowOffset', part = Base.capitalize(key), flag = flags[key], set = 'set' + part, get = 'get' + part; fields[set] = function(value) { var owner = this._owner, children = owner && owner._children, applyToChildren = children && children.length > 0 && !(owner instanceof CompoundPath); if (applyToChildren) { for (var i = 0, l = children.length; i < l; i++) children[i]._style[set](value); } if ((key === 'selectedColor' || !applyToChildren) && key in this._defaults) { var old = this._values[key]; if (old !== value) { if (isColor) { if (old) { Color._setOwner(old, null); old._canvasStyle = null; } if (value && value.constructor === Color) { value = Color._setOwner(value, owner, applyToChildren && set); } } this._values[key] = value; if (owner) owner._changed(flag || 129); } } }; fields[get] = function(_dontMerge) { var owner = this._owner, children = owner && owner._children, applyToChildren = children && children.length > 0 && !(owner instanceof CompoundPath), value; if (applyToChildren && !_dontMerge) { for (var i = 0, l = children.length; i < l; i++) { var childValue = children[i]._style[get](); if (!i) { value = childValue; } else if (!Base.equals(value, childValue)) { return undefined; } } } else if (key in this._defaults) { var value = this._values[key]; if (value === undefined) { value = this._defaults[key]; if (value && value.clone) { value = value.clone(); } } else { var ctor = isColor ? Color : isPoint ? Point : null; if (ctor && !(value && value.constructor === ctor)) { this._values[key] = value = ctor.read([value], 0, { readNull: true, clone: true }); } } } if (value && isColor) { value = Color._setOwner(value, owner, applyToChildren && set); } return value; }; item[get] = function(_dontMerge) { return this._style[get](_dontMerge); }; item[set] = function(value) { this._style[set](value); }; }); Base.each({ Font: 'FontFamily', WindingRule: 'FillRule' }, function(value, key) { var get = 'get' + key, set = 'set' + key; fields[get] = item[get] = '#get' + value; fields[set] = item[set] = '#set' + value; }); Item.inject(item); return fields; }, { set: function(style) { var isStyle = style instanceof Style, values = isStyle ? style._values : style; if (values) { for (var key in values) { if (key in this._defaults) { var value = values[key]; this[key] = value && isStyle && value.clone ? value.clone() : value; } } } }, equals: function(style) { function compare(style1, style2, secondary) { var values1 = style1._values, values2 = style2._values, defaults2 = style2._defaults; for (var key in values1) { var value1 = values1[key], value2 = values2[key]; if (!(secondary && key in values2) && !Base.equals(value1, value2 === undefined ? defaults2[key] : value2)) return false; } return true; } return style === this || style && this._class === style._class && compare(this, style) && compare(style, this, true) || false; }, _dispose: function() { var color; color = this.getFillColor(); if (color) color._canvasStyle = null; color = this.getStrokeColor(); if (color) color._canvasStyle = null; color = this.getShadowColor(); if (color) color._canvasStyle = null; }, hasFill: function() { var color = this.getFillColor(); return !!color && color.alpha > 0; }, hasStroke: function() { var color = this.getStrokeColor(); return !!color && color.alpha > 0 && this.getStrokeWidth() > 0; }, hasShadow: function() { var color = this.getShadowColor(); return !!color && color.alpha > 0 && (this.getShadowBlur() > 0 || !this.getShadowOffset().isZero()); }, getView: function() { return this._project._view; }, getFontStyle: function() { var fontSize = this.getFontSize(); return this.getFontWeight() + ' ' + fontSize + (/[a-z]/i.test(fontSize + '') ? ' ' : 'px ') + this.getFontFamily(); }, getFont: '#getFontFamily', setFont: '#setFontFamily', getLeading: function getLeading() { var leading = getLeading.base.call(this), fontSize = this.getFontSize(); if (/pt|em|%|px/.test(fontSize)) fontSize = this.getView().getPixelSize(fontSize); return leading != null ? leading : fontSize * 1.2; } }); var DomElement = new function() { function handlePrefix(el, name, set, value) { var prefixes = ['', 'webkit', 'moz', 'Moz', 'ms', 'o'], suffix = name[0].toUpperCase() + name.substring(1); for (var i = 0; i < 6; i++) { var prefix = prefixes[i], key = prefix ? prefix + suffix : name; if (key in el) { if (set) { el[key] = value; } else { return el[key]; } break; } } } return { getStyles: function(el) { var doc = el && el.nodeType !== 9 ? el.ownerDocument : el, view = doc && doc.defaultView; return view && view.getComputedStyle(el, ''); }, getBounds: function(el, viewport) { var doc = el.ownerDocument, body = doc.body, html = doc.documentElement, rect; try { rect = el.getBoundingClientRect(); } catch (e) { rect = { left: 0, top: 0, width: 0, height: 0 }; } var x = rect.left - (html.clientLeft || body.clientLeft || 0), y = rect.top - (html.clientTop || body.clientTop || 0); if (!viewport) { var view = doc.defaultView; x += view.pageXOffset || html.scrollLeft || body.scrollLeft; y += view.pageYOffset || html.scrollTop || body.scrollTop; } return new Rectangle(x, y, rect.width, rect.height); }, getViewportBounds: function(el) { var doc = el.ownerDocument, view = doc.defaultView, html = doc.documentElement; return new Rectangle(0, 0, view.innerWidth || html.clientWidth, view.innerHeight || html.clientHeight ); }, getOffset: function(el, viewport) { return DomElement.getBounds(el, viewport).getPoint(); }, getSize: function(el) { return DomElement.getBounds(el, true).getSize(); }, isInvisible: function(el) { return DomElement.getSize(el).equals(new Size(0, 0)); }, isInView: function(el) { return !DomElement.isInvisible(el) && DomElement.getViewportBounds(el).intersects( DomElement.getBounds(el, true)); }, isInserted: function(el) { return document.body.contains(el); }, getPrefixed: function(el, name) { return el && handlePrefix(el, name); }, setPrefixed: function(el, name, value) { if (typeof name === 'object') { for (var key in name) handlePrefix(el, key, true, name[key]); } else { handlePrefix(el, name, true, value); } } }; }; var DomEvent = { add: function(el, events) { if (el) { for (var type in events) { var func = events[type], parts = type.split(/[\s,]+/g); for (var i = 0, l = parts.length; i < l; i++) { var name = parts[i]; var options = ( el === document && (name === 'touchstart' || name === 'touchmove') ) ? { passive: false } : false; el.addEventListener(name, func, options); } } } }, remove: function(el, events) { if (el) { for (var type in events) { var func = events[type], parts = type.split(/[\s,]+/g); for (var i = 0, l = parts.length; i < l; i++) el.removeEventListener(parts[i], func, false); } } }, getPoint: function(event) { var pos = event.targetTouches ? event.targetTouches.length ? event.targetTouches[0] : event.changedTouches[0] : event; return new Point( pos.pageX || pos.clientX + document.documentElement.scrollLeft, pos.pageY || pos.clientY + document.documentElement.scrollTop ); }, getTarget: function(event) { return event.target || event.srcElement; }, getRelatedTarget: function(event) { return event.relatedTarget || event.toElement; }, getOffset: function(event, target) { return DomEvent.getPoint(event).subtract(DomElement.getOffset( target || DomEvent.getTarget(event))); } }; DomEvent.requestAnimationFrame = new function() { var nativeRequest = DomElement.getPrefixed(window, 'requestAnimationFrame'), requested = false, callbacks = [], timer; function handleCallbacks() { var functions = callbacks; callbacks = []; for (var i = 0, l = functions.length; i < l; i++) functions[i](); requested = nativeRequest && callbacks.length; if (requested) nativeRequest(handleCallbacks); } return function(callback) { callbacks.push(callback); if (nativeRequest) { if (!requested) { nativeRequest(handleCallbacks); requested = true; } } else if (!timer) { timer = setInterval(handleCallbacks, 1000 / 60); } }; }; var View = Base.extend(Emitter, { _class: 'View', initialize: function View(project, element) { function getSize(name) { return element[name] || parseInt(element.getAttribute(name), 10); } function getCanvasSize() { var size = DomElement.getSize(element); return size.isNaN() || size.isZero() ? new Size(getSize('width'), getSize('height')) : size; } var size; if (window && element) { this._id = element.getAttribute('id'); if (this._id == null) element.setAttribute('id', this._id = 'paper-view-' + View._id++); DomEvent.add(element, this._viewEvents); var none = 'none'; DomElement.setPrefixed(element.style, { userDrag: none, userSelect: none, touchCallout: none, contentZooming: none, tapHighlightColor: 'rgba(0,0,0,0)' }); if (PaperScope.hasAttribute(element, 'resize')) { var that = this; DomEvent.add(window, this._windowEvents = { resize: function() { that.setViewSize(getCanvasSize()); } }); } size = getCanvasSize(); if (PaperScope.hasAttribute(element, 'stats') && typeof Stats !== 'undefined') { this._stats = new Stats(); var stats = this._stats.domElement, style = stats.style, offset = DomElement.getOffset(element); style.position = 'absolute'; style.left = offset.x + 'px'; style.top = offset.y + 'px'; document.body.appendChild(stats); } } else { size = new Size(element); element = null; } this._project = project; this._scope = project._scope; this._element = element; if (!this._pixelRatio) this._pixelRatio = window && window.devicePixelRatio || 1; this._setElementSize(size.width, size.height); this._viewSize = size; View._views.push(this); View._viewsById[this._id] = this; (this._matrix = new Matrix())._owner = this; if (!View._focused) View._focused = this; this._frameItems = {}; this._frameItemCount = 0; this._itemEvents = { native: {}, virtual: {} }; this._autoUpdate = !paper.agent.node; this._needsUpdate = false; }, remove: function() { if (!this._project) return false; if (View._focused === this) View._focused = null; View._views.splice(View._views.indexOf(this), 1); delete View._viewsById[this._id]; var project = this._project; if (project._view === this) project._view = null; DomEvent.remove(this._element, this._viewEvents); DomEvent.remove(window, this._windowEvents); this._element = this._project = null; this.off('frame'); this._animate = false; this._frameItems = {}; return true; }, _events: Base.each( Item._itemHandlers.concat(['onResize', 'onKeyDown', 'onKeyUp']), function(name) { this[name] = {}; }, { onFrame: { install: function() { this.play(); }, uninstall: function() { this.pause(); } } } ), _animate: false, _time: 0, _count: 0, getAutoUpdate: function() { return this._autoUpdate; }, setAutoUpdate: function(autoUpdate) { this._autoUpdate = autoUpdate; if (autoUpdate) this.requestUpdate(); }, update: function() { }, draw: function() { this.update(); }, requestUpdate: function() { if (!this._requested) { var that = this; DomEvent.requestAnimationFrame(function() { that._requested = false; if (that._animate) { that.requestUpdate(); var element = that._element; if ((!DomElement.getPrefixed(document, 'hidden') || PaperScope.getAttribute(element, 'keepalive') === 'true') && DomElement.isInView(element)) { that._handleFrame(); } } if (that._autoUpdate) that.update(); }); this._requested = true; } }, play: function() { this._animate = true; this.requestUpdate(); }, pause: function() { this._animate = false; }, _handleFrame: function() { paper = this._scope; var now = Date.now() / 1000, delta = this._last ? now - this._last : 0; this._last = now; this.emit('frame', new Base({ delta: delta, time: this._time += delta, count: this._count++ })); if (this._stats) this._stats.update(); }, _animateItem: function(item, animate) { var items = this._frameItems; if (animate) { items[item._id] = { item: item, time: 0, count: 0 }; if (++this._frameItemCount === 1) this.on('frame', this._handleFrameItems); } else { delete items[item._id]; if (--this._frameItemCount === 0) { this.off('frame', this._handleFrameItems); } } }, _handleFrameItems: function(event) { for (var i in this._frameItems) { var entry = this._frameItems[i]; entry.item.emit('frame', new Base(event, { time: entry.time += event.delta, count: entry.count++ })); } }, _changed: function() { this._project._changed(4097); this._bounds = this._decomposed = undefined; }, getElement: function() { return this._element; }, getPixelRatio: function() { return this._pixelRatio; }, getResolution: function() { return this._pixelRatio * 72; }, getViewSize: function() { var size = this._viewSize; return new LinkedSize(size.width, size.height, this, 'setViewSize'); }, setViewSize: function() { var size = Size.read(arguments), delta = size.subtract(this._viewSize); if (delta.isZero()) return; this._setElementSize(size.width, size.height); this._viewSize.set(size); this._changed(); this.emit('resize', { size: size, delta: delta }); if (this._autoUpdate) { this.update(); } }, _setElementSize: function(width, height) { var element = this._element; if (element) { if (element.width !== width) element.width = width; if (element.height !== height) element.height = height; } }, getBounds: function() { if (!this._bounds) this._bounds = this._matrix.inverted()._transformBounds( new Rectangle(new Point(), this._viewSize)); return this._bounds; }, getSize: function() { return this.getBounds().getSize(); }, isVisible: function() { return DomElement.isInView(this._element); }, isInserted: function() { return DomElement.isInserted(this._element); }, getPixelSize: function(size) { var element = this._element, pixels; if (element) { var parent = element.parentNode, temp = document.createElement('div'); temp.style.fontSize = size; parent.appendChild(temp); pixels = parseFloat(DomElement.getStyles(temp).fontSize); parent.removeChild(temp); } else { pixels = parseFloat(pixels); } return pixels; }, getTextWidth: function(font, lines) { return 0; } }, Base.each(['rotate', 'scale', 'shear', 'skew'], function(key) { var rotate = key === 'rotate'; this[key] = function() { var args = arguments, value = (rotate ? Base : Point).read(args), center = Point.read(args, 0, { readNull: true }); return this.transform(new Matrix()[key](value, center || this.getCenter(true))); }; }, { _decompose: function() { return this._decomposed || (this._decomposed = this._matrix.decompose()); }, translate: function() { var mx = new Matrix(); return this.transform(mx.translate.apply(mx, arguments)); }, getCenter: function() { return this.getBounds().getCenter(); }, setCenter: function() { var center = Point.read(arguments); this.translate(this.getCenter().subtract(center)); }, getZoom: function() { var scaling = this._decompose().scaling; return (scaling.x + scaling.y) / 2; }, setZoom: function(zoom) { this.transform(new Matrix().scale(zoom / this.getZoom(), this.getCenter())); }, getRotation: function() { return this._decompose().rotation; }, setRotation: function(rotation) { var current = this.getRotation(); if (current != null && rotation != null) { this.rotate(rotation - current); } }, getScaling: function() { var scaling = this._decompose().scaling; return new LinkedPoint(scaling.x, scaling.y, this, 'setScaling'); }, setScaling: function() { var current = this.getScaling(), scaling = Point.read(arguments, 0, { clone: true, readNull: true }); if (current && scaling) { this.scale(scaling.x / current.x, scaling.y / current.y); } }, getMatrix: function() { return this._matrix; }, setMatrix: function() { var matrix = this._matrix; matrix.set.apply(matrix, arguments); }, transform: function(matrix) { this._matrix.append(matrix); }, scrollBy: function() { this.translate(Point.read(arguments).negate()); } }), { projectToView: function() { return this._matrix._transformPoint(Point.read(arguments)); }, viewToProject: function() { return this._matrix._inverseTransform(Point.read(arguments)); }, getEventPoint: function(event) { return this.viewToProject(DomEvent.getOffset(event, this._element)); }, }, { statics: { _views: [], _viewsById: {}, _id: 0, create: function(project, element) { if (document && typeof element === 'string') element = document.getElementById(element); var ctor = window ? CanvasView : View; return new ctor(project, element); } } }, new function() { if (!window) return; var prevFocus, tempFocus, dragging = false, mouseDown = false; function getView(event) { var target = DomEvent.getTarget(event); return target.getAttribute && View._viewsById[ target.getAttribute('id')]; } function updateFocus() { var view = View._focused; if (!view || !view.isVisible()) { for (var i = 0, l = View._views.length; i < l; i++) { if ((view = View._views[i]).isVisible()) { View._focused = tempFocus = view; break; } } } } function handleMouseMove(view, event, point) { view._handleMouseEvent('mousemove', event, point); } var navigator = window.navigator, mousedown, mousemove, mouseup; if (navigator.pointerEnabled || navigator.msPointerEnabled) { mousedown = 'pointerdown MSPointerDown'; mousemove = 'pointermove MSPointerMove'; mouseup = 'pointerup pointercancel MSPointerUp MSPointerCancel'; } else { mousedown = 'touchstart'; mousemove = 'touchmove'; mouseup = 'touchend touchcancel'; if (!('ontouchstart' in window && navigator.userAgent.match( /mobile|tablet|ip(ad|hone|od)|android|silk/i))) { mousedown += ' mousedown'; mousemove += ' mousemove'; mouseup += ' mouseup'; } } var viewEvents = {}, docEvents = { mouseout: function(event) { var view = View._focused, target = DomEvent.getRelatedTarget(event); if (view && (!target || target.nodeName === 'HTML')) { var offset = DomEvent.getOffset(event, view._element), x = offset.x, abs = Math.abs, ax = abs(x), max = 1 << 25, diff = ax - max; offset.x = abs(diff) < ax ? diff * (x < 0 ? -1 : 1) : x; handleMouseMove(view, event, view.viewToProject(offset)); } }, scroll: updateFocus }; viewEvents[mousedown] = function(event) { var view = View._focused = getView(event); if (!dragging) { dragging = true; view._handleMouseEvent('mousedown', event); } }; docEvents[mousemove] = function(event) { var view = View._focused; if (!mouseDown) { var target = getView(event); if (target) { if (view !== target) { if (view) handleMouseMove(view, event); if (!prevFocus) prevFocus = view; view = View._focused = tempFocus = target; } } else if (tempFocus && tempFocus === view) { if (prevFocus && !prevFocus.isInserted()) prevFocus = null; view = View._focused = prevFocus; prevFocus = null; updateFocus(); } } if (view) handleMouseMove(view, event); }; docEvents[mousedown] = function() { mouseDown = true; }; docEvents[mouseup] = function(event) { var view = View._focused; if (view && dragging) view._handleMouseEvent('mouseup', event); mouseDown = dragging = false; }; DomEvent.add(document, docEvents); DomEvent.add(window, { load: updateFocus }); var called = false, prevented = false, fallbacks = { doubleclick: 'click', mousedrag: 'mousemove' }, wasInView = false, overView, downPoint, lastPoint, downItem, overItem, dragItem, clickItem, clickTime, dblClick; function emitMouseEvent(obj, target, type, event, point, prevPoint, stopItem) { var stopped = false, mouseEvent; function emit(obj, type) { if (obj.responds(type)) { if (!mouseEvent) { mouseEvent = new MouseEvent(type, event, point, target || obj, prevPoint ? point.subtract(prevPoint) : null); } if (obj.emit(type, mouseEvent)) { called = true; if (mouseEvent.prevented) prevented = true; if (mouseEvent.stopped) return stopped = true; } } else { var fallback = fallbacks[type]; if (fallback) return emit(obj, fallback); } } while (obj && obj !== stopItem) { if (emit(obj, type)) break; obj = obj._parent; } return stopped; } function emitMouseEvents(view, hitItem, type, event, point, prevPoint) { view._project.removeOn(type); prevented = called = false; return (dragItem && emitMouseEvent(dragItem, null, type, event, point, prevPoint) || hitItem && hitItem !== dragItem && !hitItem.isDescendant(dragItem) && emitMouseEvent(hitItem, null, type === 'mousedrag' ? 'mousemove' : type, event, point, prevPoint, dragItem) || emitMouseEvent(view, dragItem || hitItem || view, type, event, point, prevPoint)); } var itemEventsMap = { mousedown: { mousedown: 1, mousedrag: 1, click: 1, doubleclick: 1 }, mouseup: { mouseup: 1, mousedrag: 1, click: 1, doubleclick: 1 }, mousemove: { mousedrag: 1, mousemove: 1, mouseenter: 1, mouseleave: 1 } }; return { _viewEvents: viewEvents, _handleMouseEvent: function(type, event, point) { var itemEvents = this._itemEvents, hitItems = itemEvents.native[type], nativeMove = type === 'mousemove', tool = this._scope.tool, view = this; function responds(type) { return itemEvents.virtual[type] || view.responds(type) || tool && tool.responds(type); } if (nativeMove && dragging && responds('mousedrag')) type = 'mousedrag'; if (!point) point = this.getEventPoint(event); var inView = this.getBounds().contains(point), hit = hitItems && inView && view._project.hitTest(point, { tolerance: 0, fill: true, stroke: true }), hitItem = hit && hit.item || null, handle = false, mouse = {}; mouse[type.substr(5)] = true; if (hitItems && hitItem !== overItem) { if (overItem) { emitMouseEvent(overItem, null, 'mouseleave', event, point); } if (hitItem) { emitMouseEvent(hitItem, null, 'mouseenter', event, point); } overItem = hitItem; } if (wasInView ^ inView) { emitMouseEvent(this, null, inView ? 'mouseenter' : 'mouseleave', event, point); overView = inView ? this : null; handle = true; } if ((inView || mouse.drag) && !point.equals(lastPoint)) { emitMouseEvents(this, hitItem, nativeMove ? type : 'mousemove', event, point, lastPoint); handle = true; } wasInView = inView; if (mouse.down && inView || mouse.up && downPoint) { emitMouseEvents(this, hitItem, type, event, point, downPoint); if (mouse.down) { dblClick = hitItem === clickItem && (Date.now() - clickTime < 300); downItem = clickItem = hitItem; if (!prevented && hitItem) { var item = hitItem; while (item && !item.responds('mousedrag')) item = item._parent; if (item) dragItem = hitItem; } downPoint = point; } else if (mouse.up) { if (!prevented && hitItem === downItem) { clickTime = Date.now(); emitMouseEvents(this, hitItem, dblClick ? 'doubleclick' : 'click', event, point, downPoint); dblClick = false; } downItem = dragItem = null; } wasInView = false; handle = true; } lastPoint = point; if (handle && tool) { called = tool._handleMouseEvent(type, event, point, mouse) || called; } if ( event.cancelable !== false && (called && !mouse.move || mouse.down && responds('mouseup')) ) { event.preventDefault(); } }, _handleKeyEvent: function(type, event, key, character) { var scope = this._scope, tool = scope.tool, keyEvent; function emit(obj) { if (obj.responds(type)) { paper = scope; obj.emit(type, keyEvent = keyEvent || new KeyEvent(type, event, key, character)); } } if (this.isVisible()) { emit(this); if (tool && tool.responds(type)) emit(tool); } }, _countItemEvent: function(type, sign) { var itemEvents = this._itemEvents, native = itemEvents.native, virtual = itemEvents.virtual; for (var key in itemEventsMap) { native[key] = (native[key] || 0) + (itemEventsMap[key][type] || 0) * sign; } virtual[type] = (virtual[type] || 0) + sign; }, statics: { updateFocus: updateFocus, _resetState: function() { dragging = mouseDown = called = wasInView = false; prevFocus = tempFocus = overView = downPoint = lastPoint = downItem = overItem = dragItem = clickItem = clickTime = dblClick = null; } } }; }); var CanvasView = View.extend({ _class: 'CanvasView', initialize: function CanvasView(project, canvas) { if (!(canvas instanceof window.HTMLCanvasElement)) { var size = Size.read(arguments, 1); if (size.isZero()) throw new Error( 'Cannot create CanvasView with the provided argument: ' + Base.slice(arguments, 1)); canvas = CanvasProvider.getCanvas(size); } var ctx = this._context = canvas.getContext('2d'); ctx.save(); this._pixelRatio = 1; if (!/^off|false$/.test(PaperScope.getAttribute(canvas, 'hidpi'))) { var deviceRatio = window.devicePixelRatio || 1, backingStoreRatio = DomElement.getPrefixed(ctx, 'backingStorePixelRatio') || 1; this._pixelRatio = deviceRatio / backingStoreRatio; } View.call(this, project, canvas); this._needsUpdate = true; }, remove: function remove() { this._context.restore(); return remove.base.call(this); }, _setElementSize: function _setElementSize(width, height) { var pixelRatio = this._pixelRatio; _setElementSize.base.call(this, width * pixelRatio, height * pixelRatio); if (pixelRatio !== 1) { var element = this._element, ctx = this._context; if (!PaperScope.hasAttribute(element, 'resize')) { var style = element.style; style.width = width + 'px'; style.height = height + 'px'; } ctx.restore(); ctx.save(); ctx.scale(pixelRatio, pixelRatio); } }, getContext: function() { return this._context; }, getPixelSize: function getPixelSize(size) { var agent = paper.agent, pixels; if (agent && agent.firefox) { pixels = getPixelSize.base.call(this, size); } else { var ctx = this._context, prevFont = ctx.font; ctx.font = size + ' serif'; pixels = parseFloat(ctx.font); ctx.font = prevFont; } return pixels; }, getTextWidth: function(font, lines) { var ctx = this._context, prevFont = ctx.font, width = 0; ctx.font = font; for (var i = 0, l = lines.length; i < l; i++) width = Math.max(width, ctx.measureText(lines[i]).width); ctx.font = prevFont; return width; }, update: function() { if (!this._needsUpdate) return false; var project = this._project, ctx = this._context, size = this._viewSize; ctx.clearRect(0, 0, size.width + 1, size.height + 1); if (project) project.draw(ctx, this._matrix, this._pixelRatio); this._needsUpdate = false; return true; } }); var Event = Base.extend({ _class: 'Event', initialize: function Event(event) { this.event = event; this.type = event && event.type; }, prevented: false, stopped: false, preventDefault: function() { this.prevented = true; this.event.preventDefault(); }, stopPropagation: function() { this.stopped = true; this.event.stopPropagation(); }, stop: function() { this.stopPropagation(); this.preventDefault(); }, getTimeStamp: function() { return this.event.timeStamp; }, getModifiers: function() { return Key.modifiers; } }); var KeyEvent = Event.extend({ _class: 'KeyEvent', initialize: function KeyEvent(type, event, key, character) { this.type = type; this.event = event; this.key = key; this.character = character; }, toString: function() { return "{ type: '" + this.type + "', key: '" + this.key + "', character: '" + this.character + "', modifiers: " + this.getModifiers() + " }"; } }); var Key = new function() { var keyLookup = { '\t': 'tab', ' ': 'space', '\b': 'backspace', '\x7f': 'delete', 'Spacebar': 'space', 'Del': 'delete', 'Win': 'meta', 'Esc': 'escape' }, charLookup = { 'tab': '\t', 'space': ' ', 'enter': '\r' }, keyMap = {}, charMap = {}, metaFixMap, downKey, modifiers = new Base({ shift: false, control: false, alt: false, meta: false, capsLock: false, space: false }).inject({ option: { get: function() { return this.alt; } }, command: { get: function() { var agent = paper && paper.agent; return agent && agent.mac ? this.meta : this.control; } } }); function getKey(event) { var key = event.key || event.keyIdentifier; key = /^U\+/.test(key) ? String.fromCharCode(parseInt(key.substr(2), 16)) : /^Arrow[A-Z]/.test(key) ? key.substr(5) : key === 'Unidentified' || key === undefined ? String.fromCharCode(event.keyCode) : key; return keyLookup[key] || (key.length > 1 ? Base.hyphenate(key) : key.toLowerCase()); } function handleKey(down, key, character, event) { var type = down ? 'keydown' : 'keyup', view = View._focused, name; keyMap[key] = down; if (down) { charMap[key] = character; } else { delete charMap[key]; } if (key.length > 1 && (name = Base.camelize(key)) in modifiers) { modifiers[name] = down; var agent = paper && paper.agent; if (name === 'meta' && agent && agent.mac) { if (down) { metaFixMap = {}; } else { for (var k in metaFixMap) { if (k in charMap) handleKey(false, k, metaFixMap[k], event); } metaFixMap = null; } } } else if (down && metaFixMap) { metaFixMap[key] = character; } if (view) { view._handleKeyEvent(down ? 'keydown' : 'keyup', event, key, character); } } DomEvent.add(document, { keydown: function(event) { var key = getKey(event), agent = paper && paper.agent; if (key.length > 1 || agent && (agent.chrome && (event.altKey || agent.mac && event.metaKey || !agent.mac && event.ctrlKey))) { handleKey(true, key, charLookup[key] || (key.length > 1 ? '' : key), event); } else { downKey = key; } }, keypress: function(event) { if (downKey) { var key = getKey(event), code = event.charCode, character = code >= 32 ? String.fromCharCode(code) : key.length > 1 ? '' : key; if (key !== downKey) { key = character.toLowerCase(); } handleKey(true, key, character, event); downKey = null; } }, keyup: function(event) { var key = getKey(event); if (key in charMap) handleKey(false, key, charMap[key], event); } }); DomEvent.add(window, { blur: function(event) { for (var key in charMap) handleKey(false, key, charMap[key], event); } }); return { modifiers: modifiers, isDown: function(key) { return !!keyMap[key]; } }; }; var MouseEvent = Event.extend({ _class: 'MouseEvent', initialize: function MouseEvent(type, event, point, target, delta) { this.type = type; this.event = event; this.point = point; this.target = target; this.delta = delta; }, toString: function() { return "{ type: '" + this.type + "', point: " + this.point + ', target: ' + this.target + (this.delta ? ', delta: ' + this.delta : '') + ', modifiers: ' + this.getModifiers() + ' }'; } }); var ToolEvent = Event.extend({ _class: 'ToolEvent', _item: null, initialize: function ToolEvent(tool, type, event) { this.tool = tool; this.type = type; this.event = event; }, _choosePoint: function(point, toolPoint) { return point ? point : toolPoint ? toolPoint.clone() : null; }, getPoint: function() { return this._choosePoint(this._point, this.tool._point); }, setPoint: function(point) { this._point = point; }, getLastPoint: function() { return this._choosePoint(this._lastPoint, this.tool._lastPoint); }, setLastPoint: function(lastPoint) { this._lastPoint = lastPoint; }, getDownPoint: function() { return this._choosePoint(this._downPoint, this.tool._downPoint); }, setDownPoint: function(downPoint) { this._downPoint = downPoint; }, getMiddlePoint: function() { if (!this._middlePoint && this.tool._lastPoint) { return this.tool._point.add(this.tool._lastPoint).divide(2); } return this._middlePoint; }, setMiddlePoint: function(middlePoint) { this._middlePoint = middlePoint; }, getDelta: function() { return !this._delta && this.tool._lastPoint ? this.tool._point.subtract(this.tool._lastPoint) : this._delta; }, setDelta: function(delta) { this._delta = delta; }, getCount: function() { return this.tool[/^mouse(down|up)$/.test(this.type) ? '_downCount' : '_moveCount']; }, setCount: function(count) { this.tool[/^mouse(down|up)$/.test(this.type) ? 'downCount' : 'count'] = count; }, getItem: function() { if (!this._item) { var result = this.tool._scope.project.hitTest(this.getPoint()); if (result) { var item = result.item, parent = item._parent; while (/^(Group|CompoundPath)$/.test(parent._class)) { item = parent; parent = parent._parent; } this._item = item; } } return this._item; }, setItem: function(item) { this._item = item; }, toString: function() { return '{ type: ' + this.type + ', point: ' + this.getPoint() + ', count: ' + this.getCount() + ', modifiers: ' + this.getModifiers() + ' }'; } }); var Tool = PaperScopeItem.extend({ _class: 'Tool', _list: 'tools', _reference: 'tool', _events: ['onMouseDown', 'onMouseUp', 'onMouseDrag', 'onMouseMove', 'onActivate', 'onDeactivate', 'onEditOptions', 'onKeyDown', 'onKeyUp'], initialize: function Tool(props) { PaperScopeItem.call(this); this._moveCount = -1; this._downCount = -1; this.set(props); }, getMinDistance: function() { return this._minDistance; }, setMinDistance: function(minDistance) { this._minDistance = minDistance; if (minDistance != null && this._maxDistance != null && minDistance > this._maxDistance) { this._maxDistance = minDistance; } }, getMaxDistance: function() { return this._maxDistance; }, setMaxDistance: function(maxDistance) { this._maxDistance = maxDistance; if (this._minDistance != null && maxDistance != null && maxDistance < this._minDistance) { this._minDistance = maxDistance; } }, getFixedDistance: function() { return this._minDistance == this._maxDistance ? this._minDistance : null; }, setFixedDistance: function(distance) { this._minDistance = this._maxDistance = distance; }, _handleMouseEvent: function(type, event, point, mouse) { paper = this._scope; if (mouse.drag && !this.responds(type)) type = 'mousemove'; var move = mouse.move || mouse.drag, responds = this.responds(type), minDistance = this.minDistance, maxDistance = this.maxDistance, called = false, tool = this; function update(minDistance, maxDistance) { var pt = point, toolPoint = move ? tool._point : (tool._downPoint || pt); if (move) { if (tool._moveCount >= 0 && pt.equals(toolPoint)) { return false; } if (toolPoint && (minDistance != null || maxDistance != null)) { var vector = pt.subtract(toolPoint), distance = vector.getLength(); if (distance < (minDistance || 0)) return false; if (maxDistance) { pt = toolPoint.add(vector.normalize( Math.min(distance, maxDistance))); } } tool._moveCount++; } tool._point = pt; tool._lastPoint = toolPoint || pt; if (mouse.down) { tool._moveCount = -1; tool._downPoint = pt; tool._downCount++; } return true; } function emit() { if (responds) { called = tool.emit(type, new ToolEvent(tool, type, event)) || called; } } if (mouse.down) { update(); emit(); } else if (mouse.up) { update(null, maxDistance); emit(); } else if (responds) { while (update(minDistance, maxDistance)) emit(); } return called; } }); var Tween = Base.extend(Emitter, { _class: 'Tween', statics: { easings: new Base({ linear: function(t) { return t; }, easeInQuad: function(t) { return t * t; }, easeOutQuad: function(t) { return t * (2 - t); }, easeInOutQuad: function(t) { return t < 0.5 ? 2 * t * t : -1 + 2 * (2 - t) * t; }, easeInCubic: function(t) { return t * t * t; }, easeOutCubic: function(t) { return --t * t * t + 1; }, easeInOutCubic: function(t) { return t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1; }, easeInQuart: function(t) { return t * t * t * t; }, easeOutQuart: function(t) { return 1 - (--t) * t * t * t; }, easeInOutQuart: function(t) { return t < 0.5 ? 8 * t * t * t * t : 1 - 8 * (--t) * t * t * t; }, easeInQuint: function(t) { return t * t * t * t * t; }, easeOutQuint: function(t) { return 1 + --t * t * t * t * t; }, easeInOutQuint: function(t) { return t < 0.5 ? 16 * t * t * t * t * t : 1 + 16 * (--t) * t * t * t * t; } }) }, initialize: function Tween(object, from, to, duration, easing, start) { this.object = object; var type = typeof easing; var isFunction = type === 'function'; this.type = isFunction ? type : type === 'string' ? easing : 'linear'; this.easing = isFunction ? easing : Tween.easings[this.type]; this.duration = duration; this.running = false; this._then = null; this._startTime = null; var state = from || to; this._keys = state ? Object.keys(state) : []; this._parsedKeys = this._parseKeys(this._keys); this._from = state && this._getState(from); this._to = state && this._getState(to); if (start !== false) { this.start(); } }, then: function(then) { this._then = then; return this; }, start: function() { this._startTime = null; this.running = true; return this; }, stop: function() { this.running = false; return this; }, update: function(progress) { if (this.running) { if (progress >= 1) { progress = 1; this.running = false; } var factor = this.easing(progress), keys = this._keys, getValue = function(value) { return typeof value === 'function' ? value(factor, progress) : value; }; for (var i = 0, l = keys && keys.length; i < l; i++) { var key = keys[i], from = getValue(this._from[key]), to = getValue(this._to[key]), value = (from && to && from.__add && to.__add) ? to.__subtract(from).__multiply(factor).__add(from) : ((to - from) * factor) + from; this._setProperty(this._parsedKeys[key], value); } if (this.responds('update')) { this.emit('update', new Base({ progress: progress, factor: factor })); } if (!this.running && this._then) { this._then(this.object); } } return this; }, _events: { onUpdate: {} }, _handleFrame: function(time) { var startTime = this._startTime, progress = startTime ? (time - startTime) / this.duration : 0; if (!startTime) { this._startTime = time; } this.update(progress); }, _getState: function(state) { var keys = this._keys, result = {}; for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i], path = this._parsedKeys[key], current = this._getProperty(path), value; if (state) { var resolved = this._resolveValue(current, state[key]); this._setProperty(path, resolved); value = this._getProperty(path); value = value && value.clone ? value.clone() : value; this._setProperty(path, current); } else { value = current && current.clone ? current.clone() : current; } result[key] = value; } return result; }, _resolveValue: function(current, value) { if (value) { if (Array.isArray(value) && value.length === 2) { var operator = value[0]; return ( operator && operator.match && operator.match(/^[+\-\*\/]=/) ) ? this._calculate(current, operator[0], value[1]) : value; } else if (typeof value === 'string') { var match = value.match(/^[+\-*/]=(.*)/); if (match) { var parsed = JSON.parse(match[1].replace( /(['"])?([a-zA-Z0-9_]+)(['"])?:/g, '"$2": ' )); return this._calculate(current, value[0], parsed); } } } return value; }, _calculate: function(left, operator, right) { return paper.PaperScript.calculateBinary(left, operator, right); }, _parseKeys: function(keys) { var parsed = {}; for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i], path = key .replace(/\.([^.]*)/g, '/$1') .replace(/\[['"]?([^'"\]]*)['"]?\]/g, '/$1'); parsed[key] = path.split('/'); } return parsed; }, _getProperty: function(path, offset) { var obj = this.object; for (var i = 0, l = path.length - (offset || 0); i < l && obj; i++) { obj = obj[path[i]]; } return obj; }, _setProperty: function(path, value) { var dest = this._getProperty(path, 1); if (dest) { dest[path[path.length - 1]] = value; } } }); var Http = { request: function(options) { var xhr = new self.XMLHttpRequest(); xhr.open((options.method || 'get').toUpperCase(), options.url, Base.pick(options.async, true)); if (options.mimeType) xhr.overrideMimeType(options.mimeType); xhr.onload = function() { var status = xhr.status; if (status === 0 || status === 200) { if (options.onLoad) { options.onLoad.call(xhr, xhr.responseText); } } else { xhr.onerror(); } }; xhr.onerror = function() { var status = xhr.status, message = 'Could not load "' + options.url + '" (Status: ' + status + ')'; if (options.onError) { options.onError(message, status); } else { throw new Error(message); } }; return xhr.send(null); } }; var CanvasProvider = Base.exports.CanvasProvider = { canvases: [], getCanvas: function(width, height) { if (!window) return null; var canvas, clear = true; if (typeof width === 'object') { height = width.height; width = width.width; } if (this.canvases.length) { canvas = this.canvases.pop(); } else { canvas = document.createElement('canvas'); clear = false; } var ctx = canvas.getContext('2d'); if (!ctx) { throw new Error('Canvas ' + canvas + ' is unable to provide a 2D context.'); } if (canvas.width === width && canvas.height === height) { if (clear) ctx.clearRect(0, 0, width + 1, height + 1); } else { canvas.width = width; canvas.height = height; } ctx.save(); return canvas; }, getContext: function(width, height) { var canvas = this.getCanvas(width, height); return canvas ? canvas.getContext('2d') : null; }, release: function(obj) { var canvas = obj && obj.canvas ? obj.canvas : obj; if (canvas && canvas.getContext) { canvas.getContext('2d').restore(); this.canvases.push(canvas); } } }; var BlendMode = new function() { var min = Math.min, max = Math.max, abs = Math.abs, sr, sg, sb, sa, br, bg, bb, ba, dr, dg, db; function getLum(r, g, b) { return 0.2989 * r + 0.587 * g + 0.114 * b; } function setLum(r, g, b, l) { var d = l - getLum(r, g, b); dr = r + d; dg = g + d; db = b + d; var l = getLum(dr, dg, db), mn = min(dr, dg, db), mx = max(dr, dg, db); if (mn < 0) { var lmn = l - mn; dr = l + (dr - l) * l / lmn; dg = l + (dg - l) * l / lmn; db = l + (db - l) * l / lmn; } if (mx > 255) { var ln = 255 - l, mxl = mx - l; dr = l + (dr - l) * ln / mxl; dg = l + (dg - l) * ln / mxl; db = l + (db - l) * ln / mxl; } } function getSat(r, g, b) { return max(r, g, b) - min(r, g, b); } function setSat(r, g, b, s) { var col = [r, g, b], mx = max(r, g, b), mn = min(r, g, b), md; mn = mn === r ? 0 : mn === g ? 1 : 2; mx = mx === r ? 0 : mx === g ? 1 : 2; md = min(mn, mx) === 0 ? max(mn, mx) === 1 ? 2 : 1 : 0; if (col[mx] > col[mn]) { col[md] = (col[md] - col[mn]) * s / (col[mx] - col[mn]); col[mx] = s; } else { col[md] = col[mx] = 0; } col[mn] = 0; dr = col[0]; dg = col[1]; db = col[2]; } var modes = { multiply: function() { dr = br * sr / 255; dg = bg * sg / 255; db = bb * sb / 255; }, screen: function() { dr = br + sr - (br * sr / 255); dg = bg + sg - (bg * sg / 255); db = bb + sb - (bb * sb / 255); }, overlay: function() { dr = br < 128 ? 2 * br * sr / 255 : 255 - 2 * (255 - br) * (255 - sr) / 255; dg = bg < 128 ? 2 * bg * sg / 255 : 255 - 2 * (255 - bg) * (255 - sg) / 255; db = bb < 128 ? 2 * bb * sb / 255 : 255 - 2 * (255 - bb) * (255 - sb) / 255; }, 'soft-light': function() { var t = sr * br / 255; dr = t + br * (255 - (255 - br) * (255 - sr) / 255 - t) / 255; t = sg * bg / 255; dg = t + bg * (255 - (255 - bg) * (255 - sg) / 255 - t) / 255; t = sb * bb / 255; db = t + bb * (255 - (255 - bb) * (255 - sb) / 255 - t) / 255; }, 'hard-light': function() { dr = sr < 128 ? 2 * sr * br / 255 : 255 - 2 * (255 - sr) * (255 - br) / 255; dg = sg < 128 ? 2 * sg * bg / 255 : 255 - 2 * (255 - sg) * (255 - bg) / 255; db = sb < 128 ? 2 * sb * bb / 255 : 255 - 2 * (255 - sb) * (255 - bb) / 255; }, 'color-dodge': function() { dr = br === 0 ? 0 : sr === 255 ? 255 : min(255, 255 * br / (255 - sr)); dg = bg === 0 ? 0 : sg === 255 ? 255 : min(255, 255 * bg / (255 - sg)); db = bb === 0 ? 0 : sb === 255 ? 255 : min(255, 255 * bb / (255 - sb)); }, 'color-burn': function() { dr = br === 255 ? 255 : sr === 0 ? 0 : max(0, 255 - (255 - br) * 255 / sr); dg = bg === 255 ? 255 : sg === 0 ? 0 : max(0, 255 - (255 - bg) * 255 / sg); db = bb === 255 ? 255 : sb === 0 ? 0 : max(0, 255 - (255 - bb) * 255 / sb); }, darken: function() { dr = br < sr ? br : sr; dg = bg < sg ? bg : sg; db = bb < sb ? bb : sb; }, lighten: function() { dr = br > sr ? br : sr; dg = bg > sg ? bg : sg; db = bb > sb ? bb : sb; }, difference: function() { dr = br - sr; if (dr < 0) dr = -dr; dg = bg - sg; if (dg < 0) dg = -dg; db = bb - sb; if (db < 0) db = -db; }, exclusion: function() { dr = br + sr * (255 - br - br) / 255; dg = bg + sg * (255 - bg - bg) / 255; db = bb + sb * (255 - bb - bb) / 255; }, hue: function() { setSat(sr, sg, sb, getSat(br, bg, bb)); setLum(dr, dg, db, getLum(br, bg, bb)); }, saturation: function() { setSat(br, bg, bb, getSat(sr, sg, sb)); setLum(dr, dg, db, getLum(br, bg, bb)); }, luminosity: function() { setLum(br, bg, bb, getLum(sr, sg, sb)); }, color: function() { setLum(sr, sg, sb, getLum(br, bg, bb)); }, add: function() { dr = min(br + sr, 255); dg = min(bg + sg, 255); db = min(bb + sb, 255); }, subtract: function() { dr = max(br - sr, 0); dg = max(bg - sg, 0); db = max(bb - sb, 0); }, average: function() { dr = (br + sr) / 2; dg = (bg + sg) / 2; db = (bb + sb) / 2; }, negation: function() { dr = 255 - abs(255 - sr - br); dg = 255 - abs(255 - sg - bg); db = 255 - abs(255 - sb - bb); } }; var nativeModes = this.nativeModes = Base.each([ 'source-over', 'source-in', 'source-out', 'source-atop', 'destination-over', 'destination-in', 'destination-out', 'destination-atop', 'lighter', 'darker', 'copy', 'xor' ], function(mode) { this[mode] = true; }, {}); var ctx = CanvasProvider.getContext(1, 1); if (ctx) { Base.each(modes, function(func, mode) { var darken = mode === 'darken', ok = false; ctx.save(); try { ctx.fillStyle = darken ? '#300' : '#a00'; ctx.fillRect(0, 0, 1, 1); ctx.globalCompositeOperation = mode; if (ctx.globalCompositeOperation === mode) { ctx.fillStyle = darken ? '#a00' : '#300'; ctx.fillRect(0, 0, 1, 1); ok = ctx.getImageData(0, 0, 1, 1).data[0] !== darken ? 170 : 51; } } catch (e) {} ctx.restore(); nativeModes[mode] = ok; }); CanvasProvider.release(ctx); } this.process = function(mode, srcContext, dstContext, alpha, offset) { var srcCanvas = srcContext.canvas, normal = mode === 'normal'; if (normal || nativeModes[mode]) { dstContext.save(); dstContext.setTransform(1, 0, 0, 1, 0, 0); dstContext.globalAlpha = alpha; if (!normal) dstContext.globalCompositeOperation = mode; dstContext.drawImage(srcCanvas, offset.x, offset.y); dstContext.restore(); } else { var process = modes[mode]; if (!process) return; var dstData = dstContext.getImageData(offset.x, offset.y, srcCanvas.width, srcCanvas.height), dst = dstData.data, src = srcContext.getImageData(0, 0, srcCanvas.width, srcCanvas.height).data; for (var i = 0, l = dst.length; i < l; i += 4) { sr = src[i]; br = dst[i]; sg = src[i + 1]; bg = dst[i + 1]; sb = src[i + 2]; bb = dst[i + 2]; sa = src[i + 3]; ba = dst[i + 3]; process(); var a1 = sa * alpha / 255, a2 = 1 - a1; dst[i] = a1 * dr + a2 * br; dst[i + 1] = a1 * dg + a2 * bg; dst[i + 2] = a1 * db + a2 * bb; dst[i + 3] = sa * alpha + a2 * ba; } dstContext.putImageData(dstData, offset.x, offset.y); } }; }; var SvgElement = new function() { var svg = 'http://www.w3.org/2000/svg', xmlns = 'http://www.w3.org/2000/xmlns', xlink = 'http://www.w3.org/1999/xlink', attributeNamespace = { href: xlink, xlink: xmlns, xmlns: xmlns + '/', 'xmlns:xlink': xmlns + '/' }; function create(tag, attributes, formatter) { return set(document.createElementNS(svg, tag), attributes, formatter); } function get(node, name) { var namespace = attributeNamespace[name], value = namespace ? node.getAttributeNS(namespace, name) : node.getAttribute(name); return value === 'null' ? null : value; } function set(node, attributes, formatter) { for (var name in attributes) { var value = attributes[name], namespace = attributeNamespace[name]; if (typeof value === 'number' && formatter) value = formatter.number(value); if (namespace) { node.setAttributeNS(namespace, name, value); } else { node.setAttribute(name, value); } } return node; } return { svg: svg, xmlns: xmlns, xlink: xlink, create: create, get: get, set: set }; }; var SvgStyles = Base.each({ fillColor: ['fill', 'color'], fillRule: ['fill-rule', 'string'], strokeColor: ['stroke', 'color'], strokeWidth: ['stroke-width', 'number'], strokeCap: ['stroke-linecap', 'string'], strokeJoin: ['stroke-linejoin', 'string'], strokeScaling: ['vector-effect', 'lookup', { true: 'none', false: 'non-scaling-stroke' }, function(item, value) { return !value && (item instanceof PathItem || item instanceof Shape || item instanceof TextItem); }], miterLimit: ['stroke-miterlimit', 'number'], dashArray: ['stroke-dasharray', 'array'], dashOffset: ['stroke-dashoffset', 'number'], fontFamily: ['font-family', 'string'], fontWeight: ['font-weight', 'string'], fontSize: ['font-size', 'number'], justification: ['text-anchor', 'lookup', { left: 'start', center: 'middle', right: 'end' }], opacity: ['opacity', 'number'], blendMode: ['mix-blend-mode', 'style'] }, function(entry, key) { var part = Base.capitalize(key), lookup = entry[2]; this[key] = { type: entry[1], property: key, attribute: entry[0], toSVG: lookup, fromSVG: lookup && Base.each(lookup, function(value, name) { this[value] = name; }, {}), exportFilter: entry[3], get: 'get' + part, set: 'set' + part }; }, {}); new function() { var formatter; function getTransform(matrix, coordinates, center) { var attrs = new Base(), trans = matrix.getTranslation(); if (coordinates) { var point; if (matrix.isInvertible()) { matrix = matrix._shiftless(); point = matrix._inverseTransform(trans); trans = null; } else { point = new Point(); } attrs[center ? 'cx' : 'x'] = point.x; attrs[center ? 'cy' : 'y'] = point.y; } if (!matrix.isIdentity()) { var decomposed = matrix.decompose(); if (decomposed) { var parts = [], angle = decomposed.rotation, scale = decomposed.scaling, skew = decomposed.skewing; if (trans && !trans.isZero()) parts.push('translate(' + formatter.point(trans) + ')'); if (angle) parts.push('rotate(' + formatter.number(angle) + ')'); if (!Numerical.isZero(scale.x - 1) || !Numerical.isZero(scale.y - 1)) parts.push('scale(' + formatter.point(scale) +')'); if (skew.x) parts.push('skewX(' + formatter.number(skew.x) + ')'); if (skew.y) parts.push('skewY(' + formatter.number(skew.y) + ')'); attrs.transform = parts.join(' '); } else { attrs.transform = 'matrix(' + matrix.getValues().join(',') + ')'; } } return attrs; } function exportGroup(item, options) { var attrs = getTransform(item._matrix), children = item._children; var node = SvgElement.create('g', attrs, formatter); for (var i = 0, l = children.length; i < l; i++) { var child = children[i]; var childNode = exportSVG(child, options); if (childNode) { if (child.isClipMask()) { var clip = SvgElement.create('clipPath'); clip.appendChild(childNode); setDefinition(child, clip, 'clip'); SvgElement.set(node, { 'clip-path': 'url(#' + clip.id + ')' }); } else { node.appendChild(childNode); } } } return node; } function exportRaster(item, options) { var attrs = getTransform(item._matrix, true), size = item.getSize(), image = item.getImage(); attrs.x -= size.width / 2; attrs.y -= size.height / 2; attrs.width = size.width; attrs.height = size.height; attrs.href = options.embedImages == false && image && image.src || item.toDataURL(); return SvgElement.create('image', attrs, formatter); } function exportPath(item, options) { var matchShapes = options.matchShapes; if (matchShapes) { var shape = item.toShape(false); if (shape) return exportShape(shape, options); } var segments = item._segments, length = segments.length, type, attrs = getTransform(item._matrix); if (matchShapes && length >= 2 && !item.hasHandles()) { if (length > 2) { type = item._closed ? 'polygon' : 'polyline'; var parts = []; for (var i = 0; i < length; i++) { parts.push(formatter.point(segments[i]._point)); } attrs.points = parts.join(' '); } else { type = 'line'; var start = segments[0]._point, end = segments[1]._point; attrs.set({ x1: start.x, y1: start.y, x2: end.x, y2: end.y }); } } else { type = 'path'; attrs.d = item.getPathData(null, options.precision); } return SvgElement.create(type, attrs, formatter); } function exportShape(item) { var type = item._type, radius = item._radius, attrs = getTransform(item._matrix, true, type !== 'rectangle'); if (type === 'rectangle') { type = 'rect'; var size = item._size, width = size.width, height = size.height; attrs.x -= width / 2; attrs.y -= height / 2; attrs.width = width; attrs.height = height; if (radius.isZero()) radius = null; } if (radius) { if (type === 'circle') { attrs.r = radius; } else { attrs.rx = radius.width; attrs.ry = radius.height; } } return SvgElement.create(type, attrs, formatter); } function exportCompoundPath(item, options) { var attrs = getTransform(item._matrix); var data = item.getPathData(null, options.precision); if (data) attrs.d = data; return SvgElement.create('path', attrs, formatter); } function exportSymbolItem(item, options) { var attrs = getTransform(item._matrix, true), definition = item._definition, node = getDefinition(definition, 'symbol'), definitionItem = definition._item, bounds = definitionItem.getStrokeBounds(); if (!node) { node = SvgElement.create('symbol', { viewBox: formatter.rectangle(bounds) }); node.appendChild(exportSVG(definitionItem, options)); setDefinition(definition, node, 'symbol'); } attrs.href = '#' + node.id; attrs.x += bounds.x; attrs.y += bounds.y; attrs.width = bounds.width; attrs.height = bounds.height; attrs.overflow = 'visible'; return SvgElement.create('use', attrs, formatter); } function exportGradient(color) { var gradientNode = getDefinition(color, 'color'); if (!gradientNode) { var gradient = color.getGradient(), radial = gradient._radial, origin = color.getOrigin(), destination = color.getDestination(), attrs; if (radial) { attrs = { cx: origin.x, cy: origin.y, r: origin.getDistance(destination) }; var highlight = color.getHighlight(); if (highlight) { attrs.fx = highlight.x; attrs.fy = highlight.y; } } else { attrs = { x1: origin.x, y1: origin.y, x2: destination.x, y2: destination.y }; } attrs.gradientUnits = 'userSpaceOnUse'; gradientNode = SvgElement.create((radial ? 'radial' : 'linear') + 'Gradient', attrs, formatter); var stops = gradient._stops; for (var i = 0, l = stops.length; i < l; i++) { var stop = stops[i], stopColor = stop._color, alpha = stopColor.getAlpha(), offset = stop._offset; attrs = { offset: offset == null ? i / (l - 1) : offset }; if (stopColor) attrs['stop-color'] = stopColor.toCSS(true); if (alpha < 1) attrs['stop-opacity'] = alpha; gradientNode.appendChild( SvgElement.create('stop', attrs, formatter)); } setDefinition(color, gradientNode, 'color'); } return 'url(#' + gradientNode.id + ')'; } function exportText(item) { var node = SvgElement.create('text', getTransform(item._matrix, true), formatter); node.textContent = item._content; return node; } var exporters = { Group: exportGroup, Layer: exportGroup, Raster: exportRaster, Path: exportPath, Shape: exportShape, CompoundPath: exportCompoundPath, SymbolItem: exportSymbolItem, PointText: exportText }; function applyStyle(item, node, isRoot) { var attrs = {}, parent = !isRoot && item.getParent(), style = []; if (item._name != null) attrs.id = item._name; Base.each(SvgStyles, function(entry) { var get = entry.get, type = entry.type, value = item[get](); if (entry.exportFilter ? entry.exportFilter(item, value) : !parent || !Base.equals(parent[get](), value)) { if (type === 'color' && value != null) { var alpha = value.getAlpha(); if (alpha < 1) attrs[entry.attribute + '-opacity'] = alpha; } if (type === 'style') { style.push(entry.attribute + ': ' + value); } else { attrs[entry.attribute] = value == null ? 'none' : type === 'color' ? value.gradient ? exportGradient(value, item) : value.toCSS(true) : type === 'array' ? value.join(',') : type === 'lookup' ? entry.toSVG[value] : value; } } }); if (style.length) attrs.style = style.join(';'); if (attrs.opacity === 1) delete attrs.opacity; if (!item._visible) attrs.visibility = 'hidden'; return SvgElement.set(node, attrs, formatter); } var definitions; function getDefinition(item, type) { if (!definitions) definitions = { ids: {}, svgs: {} }; return item && definitions.svgs[type + '-' + (item._id || item.__id || (item.__id = UID.get('svg')))]; } function setDefinition(item, node, type) { if (!definitions) getDefinition(); var typeId = definitions.ids[type] = (definitions.ids[type] || 0) + 1; node.id = type + '-' + typeId; definitions.svgs[type + '-' + (item._id || item.__id)] = node; } function exportDefinitions(node, options) { var svg = node, defs = null; if (definitions) { svg = node.nodeName.toLowerCase() === 'svg' && node; for (var i in definitions.svgs) { if (!defs) { if (!svg) { svg = SvgElement.create('svg'); svg.appendChild(node); } defs = svg.insertBefore(SvgElement.create('defs'), svg.firstChild); } defs.appendChild(definitions.svgs[i]); } definitions = null; } return options.asString ? new self.XMLSerializer().serializeToString(svg) : svg; } function exportSVG(item, options, isRoot) { var exporter = exporters[item._class], node = exporter && exporter(item, options); if (node) { var onExport = options.onExport; if (onExport) node = onExport(item, node, options) || node; var data = JSON.stringify(item._data); if (data && data !== '{}' && data !== 'null') node.setAttribute('data-paper-data', data); } return node && applyStyle(item, node, isRoot); } function setOptions(options) { if (!options) options = {}; formatter = new Formatter(options.precision); return options; } Item.inject({ exportSVG: function(options) { options = setOptions(options); return exportDefinitions(exportSVG(this, options, true), options); } }); Project.inject({ exportSVG: function(options) { options = setOptions(options); var children = this._children, view = this.getView(), bounds = Base.pick(options.bounds, 'view'), mx = options.matrix || bounds === 'view' && view._matrix, matrix = mx && Matrix.read([mx]), rect = bounds === 'view' ? new Rectangle([0, 0], view.getViewSize()) : bounds === 'content' ? Item._getBounds(children, matrix, { stroke: true }) .rect : Rectangle.read([bounds], 0, { readNull: true }), attrs = { version: '1.1', xmlns: SvgElement.svg, 'xmlns:xlink': SvgElement.xlink, }; if (rect) { attrs.width = rect.width; attrs.height = rect.height; if (rect.x || rect.x === 0 || rect.y || rect.y === 0) attrs.viewBox = formatter.rectangle(rect); } var node = SvgElement.create('svg', attrs, formatter), parent = node; if (matrix && !matrix.isIdentity()) { parent = node.appendChild(SvgElement.create('g', getTransform(matrix), formatter)); } for (var i = 0, l = children.length; i < l; i++) { parent.appendChild(exportSVG(children[i], options, true)); } return exportDefinitions(node, options); } }); }; new function() { var definitions = {}, rootSize; function getValue(node, name, isString, allowNull, allowPercent, defaultValue) { var value = SvgElement.get(node, name) || defaultValue, res = value == null ? allowNull ? null : isString ? '' : 0 : isString ? value : parseFloat(value); return /%\s*$/.test(value) ? (res / 100) * (allowPercent ? 1 : rootSize[/x|^width/.test(name) ? 'width' : 'height']) : res; } function getPoint(node, x, y, allowNull, allowPercent, defaultX, defaultY) { x = getValue(node, x || 'x', false, allowNull, allowPercent, defaultX); y = getValue(node, y || 'y', false, allowNull, allowPercent, defaultY); return allowNull && (x == null || y == null) ? null : new Point(x, y); } function getSize(node, w, h, allowNull, allowPercent) { w = getValue(node, w || 'width', false, allowNull, allowPercent); h = getValue(node, h || 'height', false, allowNull, allowPercent); return allowNull && (w == null || h == null) ? null : new Size(w, h); } function convertValue(value, type, lookup) { return value === 'none' ? null : type === 'number' ? parseFloat(value) : type === 'array' ? value ? value.split(/[\s,]+/g).map(parseFloat) : [] : type === 'color' ? getDefinition(value) || value : type === 'lookup' ? lookup[value] : value; } function importGroup(node, type, options, isRoot) { var nodes = node.childNodes, isClip = type === 'clippath', isDefs = type === 'defs', item = new Group(), project = item._project, currentStyle = project._currentStyle, children = []; if (!isClip && !isDefs) { item = applyAttributes(item, node, isRoot); project._currentStyle = item._style.clone(); } if (isRoot) { var defs = node.querySelectorAll('defs'); for (var i = 0, l = defs.length; i < l; i++) { importNode(defs[i], options, false); } } for (var i = 0, l = nodes.length; i < l; i++) { var childNode = nodes[i], child; if (childNode.nodeType === 1 && !/^defs$/i.test(childNode.nodeName) && (child = importNode(childNode, options, false)) && !(child instanceof SymbolDefinition)) children.push(child); } item.addChildren(children); if (isClip) item = applyAttributes(item.reduce(), node, isRoot); project._currentStyle = currentStyle; if (isClip || isDefs) { item.remove(); item = null; } return item; } function importPoly(node, type) { var coords = node.getAttribute('points').match( /[+-]?(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g), points = []; for (var i = 0, l = coords.length; i < l; i += 2) points.push(new Point( parseFloat(coords[i]), parseFloat(coords[i + 1]))); var path = new Path(points); if (type === 'polygon') path.closePath(); return path; } function importPath(node) { return PathItem.create(node.getAttribute('d')); } function importGradient(node, type) { var id = (getValue(node, 'href', true) || '').substring(1), radial = type === 'radialgradient', gradient; if (id) { gradient = definitions[id].getGradient(); if (gradient._radial ^ radial) { gradient = gradient.clone(); gradient._radial = radial; } } else { var nodes = node.childNodes, stops = []; for (var i = 0, l = nodes.length; i < l; i++) { var child = nodes[i]; if (child.nodeType === 1) stops.push(applyAttributes(new GradientStop(), child)); } gradient = new Gradient(stops, radial); } var origin, destination, highlight, scaleToBounds = getValue(node, 'gradientUnits', true) !== 'userSpaceOnUse'; if (radial) { origin = getPoint(node, 'cx', 'cy', false, scaleToBounds, '50%', '50%'); destination = origin.add( getValue(node, 'r', false, false, scaleToBounds, '50%'), 0); highlight = getPoint(node, 'fx', 'fy', true, scaleToBounds); } else { origin = getPoint(node, 'x1', 'y1', false, scaleToBounds, '0%', '0%'); destination = getPoint(node, 'x2', 'y2', false, scaleToBounds, '100%', '0%'); } var color = applyAttributes( new Color(gradient, origin, destination, highlight), node); color._scaleToBounds = scaleToBounds; return null; } var importers = { '#document': function (node, type, options, isRoot) { var nodes = node.childNodes; for (var i = 0, l = nodes.length; i < l; i++) { var child = nodes[i]; if (child.nodeType === 1) return importNode(child, options, isRoot); } }, g: importGroup, svg: importGroup, clippath: importGroup, polygon: importPoly, polyline: importPoly, path: importPath, lineargradient: importGradient, radialgradient: importGradient, image: function (node) { var raster = new Raster(getValue(node, 'href', true)); raster.on('load', function() { var size = getSize(node); this.setSize(size); var center = getPoint(node).add(size.divide(2)); this._matrix.append(new Matrix().translate(center)); }); return raster; }, symbol: function(node, type, options, isRoot) { return new SymbolDefinition( importGroup(node, type, options, isRoot), true); }, defs: importGroup, use: function(node) { var id = (getValue(node, 'href', true) || '').substring(1), definition = definitions[id], point = getPoint(node); return definition ? definition instanceof SymbolDefinition ? definition.place(point) : definition.clone().translate(point) : null; }, circle: function(node) { return new Shape.Circle( getPoint(node, 'cx', 'cy'), getValue(node, 'r')); }, ellipse: function(node) { return new Shape.Ellipse({ center: getPoint(node, 'cx', 'cy'), radius: getSize(node, 'rx', 'ry') }); }, rect: function(node) { return new Shape.Rectangle(new Rectangle( getPoint(node), getSize(node) ), getSize(node, 'rx', 'ry')); }, line: function(node) { return new Path.Line( getPoint(node, 'x1', 'y1'), getPoint(node, 'x2', 'y2')); }, text: function(node) { var text = new PointText(getPoint(node).add( getPoint(node, 'dx', 'dy'))); text.setContent(node.textContent.trim() || ''); return text; }, switch: importGroup }; function applyTransform(item, value, name, node) { if (item.transform) { var transforms = (node.getAttribute(name) || '').split(/\)\s*/g), matrix = new Matrix(); for (var i = 0, l = transforms.length; i < l; i++) { var transform = transforms[i]; if (!transform) break; var parts = transform.split(/\(\s*/), command = parts[0], v = parts[1].split(/[\s,]+/g); for (var j = 0, m = v.length; j < m; j++) v[j] = parseFloat(v[j]); switch (command) { case 'matrix': matrix.append( new Matrix(v[0], v[1], v[2], v[3], v[4], v[5])); break; case 'rotate': matrix.rotate(v[0], v[1] || 0, v[2] || 0); break; case 'translate': matrix.translate(v[0], v[1] || 0); break; case 'scale': matrix.scale(v); break; case 'skewX': matrix.skew(v[0], 0); break; case 'skewY': matrix.skew(0, v[0]); break; } } item.transform(matrix); } } function applyOpacity(item, value, name) { var key = name === 'fill-opacity' ? 'getFillColor' : 'getStrokeColor', color = item[key] && item[key](); if (color) color.setAlpha(parseFloat(value)); } var attributes = Base.set(Base.each(SvgStyles, function(entry) { this[entry.attribute] = function(item, value) { if (item[entry.set]) { item[entry.set](convertValue(value, entry.type, entry.fromSVG)); if (entry.type === 'color') { var color = item[entry.get](); if (color) { if (color._scaleToBounds) { var bounds = item.getBounds(); color.transform(new Matrix() .translate(bounds.getPoint()) .scale(bounds.getSize())); } } } } }; }, {}), { id: function(item, value) { definitions[value] = item; if (item.setName) item.setName(value); }, 'clip-path': function(item, value) { var clip = getDefinition(value); if (clip) { clip = clip.clone(); clip.setClipMask(true); if (item instanceof Group) { item.insertChild(0, clip); } else { return new Group(clip, item); } } }, gradientTransform: applyTransform, transform: applyTransform, 'fill-opacity': applyOpacity, 'stroke-opacity': applyOpacity, visibility: function(item, value) { if (item.setVisible) item.setVisible(value === 'visible'); }, display: function(item, value) { if (item.setVisible) item.setVisible(value !== null); }, 'stop-color': function(item, value) { if (item.setColor) item.setColor(value); }, 'stop-opacity': function(item, value) { if (item._color) item._color.setAlpha(parseFloat(value)); }, offset: function(item, value) { if (item.setOffset) { var percent = value.match(/(.*)%$/); item.setOffset(percent ? percent[1] / 100 : parseFloat(value)); } }, viewBox: function(item, value, name, node, styles) { var rect = new Rectangle(convertValue(value, 'array')), size = getSize(node, null, null, true), group, matrix; if (item instanceof Group) { var scale = size ? size.divide(rect.getSize()) : 1, matrix = new Matrix().scale(scale) .translate(rect.getPoint().negate()); group = item; } else if (item instanceof SymbolDefinition) { if (size) rect.setSize(size); group = item._item; } if (group) { if (getAttribute(node, 'overflow', styles) !== 'visible') { var clip = new Shape.Rectangle(rect); clip.setClipMask(true); group.addChild(clip); } if (matrix) group.transform(matrix); } } }); function getAttribute(node, name, styles) { var attr = node.attributes[name], value = attr && attr.value; if (!value && node.style) { var style = Base.camelize(name); value = node.style[style]; if (!value && styles.node[style] !== styles.parent[style]) value = styles.node[style]; } return !value ? undefined : value === 'none' ? null : value; } function applyAttributes(item, node, isRoot) { var parent = node.parentNode, styles = { node: DomElement.getStyles(node) || {}, parent: !isRoot && !/^defs$/i.test(parent.tagName) && DomElement.getStyles(parent) || {} }; Base.each(attributes, function(apply, name) { var value = getAttribute(node, name, styles); item = value !== undefined && apply(item, value, name, node, styles) || item; }); return item; } function getDefinition(value) { var match = value && value.match(/\((?:["'#]*)([^"')]+)/), name = match && match[1], res = name && definitions[window ? name.replace(window.location.href.split('#')[0] + '#', '') : name]; if (res && res._scaleToBounds) { res = res.clone(); res._scaleToBounds = true; } return res; } function importNode(node, options, isRoot) { var type = node.nodeName.toLowerCase(), isElement = type !== '#document', body = document.body, container, parent, next; if (isRoot && isElement) { rootSize = paper.getView().getSize(); rootSize = getSize(node, null, null, true) || rootSize; container = SvgElement.create('svg', { style: 'stroke-width: 1px; stroke-miterlimit: 10' }); parent = node.parentNode; next = node.nextSibling; container.appendChild(node); body.appendChild(container); } var settings = paper.settings, applyMatrix = settings.applyMatrix, insertItems = settings.insertItems; settings.applyMatrix = false; settings.insertItems = false; var importer = importers[type], item = importer && importer(node, type, options, isRoot) || null; settings.insertItems = insertItems; settings.applyMatrix = applyMatrix; if (item) { if (isElement && !(item instanceof Group)) item = applyAttributes(item, node, isRoot); var onImport = options.onImport, data = isElement && node.getAttribute('data-paper-data'); if (onImport) item = onImport(node, item, options) || item; if (options.expandShapes && item instanceof Shape) { item.remove(); item = item.toPath(); } if (data) item._data = JSON.parse(data); } if (container) { body.removeChild(container); if (parent) { if (next) { parent.insertBefore(node, next); } else { parent.appendChild(node); } } } if (isRoot) { definitions = {}; if (item && Base.pick(options.applyMatrix, applyMatrix)) item.matrix.apply(true, true); } return item; } function importSVG(source, options, owner) { if (!source) return null; options = typeof options === 'function' ? { onLoad: options } : options || {}; var scope = paper, item = null; function onLoad(svg) { try { var node = typeof svg === 'object' ? svg : new self.DOMParser().parseFromString( svg.trim(), 'image/svg+xml' ); if (!node.nodeName) { node = null; throw new Error('Unsupported SVG source: ' + source); } paper = scope; item = importNode(node, options, true); if (!options || options.insert !== false) { owner._insertItem(undefined, item); } var onLoad = options.onLoad; if (onLoad) onLoad(item, svg); } catch (e) { onError(e); } } function onError(message, status) { var onError = options.onError; if (onError) { onError(message, status); } else { throw new Error(message); } } if (typeof source === 'string' && !/^[\s\S]*</.test(source)) { var node = document.getElementById(source); if (node) { onLoad(node); } else { Http.request({ url: source, async: true, onLoad: onLoad, onError: onError }); } } else if (typeof File !== 'undefined' && source instanceof File) { var reader = new FileReader(); reader.onload = function() { onLoad(reader.result); }; reader.onerror = function() { onError(reader.error); }; return reader.readAsText(source); } else { onLoad(source); } return item; } Item.inject({ importSVG: function(node, options) { return importSVG(node, options, this); } }); Project.inject({ importSVG: function(node, options) { this.activate(); return importSVG(node, options, this); } }); }; var paper = new (PaperScope.inject(Base.exports, { Base: Base, Numerical: Numerical, Key: Key, DomEvent: DomEvent, DomElement: DomElement, document: document, window: window, Symbol: SymbolDefinition, PlacedSymbol: SymbolItem }))(); if (paper.agent.node) { require('./node/extend.js')(paper); } if (typeof define === 'function' && define.amd) { define('paper', paper); } else if (typeof module === 'object' && module) { module.exports = paper; } return paper; }.call(this, typeof self === 'object' ? self : null);
{ "content_hash": "482a4dec3b04baf418ab87222c236038", "timestamp": "", "source": "github", "line_count": 15653, "max_line_length": 229, "avg_line_length": 25.09506164952405, "alnum_prop": 0.5852148477774411, "repo_name": "cdnjs/cdnjs", "id": "130f5f4ec8e9235aad2a3dfd61ec38aedffc5a41", "size": "393571", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ajax/libs/paper.js/0.12.12/paper-core.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * isCollidingBottomRight() * ------------------------ * Used to determine whether the right-bottom side of obj1 collides with the * left side of obj2. The objects must have an x1, y1, x2, and y2. * * @param {CollisionObject} obj1 This is the first object in the collision test. * @param {CollisionObject} obj2 This is the second object in the collision test. * @return {boolean} Returns whether there is a collision or not. */ var isCollidingBottomRight = function (obj1, obj2) { return (obj1.x1 < obj2.x1) && (obj1.x1 < obj2.x2) && (obj1.x2 > obj2.x1) && (obj1.x2 < obj2.x2) && (obj1.y1 < obj2.y1) && (obj1.y1 < obj2.y2) && (obj1.y2 > obj2.y1) && (obj1.y2 < obj2.y2); }; exports.default = isCollidingBottomRight;
{ "content_hash": "3bc8b6c8245ec2880a9223ab3476565d", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 81, "avg_line_length": 43.78947368421053, "alnum_prop": 0.6418269230769231, "repo_name": "mission-bay-games/collision.js", "id": "260cd98508c469549d828daf1708d0b52a153f42", "size": "832", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/is-colliding-bottom/is-colliding-bottom-right/is-colliding-bottom-right.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "9120" } ], "symlink_target": "" }
./configure --debug --no-regex --no-pcre2 make all pushd fuzzer/ make cp Fuzz_http $OUT/Fuzz_http cp Fuzz_json $OUT/Fuzz_json popd pushd $SRC/oss-fuzz-bloat/nginx-unit/ cp Fuzz_http_seed_corpus.zip $OUT/Fuzz_http_seed_corpus.zip cp Fuzz_json_seed_corpus.zip $OUT/Fuzz_json_seed_corpus.zip popd
{ "content_hash": "0a396ad11f161f5754c0ff51ffd82575", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 59, "avg_line_length": 22.76923076923077, "alnum_prop": 0.7533783783783784, "repo_name": "google/oss-fuzz", "id": "408bca4a25ff2475c871aeda2afd6355540c018e", "size": "970", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "projects/unit/build.sh", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "559317" }, { "name": "C++", "bytes": "420884" }, { "name": "CMake", "bytes": "1635" }, { "name": "Dockerfile", "bytes": "899156" }, { "name": "Go", "bytes": "78124" }, { "name": "HTML", "bytes": "13787" }, { "name": "Java", "bytes": "607666" }, { "name": "JavaScript", "bytes": "2508" }, { "name": "Makefile", "bytes": "15308" }, { "name": "Python", "bytes": "1002953" }, { "name": "Ruby", "bytes": "1827" }, { "name": "Rust", "bytes": "9192" }, { "name": "Shell", "bytes": "1433213" }, { "name": "Starlark", "bytes": "5471" }, { "name": "Swift", "bytes": "1363" } ], "symlink_target": "" }
<?php /** * @see Zend_Service_DeveloperGarden_Request_RequestAbstract */ // require_once 'Zend/Service/DeveloperGarden/Request/RequestAbstract.php'; /** * @category Zend * @package Zend_Service * @subpackage DeveloperGarden * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @author Marco Kaiser * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Service_DeveloperGarden_Request_ConferenceCall_RemoveConferenceTemplateParticipantRequest extends Zend_Service_DeveloperGarden_Request_RequestAbstract { /** * the template id * * @var string */ public $templateId = null; /** * the participant id * * @var string */ public $participantId = null; /** * constructor * * @param integer $environment * @param string $templateId * @param string $participantId */ public function __construct($environment, $templateId, $participantId) { parent::__construct($environment); $this->setTemplateId($templateId) ->setParticipantId($participantId); } /** * set the template id * * @param string $templateId * @return Zend_Service_DeveloperGarden_Request_ConferenceCall_RemoveConferenceTemplateParticipantRequest */ public function setTemplateId($templateId) { $this->templateId = $templateId; return $this; } /** * set the participant id * * @param string $participantId * @return Zend_Service_DeveloperGarden_Request_ConferenceCall_RemoveConferenceTemplateParticipantRequest */ public function setParticipantId($participantId) { $this->participantId = $participantId; return $this; } }
{ "content_hash": "91cc18d42a6d31fe3790be5737283b1a", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 109, "avg_line_length": 25.64788732394366, "alnum_prop": 0.6507413509060955, "repo_name": "calonso-conabio/intranet", "id": "e3640430229cd31055c3865041b13f66e9b55dde", "size": "2545", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "protected/vendors/Zend/Service/DeveloperGarden/Request/ConferenceCall/RemoveConferenceTemplateParticipantRequest.php", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "13" }, { "name": "Batchfile", "bytes": "1410" }, { "name": "CSS", "bytes": "215052" }, { "name": "HTML", "bytes": "31712" }, { "name": "JavaScript", "bytes": "657426" }, { "name": "PHP", "bytes": "13097099" }, { "name": "Shell", "bytes": "179" } ], "symlink_target": "" }
package com.orionplatform.math.set; import java.util.Arrays; import java.util.List; import com.orionplatform.core.exception.Assert; import com.orionplatform.data.data_structures.set.OrionSet; import com.orionplatform.math.MathRule; import com.orionplatform.math.number.ANumber; public class SetRules extends MathRule { public static synchronized void isNotEmpty(Set set) { Assert.notNull(set, "The set input cannot be null."); isValid(set.getElements()); } public static synchronized void isNotEmpty(MultiSet set) { Assert.notNull(set, "The MultiSet input cannot be null."); isValid(set.getElements()); } public static synchronized void isNotEmpty(OrionSet<ANumber> elements) { Assert.notEmpty(elements, "The elements input cannot be null/empty."); } public static synchronized void isNotEmpty(List<ANumber> elements) { Assert.notEmpty(elements, "The elements input cannot be null/empty."); } public static synchronized void isValid(OrionSet<ANumber> elements) { isNotEmpty(elements); } public static synchronized void isValid(List<ANumber> elements) { isNotEmpty(elements); } public static synchronized void isValid(Set set) { Assert.notNull(set, "The set input cannot be null."); isValid(set.getElements()); } public static synchronized void isValid(MultiSet set) { Assert.notNull(set, "The MultiSet input cannot be null."); isValid(set.getElements()); } public static synchronized <T> void isValid(Set... sets) { Assert.notNull(sets, "The set input cannot be null."); Arrays.stream(sets).forEach(set -> isValid(set.getElements())); } public static synchronized <T> void isValid(MultiSet... sets) { Assert.notNull(sets, "The MultiSet input cannot be null."); Arrays.stream(sets).forEach(multiset -> isValid(multiset.getElements())); } }
{ "content_hash": "99b0cd555e211bd365b7900592b0983a", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 81, "avg_line_length": 27.342105263157894, "alnum_prop": 0.651106833493744, "repo_name": "orioncode/orionplatform", "id": "25b0312f795e5b164a831190b21d6249231864d1", "size": "2078", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "orion_math/orion_math_core/src/main/java/com/orionplatform/math/set/SetRules.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "622824" }, { "name": "HTML", "bytes": "3108485" }, { "name": "Java", "bytes": "8358343" }, { "name": "JavaScript", "bytes": "211562" } ], "symlink_target": "" }
#include "vix_all.h" #include <maya/MFnSet.h> #include <maya/MFnTransform.h> #include <maya/MPlug.h> #include <maya/MPlugArray.h> #include <maya/MItDependencyGraph.h> #include <maya/MFnCompoundAttribute.h> /*! * @fn SharedObj* meConvProj::Make() * * A Maya projection node applies a 3D projection onto a texture. It has two inputs - * the texture image and a 3D texture placement (4x4 matrix). * This converter exists to provide a way to link the 3D texture matrix to the texture. * It does not have a corresponding Vixen object. * * @return NULL * * @see meConvTex::Make meConvProj::Convert */ SharedObj* meConvProj::Make() { meConnIter iter(m_MayaObj, "image", true); MPlug plug; while (iter.Next(m_TexImage, MFn::kTexture2d)) return NULL; ME_ERROR(("ERROR: Projection texture %s has no image file", GetMayaName()), NULL); return NULL; } /*! * @fn int meConvProj::Link(meConvObj* convparent) * * Links this UV mapper to the texture converter associated with * the image used as input to the projection. This effectively associates * the 3D texture matrix with the right texture. * * @return -1 on error, 0 if no link, 1 if successful link * * @see meConvTex::Make */ int meConvProj::Link(meConvObj* convparent) { ConvRef cvref = Exporter->MayaObjects[m_TexImage]; meConvTex* texconv = dynamic_cast<meConvTex*>( (meConvObj*) cvref ); MObject uvmapper; meConvUV3* uvconv; if (!texconv) return -1; assert(convparent == NULL); /* * Find the UV converter which uses the projection matrix */ meConnIter iter(m_MayaObj, "placementMatrix", true); if (!iter.Next(uvmapper, MFn::kPlace3dTexture)) return -1; cvref = Exporter->MayaObjects[uvmapper]; uvconv = dynamic_cast<meConvUV3*> ((meConvObj*) cvref); if (!uvconv) return -1; uvconv->NoTexCoords = true; // texcoords generated automatically uvconv->UVGen = Sampler::TEXGEN_SPHERE; // assume spherical projection /* * Link the UV converter to the texture converter */ if (!texconv->UVMapper.IsNull()) { ME_ERROR(("ERROR: texture %s with multiple UV mappers", texconv->GetMayaName()), 0); } meLog(1, "UV projection %s linked to texture %s", uvconv->GetMayaName(), texconv->GetMayaName()); texconv->UVMapper = uvconv; // link UV mapper to the texture texconv->DoConvert = true; // link texture to state return 1; } meConvUV::meConvUV(MObject& uvobj) : meConvShader(uvobj) { MStatus status; MFnDependencyNode uvmap(uvobj, &status); MPlug plug; RotateFrame = 0; RotateUV = 0; CoverageU = 1; CoverageV = 1; TranslateU = 0; TranslateV = 0; RepeatU = 1; RepeatV = 1; OffsetU = 1; OffsetV = 0; WrapU = 1; WrapV = 1; Stagger = 0; Mirror = 0; HasMapper = false; NoTexCoords = false; MakeTexCoords = false; } /*! * @fn SharedObj* meConvUV::Make() * * Extracts UV mapping parameters from the Maya texture placement object. * If the UV mapper is attached to a texture, this converter becomes a * child of the texture's converter. * * @see meConvGeo::LinkUVMappers */ SharedObj* meConvUV::Make() { MStatus status; MFnDependencyNode uvmap(m_MayaObj, &status); MPlug plug; if (!status || !m_MayaObj.hasFn(MFn::kPlace2dTexture)) return NULL; HasMapper = true; plug = uvmap.findPlug("coverageU"); plug.getValue(CoverageU); plug = uvmap.findPlug("coverageV"); plug.getValue(CoverageV); plug = uvmap.findPlug("translateU"); plug.getValue(TranslateU); plug = uvmap.findPlug("translateV"); plug.getValue(TranslateV); plug = uvmap.findPlug("repeatU"); plug.getValue(RepeatU); plug = uvmap.findPlug("repeatV"); plug.getValue(RepeatV); plug = uvmap.findPlug("offsetU"); plug.getValue(OffsetU); plug = uvmap.findPlug("offsetV"); plug.getValue(OffsetV); plug = uvmap.findPlug("wrapU"); plug.getValue(WrapU); plug = uvmap.findPlug("wrapV"); plug.getValue(WrapV); plug = uvmap.findPlug("rotateUV"); plug.getValue(RotateUV); plug = uvmap.findPlug("rotateFrame"); plug.getValue(RotateFrame); return this; } int meConvUV::Convert(meConvObj*) { meLog(1, "%s: Converting UV mapper", GetMayaName()); return 1; } /*! * @fn bool meConvUV::MapUV(Vec2* uv, Vec3* loc, Vec3* ctr) * @param uv U and V coordinates before (input) and after (output) mapping * @param loc location at this UV * @param ctr center of object * * Maps a U,V coordinate from a Maya mesh using the given texture placement object. * The location and center are not used by the base implementation but are * included for subclasses which generate texcoords from object space coordinates. * * @returns true if mapping successful, false if no mapper * * @see meConvUV3::MapUV */ bool meConvUV::MapUV(Vec2* uv, Vec3* loc, Vec3* ctr) { float outu, outv; if (!HasMapper) return false; map(uv->x, uv->y, outu, outv); uv->x = outu; uv->y = outv; return true; } /*! * @fn bool meConvUV::MapUV(Vec2* uvs, int n) * @param uvs input and output array of UVs * Maps U,V coordinates from a Maya mesh using the given texture placement object. * * @returns true if mapping successful, false if no texture mapper */ bool meConvUV::MapUV(Vec2* uvs, int n) { float outU, outV; float inU, inV; if (!HasMapper) return false; for (int i = 0; i < n; ++i) { Vec2* uvptr = uvs + i; Vec2& tc = *uvptr; inU = tc.x; inV = tc.y; map(inU, inV, outU, outV); tc.x = outU; tc.y = outV; } return true; } /* * @fn int meConvUV::Link(meConvObj* convparent) * Find the converter for texture which uses this UV mapper and attach * the UV mapper as a child of the texture converter. * This relationship is used later in determining which UV mapper * to use for which set of mesh texture coordinates. */ int meConvUV::Link(meConvObj* convparent) { MObject texobj; meConnIter iter(m_MayaObj, "outUV", false); while (iter.Next(texobj)) { ConvRef cvref; meConvTex* txconv; if (!texobj.hasFn(MFn::kTexture2d) && // not a texture? !texobj.hasFn(MFn::kTexture3d)) continue; cvref = Exporter->MayaObjects[texobj]; txconv = dynamic_cast<meConvTex*>( (meConvObj*) cvref ); if (!txconv) continue; if (!txconv->UVMapper.IsNull() && ((meConvUV*) txconv->UVMapper != this)) { meLog(1, "ERROR: %s texture with multiple UV mappers", txconv->GetMayaName()); continue; } else { meLog(1, "%s: UV mapper linked to texture %s", GetMayaName(), txconv->GetMayaName()); txconv->UVMapper = this; // make UV mapper a child of the texture } } return 1; } #define ME_MAPMETHOD1 void meConvUV::map(float inU, float inV, float& outU, float& outV) { bool inside = true; float tmp; outU = mapU(inU, inV, inside); outV = mapV(inU, inV, inside); if (inside) { if (Stagger) if (int(ffloor(outV)) % 2) outU += 0.5f; if (Mirror) { if (int(ffloor(outU)) % 2) outU = 2 * ffloor(outU) + 1.0f - outU; if (int(ffloor(outV)) % 2) outV = 2 * ffloor(outV) + 1.0f - outV; } #ifdef ME_MAPMETHOD1 float cosa = cos(-RotateUV); float sina = sin(-RotateUV); outU -= 0.5f; outV -= 0.5f; tmp = outU * cosa - outV * sina + 0.5f; outV = outU * sina + outV * cosa + 0.5f; #else float cosa = cos(RotateUV); float sina = sin(RotateUV); outU -= 0.5f; outV -= 0.5f; tmp = outU * sina + outV * cosa + 0.5; outV = outU * cosa - outV * sina + 0.5; #endif outU = tmp; } } float meConvUV::mapU(float inU, float inV, bool& inside) { #ifdef ME_MAPMETHOD1 double outU = (inV - 0.5) * sin(-RotateFrame) + (inU - 0.5) * cos(-RotateFrame) + 0.5; if (CoverageU < 1.0) { if (outU >= 1.0) outU -= floor(outU); else if (outU < 0.0) outU = outU - floor(outU) + 1.0; outU -= TranslateU; if (WrapU) { if (outU >= CoverageU) outU -= 1.0; else if (outU < 0.0) outU += 1.0; } #else float outU = (inU - 0.5) * sin(RotateFrame) + (inV - 0.5) * cos(RotateFrame) + 0.5; if (CoverageU < 1.0) { if (WrapU) { if (outU > 1.0) outU -= ffloor(outU); else if (outU < 0.0) outU = outU - ffloor(outU) + 1.0; outU = outU - (TranslateU - ffloor(TranslateU)); if (outU > CoverageU) outU -= 1.0; else if (outU < 0.0) outU += 1.0; outU /= CoverageU; } #endif if (outU < 0.0 || outU > 1.0) inside = false; } else { outU = (outU - TranslateU) / CoverageU; if (!WrapU) { if (outU < 0.0 || outU > 1.0) inside = false; } } return (float) (outU * RepeatU + OffsetU); } float meConvUV::mapV(float inU, float inV, bool& inside) { #ifdef ME_MAPMETHOD1 float outV = (inV - 0.5f) * cos(-RotateFrame) - (inU - 0.5f) * sin(-RotateFrame) + 0.5f; if (CoverageV < 1.0f) { if (WrapV) { if (outV > 1.0f) outV -= ffloor(outV); else if (outV < 0.0f) outV = outV - ffloor(outV) + 1.0f; outV = outV - (TranslateV - ffloor(TranslateV)); if (outV > CoverageV) outV -= 1.0f; else if (outV < 0.0f) outV += 1.0f; outV /= CoverageV; } #else float outV = (inU - 0.5f) * cos(RotateFrame) - (inV - 0.5f) * sin(RotateFrame) + 0.5f; if (CoverageV < 1.0f) { if (WrapV) { if (outV > 1.0f) outV -= ffloor(outV); else if (outV < 0.0f) outV = outV - ffloor(outV) + 1.0f; outV = outV - (TranslateV - ffloor(TranslateV)); if (outV > CoverageV) outV -= 1.0f; else if (outV < 0.0f) outV += 1.0f; outV /= CoverageV; } #endif if (outV < 0.0f || outV > 1.0f) inside = false; } else { outV = (outV - TranslateV) / CoverageV; if (!WrapV) { if (outV < 0.0f || outV > 1.0f) inside = false; } } return outV * RepeatV + OffsetV; } meConvUV3::meConvUV3(MObject& uvobj) : meConvUV(uvobj) { HasMapper = false; NoTexCoords = true; UVMatrix.Identity(); } /*! * @fn SharedObj* meConvUV3::Make() * * Extracts UV mapping matrix from the Maya 3D texture placement object. * The Maya UV mapping may be directly attached to a texture or it may * be linked to an environment mapping node. * * 3D texture placement generates texture coordinates - it does not * start with a UV set from Maya. The 3D matrix becomes the Vixen * texture projection matrix in the GeoState. If it is used as a * reflection map, the texture coordinates that are generated dynamically * use a spherical projection and vary with the eyepoint. * * Note: 3D matrix currently disabled - not sure how to apply it in Vixen. * * @see meConvGeo::LinkUVMappers meConvUV3::Link meConvUV3::UpdateState */ SharedObj* meConvUV3::Make() { MFnTransform uvmap(m_MayaObj, &m_Status); MDagPath dagPath; if (!m_Status || !m_MayaObj.hasFn(MFn::kPlace3dTexture)) return NULL; MTransformationMatrix tmtx = uvmap.transformation(); MMatrix mtx = tmtx.asMatrix(); float fltdata[4][4]; if (!mtx.isEquivalent(MMatrix::identity)) { mtx.get(fltdata); UVMatrix.SetMatrix(&fltdata[0][0]); UVMatrix.Transpose(); } // HasMapper = true; return NULL; } int meConvUV3::Link(meConvObj* convparent) { MFnTransform uvmap(m_MayaObj); MPlug plug = uvmap.findPlug("worldInverseMatrix"); MObject texobj; if (IsChild()) // already attached? return 1; if (plug.numElements() < 1) return 0; meConnIter iter(plug[0], false); while (iter.Next(texobj)) { if (texobj.hasFn(MFn::kTexture3d)) // associated with 3D texture? MakeTexCoords = true; // generate static texcoords else if (!texobj.hasFn(MFn::kTexture2d)) // not a texture? continue; ConvRef cvref = Exporter->MayaObjects[texobj]; meConvTex* txconv = dynamic_cast<meConvTex*>( (meConvObj*) cvref ); if (!txconv) continue; meLog(1, "UV mapping %s linked to texture %s", GetMayaName(), txconv->GetMayaName()); txconv->Append(this); // make UV mapper a child of the texture assert(UVGen == Sampler::NONE); } return 1; } int meConvUV3::Convert(meConvObj*) { meLog(1, "%s: Converting 3D UV mapper", GetMayaName()); return 1; } /*! * @fn void meConvUV3::UpdateState(meConvState* state, int texindex) * @state state converter for GeoState to update * @texindex index of texture to update * * Updates the Vixen GeoState invormation for 3D UV mapping. * The UV matrix from this converter becomes the Vixen * texture matrix. */ void meConvUV3::UpdateState(meConvState* state, int texindex) { } void meConvUV3::map(float inU, float inV, float& outU, float& outV) { if (!HasMapper || NoTexCoords) { outU = inU; outV = inV; return; } Vec3 vec(inU, inV, 0); vec *= UVMatrix; outU = vec[0]; outV = vec[1]; } /*! * @fn bool meConvUV::MapUV(Vec2* uv, Vec3* loc, Vec3* ctr) * @param uv U and V coordinates before (input) and after (output) mapping * @param loc location at this UV * @param ctr center of object * * Maps a U,V coordinate from a Maya mesh using the given texture placement object. * The location and center are only used if texture coordinates are being generated * from the object space coordinates (MakeTexCoords is set). In this case, * there are no input UVs. * * @returns true if mapping successful, false if no mapper */ bool meConvUV3::MapUV(Vec2* uv, Vec3* loc, Vec3* center) { Vec3 v; if (!HasMapper) return false; if (!MakeTexCoords) return meConvUV::MapUV(uv, loc, center); if (NoTexCoords) return false; v = *loc - *center; // generate UVs in spherical projection v.Normalize(); uv->x = v[0] / 2 + 0.5f; uv->y = v[2] / 2 + 0.5f; uv->x *= 4; uv->y *= 4; return true; }
{ "content_hash": "d9493742b7174dd2d6e057e5d24bff27", "timestamp": "", "source": "github", "line_count": 532, "max_line_length": 101, "avg_line_length": 26.360902255639097, "alnum_prop": 0.6248573873359954, "repo_name": "Caprica666/vixen", "id": "75e763f1eb7e2de6c3fdfa6fc3cc69dafcf05ed6", "size": "14024", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tools/mayaexp/meuvmap.cpp", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Batchfile", "bytes": "497" }, { "name": "C", "bytes": "135338" }, { "name": "C#", "bytes": "1100615" }, { "name": "C++", "bytes": "4679902" }, { "name": "CMake", "bytes": "8595" }, { "name": "Clarion", "bytes": "5270" }, { "name": "GLSL", "bytes": "39084" }, { "name": "HLSL", "bytes": "43657" }, { "name": "HTML", "bytes": "70015" }, { "name": "Java", "bytes": "524219" }, { "name": "Makefile", "bytes": "5635" }, { "name": "Mathematica", "bytes": "1229773" }, { "name": "Objective-C", "bytes": "1332" }, { "name": "XSLT", "bytes": "8061" } ], "symlink_target": "" }
var expect = require('chai').expect; var repattern = require('../lib'); describe("repattern", function() { beforeEach(function() { if (require.cache['../lib']) delete require.cache['../lib']; repattern = require('../lib'); }); describe("#use", function() { it("should return the repattern function", function() { var ret = repattern.use("xyz", /.*/, ""); expect(ret).to.equal(repattern); }); it('should throw when given duplicate keys', function() { var f = function() { repattern .use("xyz", /.*/, "") .use("xyz", /.*/, ""); } expect(f).to.throw(/duplicate/); }); }); });
{ "content_hash": "5d0de45644263b907184df1761db2817", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 59, "avg_line_length": 24.115384615384617, "alnum_prop": 0.5645933014354066, "repo_name": "xianwill/node-repattern", "id": "f2bc3c6ec63266d4e1d1b67de83be4c333b0dc21", "size": "627", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test/repattern.use.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "8114" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Data; using System.Linq; using System.Security.Principal; using System.Text.RegularExpressions; using SimpleReport.Model.Constants; using SimpleReport.Model.DbExecutor; using SimpleReport.Model.Helpers; using SimpleReport.Model.Result; namespace SimpleReport.Model.Constants { } namespace SimpleReport.Model { public class Report : LookupReport { public ParameterList Parameters { get; set; } public bool HasTemplate { get { return TemplateFormat != TemplateFormat.Empty; } } public Guid? DetailReportId { get; set; } public string MailSubject { get; set; } public string MailText { get; set; } public bool OnScreenFormatAllowed { get; set; } public bool AutoRefreshAllowed { get; set; } public int AutoRefreshIntervalInSeconds { get; set; } public AccessStyle TemplateEditorAccessStyle { get; set; } public AccessStyle SubscriptionAccessStyle { get; set; } public TemplateFormat TemplateFormat { get; set; } public string ReportResultType { get; set; } public bool ConvertToPdf { get; set; } public ReportType ReportType { get; set; } = ReportType.SingleReport; public IEnumerable<LinkedReportViewModel> ReportList { get; set; } = new List<LinkedReportViewModel>(); public Report() { Parameters = new ParameterList(); } public bool IsParameterValueValid() { return Parameters.All(p => p.IsValid()); } public bool HasMailTemplateChanged(Report reportWithPossibleChanges) { return !(String.Equals(MailSubject, reportWithPossibleChanges.MailSubject, StringComparison.CurrentCulture) && String.Equals(MailText, reportWithPossibleChanges.MailText, StringComparison.CurrentCulture)); } public void ReadParameters(NameValueCollection queryString) { Parameters.ReadParameters(queryString); } public void ReadMultiReportParameters(NameValueCollection queryString) { Parameters.ReadMultiReportParameters(queryString); } public void IsAllowedToEditTemplate(IPrincipal user, Access adminAccess) { if (!IsAvailableToEditTemplate(user, adminAccess)) throw new Exception("Not allowed to edit template in report"); } public bool IsAvailableToEditTemplate(IPrincipal user, Access adminAccess) { if (TemplateEditorAccessStyle == AccessStyle.Anyone) return true; if (adminAccess.IsAvailableForMe(user)) return true; if (TemplateEditorAccessStyle == AccessStyle.ReportOwner) return ReportOwnerAccess != null && ReportOwnerAccess.IsAvailableForMe(user); return false; } public void IsAllowedToEditSubscriptions(IPrincipal user, Access adminAccess) { if (!IsAvailbleToEditSubscriptions(user, adminAccess)) throw new Exception("Not allowed to edit subscriptions for report"); } public bool IsAvailbleToEditSubscriptions(IPrincipal user, Access adminAccess) { if (SubscriptionAccessStyle == AccessStyle.Anyone) return true; if (adminAccess.IsAvailableForMe(user)) return true; if (SubscriptionAccessStyle == AccessStyle.ReportOwner) return ReportOwnerAccess != null && ReportOwnerAccess.IsAvailableForMe(user); return false; } public RawReportResult ExecuteAsRawData() { if (Connection == null) throw new Exception("Missing Connection in report"); var db = DbExecutorFactory.GetInstance(Connection); var parameters = Parameters.CreateParameters(Sql, UpdateSql, db); DataTable result = db.GetResults(Connection, Sql, parameters); var raw = new RawReportResult { Headers = result.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToArray(), Rows = result.Rows.Cast<DataRow>().Select(x => x.ItemArray.Select(Stringify).ToArray()).ToArray() }; return raw; } public ResultFileInfo ExecuteWithTemplate(Template template, Report detailReport = null) { if (Connection == null) throw new Exception("Missing Connection in report"); var db = DbExecutorFactory.GetInstance(Connection); var parameters = Parameters.CreateParameters(Sql, UpdateSql, db); var dataResult = db.GetMultipleResults(Connection, Sql, parameters); if (dataResult.Count == 0) return null; if (detailReport != null) { var table = dataResult.First(); table.Columns.Add(new DataColumn("detailurl")); var headers = table.Columns.OfType<DataColumn>().Select(x => x.ColumnName).ToArray(); foreach (DataRow tableRow in table.Rows) { tableRow["detailurl"] = DetailReportUrlHelper.GetUrl(this, detailReport, headers, tableRow.ItemArray.Select(x => x.ToString()).ToArray()); } } var result = ResultFactory.GetInstance(this, template); return result.Render(dataResult); } public Result.Result ExecuteWithTemplateWithoutRendering(Template template, Report detailReport = null) { if (Connection == null) throw new Exception("Missing Connection in report"); var db = DbExecutorFactory.GetInstance(Connection); var parameters = Parameters.CreateParameters(Sql, UpdateSql, db); var dataResult = db.GetMultipleResults(Connection, Sql, parameters); if (dataResult.Count == 0) return null; if (detailReport != null) { var table = dataResult.First(); table.Columns.Add(new DataColumn("detailurl")); var headers = table.Columns.OfType<DataColumn>().Select(x => x.ColumnName).ToArray(); foreach (DataRow tableRow in table.Rows) { tableRow["detailurl"] = DetailReportUrlHelper.GetUrl(this, detailReport, headers, tableRow.ItemArray.Select(x => x.ToString()).ToArray()); } } var result = ResultFactory.GetInstance(this, template); return result; } public void UpdateSql(string sql) { //some parameters need to modify the sql to work, like when we have an in-clause and need to replace one param with many. Sql = sql; } private string Stringify(object obj) { if (obj is DateTime) return ((DateTime)obj).ToString("yyyy-MM-dd HH:mm:ss"); return obj.ToString(); } public bool IsMasterDetailReport() { string pattern = @"(?<!\()select"; var result = Regex.Matches(this.Sql, pattern); string mergeIdPattern = @"merge_id"; var mergeResult = Regex.Matches(this.Sql, mergeIdPattern); return result.Count > 1 && mergeResult.Count >= 2; } } }
{ "content_hash": "10aa81943f3621c513b3cf9d1be5c77c", "timestamp": "", "source": "github", "line_count": 204, "max_line_length": 217, "avg_line_length": 36.86274509803921, "alnum_prop": 0.6121010638297872, "repo_name": "tronelius/simplereport", "id": "caf1b9dfb01ea35c120166ced928e79de0c861b4", "size": "7522", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SimpleReport.Model/Report.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP.NET", "bytes": "103" }, { "name": "C#", "bytes": "296246" }, { "name": "CSS", "bytes": "165838" }, { "name": "HTML", "bytes": "110801" }, { "name": "JavaScript", "bytes": "151458" }, { "name": "PowerShell", "bytes": "1510" } ], "symlink_target": "" }
package org.elasticsearch.recovery; import org.apache.lucene.util.LuceneTestCase.Slow; import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequestBuilder; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.common.Priority; import org.elasticsearch.common.collect.MapBuilder; import org.elasticsearch.test.ElasticsearchIntegrationTest; import org.elasticsearch.test.ElasticsearchIntegrationTest.ClusterScope; import org.elasticsearch.test.junit.annotations.TestLogging; import org.junit.Test; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.test.ElasticsearchIntegrationTest.Scope; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount; /** * */ @ClusterScope(scope = Scope.TEST, numDataNodes = 0, transportClientRatio = 0.0) public class FullRollingRestartTests extends ElasticsearchIntegrationTest { protected void assertTimeout(ClusterHealthRequestBuilder requestBuilder) { ClusterHealthResponse clusterHealth = requestBuilder.get(); if (clusterHealth.isTimedOut()) { logger.info("cluster health request timed out:\n{}", clusterHealth); fail("cluster health request timed out"); } } @Override protected int numberOfReplicas() { return 1; } @Test @Slow @TestLogging("indices.cluster:TRACE,cluster.service:TRACE,action.search:TRACE,indices.recovery:TRACE") public void testFullRollingRestart() throws Exception { internalCluster().startNode(); createIndex("test"); for (int i = 0; i < 1000; i++) { client().prepareIndex("test", "type1", Long.toString(i)) .setSource(MapBuilder.<String, Object>newMapBuilder().put("test", "value" + i).map()).execute().actionGet(); } flush(); for (int i = 1000; i < 2000; i++) { client().prepareIndex("test", "type1", Long.toString(i)) .setSource(MapBuilder.<String, Object>newMapBuilder().put("test", "value" + i).map()).execute().actionGet(); } // now start adding nodes internalCluster().startNodesAsync(2).get(); // make sure the cluster state is green, and all has been recovered assertTimeout(client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setTimeout("1m").setWaitForGreenStatus().setWaitForRelocatingShards(0).setWaitForNodes("3")); // now start adding nodes internalCluster().startNodesAsync(2).get(); // We now have 5 nodes setMinimumMasterNodes(3); // make sure the cluster state is green, and all has been recovered assertTimeout(client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setTimeout("1m").setWaitForGreenStatus().setWaitForRelocatingShards(0).setWaitForNodes("5")); refresh(); for (int i = 0; i < 10; i++) { assertHitCount(client().prepareCount().setQuery(matchAllQuery()).get(), 2000l); } // now start shutting nodes down internalCluster().stopRandomDataNode(); // make sure the cluster state is green, and all has been recovered assertTimeout(client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setTimeout("1m").setWaitForGreenStatus().setWaitForRelocatingShards(0).setWaitForNodes("4")); // going down to 3 nodes. note that the min_master_node may not be in effect when we shutdown the 4th // node, but that's OK as it is set to 3 before. setMinimumMasterNodes(2); internalCluster().stopRandomDataNode(); // make sure the cluster state is green, and all has been recovered assertTimeout(client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setTimeout("1m").setWaitForGreenStatus().setWaitForRelocatingShards(0).setWaitForNodes("3")); refresh(); for (int i = 0; i < 10; i++) { assertHitCount(client().prepareCount().setQuery(matchAllQuery()).get(), 2000l); } // closing the 3rd node internalCluster().stopRandomDataNode(); // make sure the cluster state is green, and all has been recovered assertTimeout(client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setTimeout("1m").setWaitForGreenStatus().setWaitForRelocatingShards(0).setWaitForNodes("2")); // closing the 2nd node setMinimumMasterNodes(1); internalCluster().stopRandomDataNode(); // make sure the cluster state is green, and all has been recovered assertTimeout(client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setTimeout("1m").setWaitForYellowStatus().setWaitForRelocatingShards(0).setWaitForNodes("1")); refresh(); for (int i = 0; i < 10; i++) { assertHitCount(client().prepareCount().setQuery(matchAllQuery()).get(), 2000l); } } }
{ "content_hash": "f7902478ab595a8f28291d938929bcb7", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 194, "avg_line_length": 46.28440366972477, "alnum_prop": 0.6909811694747274, "repo_name": "kagel/elasticsearch", "id": "94121d71a639e75d8f5134b22037b940337a1e6d", "size": "5833", "binary": false, "copies": "12", "ref": "refs/heads/master", "path": "src/test/java/org/elasticsearch/recovery/FullRollingRestartTests.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Zebra_Cookie examples</title> <link rel="stylesheet" href="public/css/reset.css" type="text/css"> <link rel="stylesheet" href="public/css/style.css" type="text/css"> <link rel="stylesheet" href="libraries/syntaxhighlighter/public/css/shCoreDefault.css" type="text/css"> <script type="text/javascript" src="public/javascript/jquery-1.7.2.js"></script> <script type="text/javascript" src="../public/javascript/zebra_cookie.js"></script> <script type="text/javascript" src="public/javascript/core.js"></script> <script type="text/javascript" src="libraries/syntaxhighlighter/public/javascript/shCore.js"></script> <script type="text/javascript" src="libraries/syntaxhighlighter/public/javascript/shBrushJScript.js"></script> <script type="text/javascript" src="libraries/syntaxhighlighter/public/javascript/shBrushXml.js"></script> <script type="text/javascript" src="libraries/syntaxhighlighter/public/javascript/shBrushCSS.js"></script> <script type="text/javascript"> SyntaxHighlighter.defaults['toolbar'] = false; SyntaxHighlighter.all(); </script> </head> <body> <div class="main-wrapper"> <h2>Zebra_Cookie examples</h2> <h4>Installation</h4> <p>Load the latest version of jQuery either from a local source, or from a CDN</p> <pre class="brush:html"> &lt;script type="text/javascript" src="path/to/jQuery.js"&gt;&lt;/script&gt; </pre> <p>Load the Zebra_Cookie plugin</p> <pre class="brush:html"> &lt;script type="text/javascript" src="path/to/zebra_cookie.js"&gt;&lt;/script&gt; </pre> <div class="hr"></div> <h4>Usage</h4> <pre class="brush:javascript"> // inside the DOM-ready function // a "cookie" object will be available in jQuery&rsquo;s namespace // the object exposes 3 methods that you can use to write, read and delete cookies $(document).ready(function() { // create a session cookie (expires when the browser closes) $.cookie.write('cookie_name', 'cookie_value'); // create a cookie that expires in 1 day $.cookie.write('cookie_name', 'cookie_value', 24 * 60 * 60); // read a cookie&rsquo;s value // following the examples above, this should return "cookie_value" $.cookie.read('cookie_name'); // the "read" method returns null if the cookie doesn&rsquo;t exist $.cookie.read('non_existing_cookie_name'); // delete the cookie $.cookie.destroy('cookie_name'); }); </pre> </div> </body> </html>
{ "content_hash": "ca9d3e57000e2f3a0a4b2c90f57cf2c6", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 118, "avg_line_length": 35.345238095238095, "alnum_prop": 0.5880767935331761, "repo_name": "hehongwei44/Project-FE", "id": "84c1fbd70003f89aafb24e6d18f23e91805755da", "size": "2969", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Cookie/examples/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "21409" }, { "name": "ActionScript", "bytes": "102969" }, { "name": "Batchfile", "bytes": "110" }, { "name": "C#", "bytes": "9776" }, { "name": "CSS", "bytes": "356472" }, { "name": "HTML", "bytes": "1185994" }, { "name": "Java", "bytes": "3336" }, { "name": "JavaScript", "bytes": "1987997" }, { "name": "PHP", "bytes": "86791" }, { "name": "Visual Basic", "bytes": "18823" } ], "symlink_target": "" }
using System; namespace UniqueList { ///Signals if one tried to get value from the null reference while working with List. [Serializable] public class ListNullException : Exception { public ListNullException() { } public ListNullException(string message) : base(message) { } public ListNullException(string message, Exception inner) : base(message, inner) { } protected ListNullException( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } } [Serializable] public class ListOverloadException : Exception { public ListOverloadException() { } public ListOverloadException(string message) : base(message) { } public ListOverloadException(string message, Exception inner) : base(message, inner) { } protected ListOverloadException( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } } [Serializable] public class UniqueListAddExisting : Exception { public UniqueListAddExisting() { } public UniqueListAddExisting(string message) : base(message) { } public UniqueListAddExisting(string message, Exception inner) : base(message, inner) { } protected UniqueListAddExisting( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } } [Serializable] public class UniqueListDeleteStrange : Exception { public UniqueListDeleteStrange() { } public UniqueListDeleteStrange(string message) : base(message) { } public UniqueListDeleteStrange(string message, Exception inner) : base(message, inner) { } protected UniqueListDeleteStrange( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } } }
{ "content_hash": "9c951ea0ec46700c8b3cc9a11d15676f", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 89, "avg_line_length": 34.43076923076923, "alnum_prop": 0.6501340482573726, "repo_name": "alexander-bzikadze/University_tasks", "id": "c90fced34b8f09ea4e2e3334ab80cd18263e1cf0", "size": "2238", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Semester_2/4.2/ArrayListExceptions.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "305" }, { "name": "C", "bytes": "79" }, { "name": "C#", "bytes": "183014" }, { "name": "C++", "bytes": "161341" }, { "name": "F#", "bytes": "74082" }, { "name": "Makefile", "bytes": "7846" }, { "name": "QMake", "bytes": "707" }, { "name": "Shell", "bytes": "1967" }, { "name": "TeX", "bytes": "2490" } ], "symlink_target": "" }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/datastore/v1/query.proto package com.google.datastore.v1; /** * <pre> * A holder for any type of filter. * </pre> * * Protobuf type {@code google.datastore.v1.Filter} */ public final class Filter extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.datastore.v1.Filter) FilterOrBuilder { // Use Filter.newBuilder() to construct. private Filter(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private Filter() { } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private Filter( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); int mutable_bitField0_ = 0; try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!input.skipField(tag)) { done = true; } break; } case 10: { com.google.datastore.v1.CompositeFilter.Builder subBuilder = null; if (filterTypeCase_ == 1) { subBuilder = ((com.google.datastore.v1.CompositeFilter) filterType_).toBuilder(); } filterType_ = input.readMessage(com.google.datastore.v1.CompositeFilter.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((com.google.datastore.v1.CompositeFilter) filterType_); filterType_ = subBuilder.buildPartial(); } filterTypeCase_ = 1; break; } case 18: { com.google.datastore.v1.PropertyFilter.Builder subBuilder = null; if (filterTypeCase_ == 2) { subBuilder = ((com.google.datastore.v1.PropertyFilter) filterType_).toBuilder(); } filterType_ = input.readMessage(com.google.datastore.v1.PropertyFilter.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((com.google.datastore.v1.PropertyFilter) filterType_); filterType_ = subBuilder.buildPartial(); } filterTypeCase_ = 2; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.datastore.v1.QueryProto.internal_static_google_datastore_v1_Filter_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.datastore.v1.QueryProto.internal_static_google_datastore_v1_Filter_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.datastore.v1.Filter.class, com.google.datastore.v1.Filter.Builder.class); } private int filterTypeCase_ = 0; private java.lang.Object filterType_; public enum FilterTypeCase implements com.google.protobuf.Internal.EnumLite { COMPOSITE_FILTER(1), PROPERTY_FILTER(2), FILTERTYPE_NOT_SET(0); private final int value; private FilterTypeCase(int value) { this.value = value; } /** * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static FilterTypeCase valueOf(int value) { return forNumber(value); } public static FilterTypeCase forNumber(int value) { switch (value) { case 1: return COMPOSITE_FILTER; case 2: return PROPERTY_FILTER; case 0: return FILTERTYPE_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public FilterTypeCase getFilterTypeCase() { return FilterTypeCase.forNumber( filterTypeCase_); } public static final int COMPOSITE_FILTER_FIELD_NUMBER = 1; /** * <pre> * A composite filter. * </pre> * * <code>optional .google.datastore.v1.CompositeFilter composite_filter = 1;</code> */ public com.google.datastore.v1.CompositeFilter getCompositeFilter() { if (filterTypeCase_ == 1) { return (com.google.datastore.v1.CompositeFilter) filterType_; } return com.google.datastore.v1.CompositeFilter.getDefaultInstance(); } /** * <pre> * A composite filter. * </pre> * * <code>optional .google.datastore.v1.CompositeFilter composite_filter = 1;</code> */ public com.google.datastore.v1.CompositeFilterOrBuilder getCompositeFilterOrBuilder() { if (filterTypeCase_ == 1) { return (com.google.datastore.v1.CompositeFilter) filterType_; } return com.google.datastore.v1.CompositeFilter.getDefaultInstance(); } public static final int PROPERTY_FILTER_FIELD_NUMBER = 2; /** * <pre> * A filter on a property. * </pre> * * <code>optional .google.datastore.v1.PropertyFilter property_filter = 2;</code> */ public com.google.datastore.v1.PropertyFilter getPropertyFilter() { if (filterTypeCase_ == 2) { return (com.google.datastore.v1.PropertyFilter) filterType_; } return com.google.datastore.v1.PropertyFilter.getDefaultInstance(); } /** * <pre> * A filter on a property. * </pre> * * <code>optional .google.datastore.v1.PropertyFilter property_filter = 2;</code> */ public com.google.datastore.v1.PropertyFilterOrBuilder getPropertyFilterOrBuilder() { if (filterTypeCase_ == 2) { return (com.google.datastore.v1.PropertyFilter) filterType_; } return com.google.datastore.v1.PropertyFilter.getDefaultInstance(); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (filterTypeCase_ == 1) { output.writeMessage(1, (com.google.datastore.v1.CompositeFilter) filterType_); } if (filterTypeCase_ == 2) { output.writeMessage(2, (com.google.datastore.v1.PropertyFilter) filterType_); } } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (filterTypeCase_ == 1) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, (com.google.datastore.v1.CompositeFilter) filterType_); } if (filterTypeCase_ == 2) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, (com.google.datastore.v1.PropertyFilter) filterType_); } memoizedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.datastore.v1.Filter)) { return super.equals(obj); } com.google.datastore.v1.Filter other = (com.google.datastore.v1.Filter) obj; boolean result = true; result = result && getFilterTypeCase().equals( other.getFilterTypeCase()); if (!result) return false; switch (filterTypeCase_) { case 1: result = result && getCompositeFilter() .equals(other.getCompositeFilter()); break; case 2: result = result && getPropertyFilter() .equals(other.getPropertyFilter()); break; case 0: default: } return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptorForType().hashCode(); switch (filterTypeCase_) { case 1: hash = (37 * hash) + COMPOSITE_FILTER_FIELD_NUMBER; hash = (53 * hash) + getCompositeFilter().hashCode(); break; case 2: hash = (37 * hash) + PROPERTY_FILTER_FIELD_NUMBER; hash = (53 * hash) + getPropertyFilter().hashCode(); break; case 0: default: } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.datastore.v1.Filter parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.datastore.v1.Filter parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.datastore.v1.Filter parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.datastore.v1.Filter parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.datastore.v1.Filter parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.datastore.v1.Filter parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.datastore.v1.Filter parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.datastore.v1.Filter parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.datastore.v1.Filter parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.datastore.v1.Filter parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.datastore.v1.Filter prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * A holder for any type of filter. * </pre> * * Protobuf type {@code google.datastore.v1.Filter} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.datastore.v1.Filter) com.google.datastore.v1.FilterOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.datastore.v1.QueryProto.internal_static_google_datastore_v1_Filter_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.datastore.v1.QueryProto.internal_static_google_datastore_v1_Filter_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.datastore.v1.Filter.class, com.google.datastore.v1.Filter.Builder.class); } // Construct using com.google.datastore.v1.Filter.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); filterTypeCase_ = 0; filterType_ = null; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.datastore.v1.QueryProto.internal_static_google_datastore_v1_Filter_descriptor; } public com.google.datastore.v1.Filter getDefaultInstanceForType() { return com.google.datastore.v1.Filter.getDefaultInstance(); } public com.google.datastore.v1.Filter build() { com.google.datastore.v1.Filter result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public com.google.datastore.v1.Filter buildPartial() { com.google.datastore.v1.Filter result = new com.google.datastore.v1.Filter(this); if (filterTypeCase_ == 1) { if (compositeFilterBuilder_ == null) { result.filterType_ = filterType_; } else { result.filterType_ = compositeFilterBuilder_.build(); } } if (filterTypeCase_ == 2) { if (propertyFilterBuilder_ == null) { result.filterType_ = filterType_; } else { result.filterType_ = propertyFilterBuilder_.build(); } } result.filterTypeCase_ = filterTypeCase_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.datastore.v1.Filter) { return mergeFrom((com.google.datastore.v1.Filter)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.datastore.v1.Filter other) { if (other == com.google.datastore.v1.Filter.getDefaultInstance()) return this; switch (other.getFilterTypeCase()) { case COMPOSITE_FILTER: { mergeCompositeFilter(other.getCompositeFilter()); break; } case PROPERTY_FILTER: { mergePropertyFilter(other.getPropertyFilter()); break; } case FILTERTYPE_NOT_SET: { break; } } onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.datastore.v1.Filter parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.datastore.v1.Filter) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int filterTypeCase_ = 0; private java.lang.Object filterType_; public FilterTypeCase getFilterTypeCase() { return FilterTypeCase.forNumber( filterTypeCase_); } public Builder clearFilterType() { filterTypeCase_ = 0; filterType_ = null; onChanged(); return this; } private com.google.protobuf.SingleFieldBuilderV3< com.google.datastore.v1.CompositeFilter, com.google.datastore.v1.CompositeFilter.Builder, com.google.datastore.v1.CompositeFilterOrBuilder> compositeFilterBuilder_; /** * <pre> * A composite filter. * </pre> * * <code>optional .google.datastore.v1.CompositeFilter composite_filter = 1;</code> */ public com.google.datastore.v1.CompositeFilter getCompositeFilter() { if (compositeFilterBuilder_ == null) { if (filterTypeCase_ == 1) { return (com.google.datastore.v1.CompositeFilter) filterType_; } return com.google.datastore.v1.CompositeFilter.getDefaultInstance(); } else { if (filterTypeCase_ == 1) { return compositeFilterBuilder_.getMessage(); } return com.google.datastore.v1.CompositeFilter.getDefaultInstance(); } } /** * <pre> * A composite filter. * </pre> * * <code>optional .google.datastore.v1.CompositeFilter composite_filter = 1;</code> */ public Builder setCompositeFilter(com.google.datastore.v1.CompositeFilter value) { if (compositeFilterBuilder_ == null) { if (value == null) { throw new NullPointerException(); } filterType_ = value; onChanged(); } else { compositeFilterBuilder_.setMessage(value); } filterTypeCase_ = 1; return this; } /** * <pre> * A composite filter. * </pre> * * <code>optional .google.datastore.v1.CompositeFilter composite_filter = 1;</code> */ public Builder setCompositeFilter( com.google.datastore.v1.CompositeFilter.Builder builderForValue) { if (compositeFilterBuilder_ == null) { filterType_ = builderForValue.build(); onChanged(); } else { compositeFilterBuilder_.setMessage(builderForValue.build()); } filterTypeCase_ = 1; return this; } /** * <pre> * A composite filter. * </pre> * * <code>optional .google.datastore.v1.CompositeFilter composite_filter = 1;</code> */ public Builder mergeCompositeFilter(com.google.datastore.v1.CompositeFilter value) { if (compositeFilterBuilder_ == null) { if (filterTypeCase_ == 1 && filterType_ != com.google.datastore.v1.CompositeFilter.getDefaultInstance()) { filterType_ = com.google.datastore.v1.CompositeFilter.newBuilder((com.google.datastore.v1.CompositeFilter) filterType_) .mergeFrom(value).buildPartial(); } else { filterType_ = value; } onChanged(); } else { if (filterTypeCase_ == 1) { compositeFilterBuilder_.mergeFrom(value); } compositeFilterBuilder_.setMessage(value); } filterTypeCase_ = 1; return this; } /** * <pre> * A composite filter. * </pre> * * <code>optional .google.datastore.v1.CompositeFilter composite_filter = 1;</code> */ public Builder clearCompositeFilter() { if (compositeFilterBuilder_ == null) { if (filterTypeCase_ == 1) { filterTypeCase_ = 0; filterType_ = null; onChanged(); } } else { if (filterTypeCase_ == 1) { filterTypeCase_ = 0; filterType_ = null; } compositeFilterBuilder_.clear(); } return this; } /** * <pre> * A composite filter. * </pre> * * <code>optional .google.datastore.v1.CompositeFilter composite_filter = 1;</code> */ public com.google.datastore.v1.CompositeFilter.Builder getCompositeFilterBuilder() { return getCompositeFilterFieldBuilder().getBuilder(); } /** * <pre> * A composite filter. * </pre> * * <code>optional .google.datastore.v1.CompositeFilter composite_filter = 1;</code> */ public com.google.datastore.v1.CompositeFilterOrBuilder getCompositeFilterOrBuilder() { if ((filterTypeCase_ == 1) && (compositeFilterBuilder_ != null)) { return compositeFilterBuilder_.getMessageOrBuilder(); } else { if (filterTypeCase_ == 1) { return (com.google.datastore.v1.CompositeFilter) filterType_; } return com.google.datastore.v1.CompositeFilter.getDefaultInstance(); } } /** * <pre> * A composite filter. * </pre> * * <code>optional .google.datastore.v1.CompositeFilter composite_filter = 1;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.datastore.v1.CompositeFilter, com.google.datastore.v1.CompositeFilter.Builder, com.google.datastore.v1.CompositeFilterOrBuilder> getCompositeFilterFieldBuilder() { if (compositeFilterBuilder_ == null) { if (!(filterTypeCase_ == 1)) { filterType_ = com.google.datastore.v1.CompositeFilter.getDefaultInstance(); } compositeFilterBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.datastore.v1.CompositeFilter, com.google.datastore.v1.CompositeFilter.Builder, com.google.datastore.v1.CompositeFilterOrBuilder>( (com.google.datastore.v1.CompositeFilter) filterType_, getParentForChildren(), isClean()); filterType_ = null; } filterTypeCase_ = 1; onChanged();; return compositeFilterBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< com.google.datastore.v1.PropertyFilter, com.google.datastore.v1.PropertyFilter.Builder, com.google.datastore.v1.PropertyFilterOrBuilder> propertyFilterBuilder_; /** * <pre> * A filter on a property. * </pre> * * <code>optional .google.datastore.v1.PropertyFilter property_filter = 2;</code> */ public com.google.datastore.v1.PropertyFilter getPropertyFilter() { if (propertyFilterBuilder_ == null) { if (filterTypeCase_ == 2) { return (com.google.datastore.v1.PropertyFilter) filterType_; } return com.google.datastore.v1.PropertyFilter.getDefaultInstance(); } else { if (filterTypeCase_ == 2) { return propertyFilterBuilder_.getMessage(); } return com.google.datastore.v1.PropertyFilter.getDefaultInstance(); } } /** * <pre> * A filter on a property. * </pre> * * <code>optional .google.datastore.v1.PropertyFilter property_filter = 2;</code> */ public Builder setPropertyFilter(com.google.datastore.v1.PropertyFilter value) { if (propertyFilterBuilder_ == null) { if (value == null) { throw new NullPointerException(); } filterType_ = value; onChanged(); } else { propertyFilterBuilder_.setMessage(value); } filterTypeCase_ = 2; return this; } /** * <pre> * A filter on a property. * </pre> * * <code>optional .google.datastore.v1.PropertyFilter property_filter = 2;</code> */ public Builder setPropertyFilter( com.google.datastore.v1.PropertyFilter.Builder builderForValue) { if (propertyFilterBuilder_ == null) { filterType_ = builderForValue.build(); onChanged(); } else { propertyFilterBuilder_.setMessage(builderForValue.build()); } filterTypeCase_ = 2; return this; } /** * <pre> * A filter on a property. * </pre> * * <code>optional .google.datastore.v1.PropertyFilter property_filter = 2;</code> */ public Builder mergePropertyFilter(com.google.datastore.v1.PropertyFilter value) { if (propertyFilterBuilder_ == null) { if (filterTypeCase_ == 2 && filterType_ != com.google.datastore.v1.PropertyFilter.getDefaultInstance()) { filterType_ = com.google.datastore.v1.PropertyFilter.newBuilder((com.google.datastore.v1.PropertyFilter) filterType_) .mergeFrom(value).buildPartial(); } else { filterType_ = value; } onChanged(); } else { if (filterTypeCase_ == 2) { propertyFilterBuilder_.mergeFrom(value); } propertyFilterBuilder_.setMessage(value); } filterTypeCase_ = 2; return this; } /** * <pre> * A filter on a property. * </pre> * * <code>optional .google.datastore.v1.PropertyFilter property_filter = 2;</code> */ public Builder clearPropertyFilter() { if (propertyFilterBuilder_ == null) { if (filterTypeCase_ == 2) { filterTypeCase_ = 0; filterType_ = null; onChanged(); } } else { if (filterTypeCase_ == 2) { filterTypeCase_ = 0; filterType_ = null; } propertyFilterBuilder_.clear(); } return this; } /** * <pre> * A filter on a property. * </pre> * * <code>optional .google.datastore.v1.PropertyFilter property_filter = 2;</code> */ public com.google.datastore.v1.PropertyFilter.Builder getPropertyFilterBuilder() { return getPropertyFilterFieldBuilder().getBuilder(); } /** * <pre> * A filter on a property. * </pre> * * <code>optional .google.datastore.v1.PropertyFilter property_filter = 2;</code> */ public com.google.datastore.v1.PropertyFilterOrBuilder getPropertyFilterOrBuilder() { if ((filterTypeCase_ == 2) && (propertyFilterBuilder_ != null)) { return propertyFilterBuilder_.getMessageOrBuilder(); } else { if (filterTypeCase_ == 2) { return (com.google.datastore.v1.PropertyFilter) filterType_; } return com.google.datastore.v1.PropertyFilter.getDefaultInstance(); } } /** * <pre> * A filter on a property. * </pre> * * <code>optional .google.datastore.v1.PropertyFilter property_filter = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.datastore.v1.PropertyFilter, com.google.datastore.v1.PropertyFilter.Builder, com.google.datastore.v1.PropertyFilterOrBuilder> getPropertyFilterFieldBuilder() { if (propertyFilterBuilder_ == null) { if (!(filterTypeCase_ == 2)) { filterType_ = com.google.datastore.v1.PropertyFilter.getDefaultInstance(); } propertyFilterBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.datastore.v1.PropertyFilter, com.google.datastore.v1.PropertyFilter.Builder, com.google.datastore.v1.PropertyFilterOrBuilder>( (com.google.datastore.v1.PropertyFilter) filterType_, getParentForChildren(), isClean()); filterType_ = null; } filterTypeCase_ = 2; onChanged();; return propertyFilterBuilder_; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return this; } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return this; } // @@protoc_insertion_point(builder_scope:google.datastore.v1.Filter) } // @@protoc_insertion_point(class_scope:google.datastore.v1.Filter) private static final com.google.datastore.v1.Filter DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.datastore.v1.Filter(); } public static com.google.datastore.v1.Filter getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<Filter> PARSER = new com.google.protobuf.AbstractParser<Filter>() { public Filter parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Filter(input, extensionRegistry); } }; public static com.google.protobuf.Parser<Filter> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<Filter> getParserForType() { return PARSER; } public com.google.datastore.v1.Filter getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
{ "content_hash": "40da28f127a50c49f72be24ee2f27285", "timestamp": "", "source": "github", "line_count": 907, "max_line_length": 172, "avg_line_length": 33.291069459757445, "alnum_prop": 0.6461665838715019, "repo_name": "speedycontrol/googleapis", "id": "2d9a3a97724367d358f424193f135de7008e8e93", "size": "30195", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "output/com/google/datastore/v1/Filter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1569787" }, { "name": "Makefile", "bytes": "1301" }, { "name": "Protocol Buffer", "bytes": "1085800" } ], "symlink_target": "" }
Scenario: you created a feature branch, rebased history nicely, and then wanted to deploy a debug version full of prints to stdout; afterwards, you want to remove that last commit so that there's no rubbish in the code and in stdout anymore. And you don't really care about git history: removing one commit from it is okay as long as it happens in a feature branch and not in master. Solution: ```bash # make sure that local branch is in sync with its counterpart in remote repo git reset HEAD^ --hard git push -f ``` Done. Gone is the HEAD commit. Use responsibly.
{ "content_hash": "81bf6958358faa8c9a1076eeea46f16a", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 383, "avg_line_length": 43.84615384615385, "alnum_prop": 0.7684210526315789, "repo_name": "taxigy/til", "id": "8f243b74bafa6239014b79ae7c562a205813fea6", "size": "621", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "git/remove-last-commit-from-history.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
from django import forms from django.http import HttpResponse from django.shortcuts import redirect from django.template.response import TemplateResponse from django.utils.translation import gettext_lazy from wagtail.admin import messages from wagtail.admin.auth import user_passes_test from wagtail.admin.views.generic import DeleteView, EditView, IndexView from wagtail.contrib.forms.views import SubmissionsListView from .models import ModelWithStringTypePrimaryKey def user_is_called_bob(user): return user.first_name == "Bob" @user_passes_test(user_is_called_bob) def bob_only_zone(request): return HttpResponse("Bobs of the world unite!") def message_test(request): if request.method == "POST": fn = getattr(messages, request.POST["level"]) fn(request, request.POST["message"]) return redirect("testapp_message_test") else: return TemplateResponse(request, "wagtailadmin/base.html") class CustomSubmissionsListView(SubmissionsListView): paginate_by = 50 ordering = ("submit_time",) ordering_csv = ("-submit_time",) def get_csv_filename(self): """Returns the filename for CSV file with page title at start""" filename = super().get_csv_filename() return self.form_page.slug + "-" + filename class TestIndexView(IndexView): model = ModelWithStringTypePrimaryKey index_url_name = "testapp_generic_index" template_name = "tests/generic_view_templates/index.html" paginate_by = 20 context_object_name = "test_object" page_title = gettext_lazy("test index view") class CustomModelEditForm(forms.ModelForm): class Meta: model = ModelWithStringTypePrimaryKey fields = ("content",) class TestEditView(EditView): model = ModelWithStringTypePrimaryKey context_object_name = "test_object" template_name = "tests/generic_view_templates/edit.html" index_url_name = "testapp_generic_index" success_url = "testapp_generic_index" edit_url_name = "testapp_generic_edit" delete_url_name = "testapp_generic_delete" form_class = CustomModelEditForm success_message = "User '{0}' updated." page_title = gettext_lazy("test edit view") class TestDeleteView(DeleteView): model = ModelWithStringTypePrimaryKey context_object_name = "test_object" template_name = "tests/generic_view_templates/delete.html" index_url_name = "testapp_generic_index" edit_url_name = "testapp_generic_edit" delete_url_name = "testapp_generic_delete" success_message = "User '{0}' updated." page_title = gettext_lazy("test delete view")
{ "content_hash": "1c09542e579b37ff7413205a19119953", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 72, "avg_line_length": 31.566265060240966, "alnum_prop": 0.7179389312977099, "repo_name": "zerolab/wagtail", "id": "cca5129b86d6e7fe4eabdd36dfc2b96022d6e553", "size": "2620", "binary": false, "copies": "4", "ref": "refs/heads/main", "path": "wagtail/test/testapp/views.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "2522" }, { "name": "Dockerfile", "bytes": "2041" }, { "name": "HTML", "bytes": "593037" }, { "name": "JavaScript", "bytes": "615631" }, { "name": "Makefile", "bytes": "1413" }, { "name": "Python", "bytes": "6560334" }, { "name": "SCSS", "bytes": "219204" }, { "name": "Shell", "bytes": "6845" }, { "name": "TypeScript", "bytes": "288102" } ], "symlink_target": "" }
coming soon... ## Example: python src/main.py -i example/example.vcf -o example/example.tab
{ "content_hash": "2babd6a74509eff812bda974426e0c0e", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 64, "avg_line_length": 18.8, "alnum_prop": 0.723404255319149, "repo_name": "khalidm/vcf2tab", "id": "f078269eca29cae57925b08457e4ee04392fc34d", "size": "117", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Python", "bytes": "3741" } ], "symlink_target": "" }
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt using System; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; namespace NUnit.TestUtilities { /// <summary> /// Summary description for ResultSummary. /// </summary> public class ResultSummary { private int resultCount = 0; private int failureCount = 0; private int successCount = 0; private int inconclusiveCount = 0; private int skipCount = 0; private DateTime startTime = DateTime.MinValue; private DateTime endTime = DateTime.MaxValue; private double duration = 0.0d; private string name; public ResultSummary() { } public ResultSummary(ITestResult result) { Summarize(result); } private void Summarize(ITestResult result) { if (name == null) { name = result.Name; startTime = result.StartTime; endTime = result.EndTime; duration = result.Duration; } if (result.HasChildren) { foreach (var childResult in result.Children) Summarize(childResult); } else { resultCount++; switch (result.ResultState.Status) { case TestStatus.Passed: successCount++; break; case TestStatus.Failed: failureCount++; break; case TestStatus.Inconclusive: inconclusiveCount++; break; case TestStatus.Skipped: default: skipCount++; break; } } } public string Name => name; public bool Success => failureCount == 0; /// <summary> /// Returns the number of test cases for which results /// have been summarized. Any tests excluded by use of /// Category or Explicit attributes are not counted. /// </summary> public int ResultCount => resultCount; /// <summary> /// Returns the number of test cases actually run, which /// is the same as ResultCount, less any Skipped, Ignored /// or NonRunnable tests. /// </summary> public int TestsRun => Passed + Failed + Inconclusive; /// <summary> /// Returns the number of tests that passed /// </summary> public int Passed => successCount; /// <summary> /// Returns the number of test cases that failed. /// </summary> public int Failed => failureCount; /// <summary> /// Returns the number of test cases that failed. /// </summary> public int Inconclusive => inconclusiveCount; /// <summary> /// Returns the number of test cases that were skipped. /// </summary> public int Skipped => skipCount; /// <summary> /// Gets the start time of the test run. /// </summary> public DateTime StartTime => startTime; /// <summary> /// Gets the end time of the test run. /// </summary> public DateTime EndTime => endTime; /// <summary> /// Gets the duration of the test run in seconds. /// </summary> public double Duration => duration; } }
{ "content_hash": "b324fd4e0a25c7a995f324b59e74ff7f", "timestamp": "", "source": "github", "line_count": 123, "max_line_length": 91, "avg_line_length": 29.59349593495935, "alnum_prop": 0.514010989010989, "repo_name": "nunit/nunit", "id": "deb39dffa7fcd6eb1ee39744d5f811f21b53a903", "size": "3642", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/NUnitFramework/tests/TestUtilities/ResultSummary.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "48" }, { "name": "C#", "bytes": "3788586" }, { "name": "F#", "bytes": "1295" }, { "name": "PowerShell", "bytes": "319" }, { "name": "Shell", "bytes": "258" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "e84aec19d778915a25bb9d0a1f4c64e8", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "7c8d3ba13a520239383f0e74d4a40b96b9601419", "size": "190", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Simira/Simira mollis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
'use strict'; var Hapi = require('hapi'); var config = require('./config'); var server = new Hapi.Server(); var schoolService = require('./index'); server.connection({ port:config.SERVER_PORT, routes:{cors:{credentials:true}} }); server.register([ { register: schoolService, options: {} } ], function(err) { if (err) { console.error('Failed to load a plugin:', err); } }); function startServer() { server.start(function() { console.log('Server running at:', server.info.uri); }); } function stopServer() { server.stop(function() { console.log('Server stopped'); }); } module.exports.start = startServer; module.exports.stop = stopServer;
{ "content_hash": "8a806bce039dedbb073933830ae6f74a", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 55, "avg_line_length": 18.026315789473685, "alnum_prop": 0.6467153284671533, "repo_name": "zrrrzzt/tfk-api-schools", "id": "78b86ba7b54429db86a57a07a60f47196f9c2c89", "size": "685", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "6384" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "36aabe9756d885911557518d304017d1", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "c2c5b52bcf13059339f3a316f4ee431e35b4fd6f", "size": "161", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Brassicales/Resedaceae/Luteola/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package typeinfo;//: typeinfo/Position.java class Position { private String title; private Person person; public Position(String jobTitle, Person employee) { title = jobTitle; person = employee; if(person == null) person = Person.NULL; } public Position(String jobTitle) { title = jobTitle; person = Person.NULL; } public String getTitle() { return title; } public void setTitle(String newTitle) { title = newTitle; } public Person getPerson() { return person; } public void setPerson(Person newPerson) { person = newPerson; if(person == null) person = Person.NULL; } public String toString() { return "Position: " + title + " " + person; } } ///:~
{ "content_hash": "13ced819b24474761b4dfb591c678c95", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 53, "avg_line_length": 25.06896551724138, "alnum_prop": 0.6464924346629987, "repo_name": "mayonghui2112/helloWorld", "id": "fd3b1ed8a2c17bb15672a943d7a80b535d80bf9a", "size": "727", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "sourceCode/testMaven/thinkingInJava/src/main/java/typeinfo/Position.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AngelScript", "bytes": "521" }, { "name": "Batchfile", "bytes": "39234" }, { "name": "C", "bytes": "22329" }, { "name": "C++", "bytes": "13466" }, { "name": "CSS", "bytes": "61000" }, { "name": "Go", "bytes": "6819" }, { "name": "Groovy", "bytes": "8821" }, { "name": "HTML", "bytes": "9234922" }, { "name": "Java", "bytes": "21874329" }, { "name": "JavaScript", "bytes": "46483" }, { "name": "NSIS", "bytes": "42042" }, { "name": "Objective-C++", "bytes": "26102" }, { "name": "PLpgSQL", "bytes": "3746" }, { "name": "Perl", "bytes": "13860" }, { "name": "Python", "bytes": "33132" }, { "name": "Shell", "bytes": "51005" }, { "name": "TSQL", "bytes": "50756" }, { "name": "XSLT", "bytes": "38702" } ], "symlink_target": "" }
 namespace RogueMetalicana.Constants.Shop { public class ShopConstants { public const char Symbol = '$'; public static string lastBought { get; set; } public static bool lastSuccess { get; set; } public static void PrintLastShopAction() { if (lastBought==null) { return; } if (lastSuccess) { Visualization.Visualisator.PrintUnderTheBattleField($"You have bought {lastBought} for {Constants.Potions.PotionsConstants.MarketPrice} gold"); } else { Visualization.Visualisator.PrintUnderTheBattleField($"You don't have enought money!"); } } } }
{ "content_hash": "2ba8f2ebc070a7a1f381c166323a15a0", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 159, "avg_line_length": 24.612903225806452, "alnum_prop": 0.546526867627785, "repo_name": "SoftMetalicana/RogueMetalicana", "id": "4275231ddb80ae26b1b9f041c80102b77fbe5d83", "size": "765", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "RogueMetalicana/RogueMetalicana/Constants/Shop/ShopConstants.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "100654" } ], "symlink_target": "" }
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.dialogflow.v3.model; /** * Settings for exporting conversations to [Insights](https://cloud.google.com/contact- * center/insights/docs). * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Dialogflow API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GoogleCloudDialogflowCxV3SecuritySettingsInsightsExportSettings extends com.google.api.client.json.GenericJson { /** * If enabled, we will automatically exports conversations to Insights and Insights runs its * analyzers. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean enableInsightsExport; /** * If enabled, we will automatically exports conversations to Insights and Insights runs its * analyzers. * @return value or {@code null} for none */ public java.lang.Boolean getEnableInsightsExport() { return enableInsightsExport; } /** * If enabled, we will automatically exports conversations to Insights and Insights runs its * analyzers. * @param enableInsightsExport enableInsightsExport or {@code null} for none */ public GoogleCloudDialogflowCxV3SecuritySettingsInsightsExportSettings setEnableInsightsExport(java.lang.Boolean enableInsightsExport) { this.enableInsightsExport = enableInsightsExport; return this; } @Override public GoogleCloudDialogflowCxV3SecuritySettingsInsightsExportSettings set(String fieldName, Object value) { return (GoogleCloudDialogflowCxV3SecuritySettingsInsightsExportSettings) super.set(fieldName, value); } @Override public GoogleCloudDialogflowCxV3SecuritySettingsInsightsExportSettings clone() { return (GoogleCloudDialogflowCxV3SecuritySettingsInsightsExportSettings) super.clone(); } }
{ "content_hash": "e5e9452df7f0bc60372cc10952c3fe14", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 182, "avg_line_length": 39.785714285714285, "alnum_prop": 0.7662477558348294, "repo_name": "googleapis/google-api-java-client-services", "id": "2d607b024864d13eeb860cfea724515615517737", "size": "2785", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "clients/google-api-services-dialogflow/v3/2.0.0/com/google/api/services/dialogflow/v3/model/GoogleCloudDialogflowCxV3SecuritySettingsInsightsExportSettings.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Epilogue &mdash; CasperJS documentation</title> <link rel="stylesheet" href="../_static/basic.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" href="../_static/jsdemo.css" type="text/css" /> <link rel="stylesheet" href="../_static/sphinxcontrib-images/LightBox2/lightbox2/css/lightbox.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../', VERSION: '', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="../_static/jsdemo.js"></script> <script type="text/javascript" src="../_static/sphinxcontrib-images/LightBox2/lightbox2/js/jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../_static/sphinxcontrib-images/LightBox2/lightbox2/js/lightbox.min.js"></script> <script type="text/javascript" src="../_static/sphinxcontrib-images/LightBox2/lightbox2-customize/jquery-noconflict.js"></script> <link rel="shortcut icon" href="../_static/casperjs-favicon.ico"/> <link rel="top" title="CasperJS documentation" href="../index.html" /> <link rel="prev" title="Ontomatica Expertise" href="../15_dir/$_15-ontomatica-expertise.html" /> <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Asap:400,700,400italic,700italic&amp;subset=latin,latin-ext"> <link rel="stylesheet" title="Dark theme" href="../_static/casperjs-dark.css"> <link rel="alternate stylesheet" title="Light theme" href="../_static/casperjs-light.css"> <script type="text/javascript" src="../_static/style-switcher.js"></script> </head> <body role="document"> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../15_dir/$_15-ontomatica-expertise.html" title="Ontomatica Expertise" accesskey="P">previous</a> |</li> <li class="nav-item nav-item-0"><a href="../index.html">CasperJS documentation</a> &raquo;</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="epilogue"> <span id="id1"></span><h1>Epilogue<a class="headerlink" href="#epilogue" title="Permalink to this headline">¶</a></h1> <ul class="simple"> <li>Vegetables are a must on a diet. I suggest carrot cake, zucchini bread, and pumpkin pie. ~Jim Davis</li> <li>There is a lot more juice in grapefruit than meets the eye. ~Author Unknown</li> <li>Sex is good, but not as good as fresh, sweet corn. ~Garrison Keillor</li> <li>Do vegetarians eat animal crackers? ~Author Unknown</li> <li>Shipping is a terrible thing to do to vegetables. They probably get jet-lagged, just like people. ~Elizabeth Berry</li> <li>Red meat is not bad for you. Now blue-green meat, that&#8217;s bad for you! ~Tommy Smothers</li> <li>As a child my family&#8217;s menu consisted of two choices: take it or leave it. ~Buddy Hackett</li> <li>My favorite animal is steak. ~Fran Lebowitz</li> <li>The poets have been mysteriously silent on the subject of cheese. ~G.K. Chesterton</li> <li>In Mexico we have a word for sushi: bait. ~Jose Simons</li> <li>I don&#8217;t think America will have really made it until we have our own salad dressing. Until then we&#8217;re stuck behind the French, Italians, Russians and Caesarians. ~Pat McNelis</li> <li>Chili represents your three stages of matter: solid, liquid, and eventually gas. ~Roseanne Barr</li> <li>A nickel will get you on the subway, but garlic will get you a seat. ~Old New York proverb</li> <li>It&#8217;s bizarre that the produce manager is more important to my children&#8217;s health than the pediatrician. ~Meryl Streep</li> <li>We are living in a world today where lemonade is made from artificial flavors and furniture polish is made from real lemons. ~Alfred E. Newman</li> <li>Hey yogurt, if you&#8217;re so cultured, how come I never see you at the opera? ~Attributed to Stephen Colbert</li> <li>I will not eat oysters. I want my food dead - not sick, not wounded - dead. ~Woody Allen</li> <li>Part of the secret of success in life is to eat what you like and let the food fight it out inside. ~Mark Twain</li> <li>Condensed milk is wonderful. I don&#8217;t see how they can get a cow to sit down on those little cans. ~Fred Allen</li> <li>The most remarkable thing about my mother is that for thirty years she served the family nothing but leftovers. The original meal has never been found. ~Calvin Trillin</li> <li>If you ate pasta and antipasto, would you still be hungry? ~Author Unknown</li> <li>An onion can make people cry, but there has never been a vegetable invented to make them laugh. ~Will Rogers</li> <li>Training is everything. The peach was once a bitter almond; cauliflower is nothing but cabbage with a college education. ~Mark Twain</li> <li>And, of course, the funniest food of all, kumquats. ~George Carlin</li> <li>Pre-heat the oven? Really? If I was the sort of person who planned ahead, I wouldn&#8217;t be eating this Totino&#8217;s Party Pizza in the first place. ~Adam Peterson</li> <li>A fruit is a vegetable with looks and money. Plus, if you let fruit rot, it turns into wine, something Brussels sprouts never do. ~P.J. O&#8217;Rourke</li> <li>Avoid fruit and nuts. You are what you eat. ~Jim Davis</li> <li>I&#8217;m not sure what makes pepperoni so good - if it&#8217;s the pepper or the oni. ~S.A. Sachs</li> <li>Fish is the only food that is considered spoiled once it smells like what it is. ~P.J. O&#8217;Rourke</li> <li>We got married in a fever hotter than a pepper sprout. ~June Carter Cash</li> <li>Welcome to the Church of the Holy Cabbage. Lettuce pray. ~Author Unknown</li> <li>A golfer&#8217;s diet: live on greens as much as possible. ~Author Unknown</li> <li>Let your food be your medicine and your medicine be your food. ~Hippocrates</li> <li>Stressed spelled backwards is desserts. Coincidence? I think not! ~Author Unknown</li> <li>Strength is the capacity to break a chocolate bar into four pieces with your bare hands - and then eat just one of the pieces. ~Judith Viorst</li> <li>There are four basic food groups: milk chocolate, dark chocolate, white chocolate, and chocolate truffles. ~Author Unknown</li> <li>Chocolate is an antidepressant, which is especially useful as you start to gain weight. ~Jason Love</li> <li>I&#8217;ve been on a diet for two weeks and all I&#8217;ve lost is fourteen days. ~Totie Fields</li> <li>I&#8217;m on a seafood diet. I see food and I eat it. ~Author Unknown</li> <li>The biggest seller is cookbooks and the second is diet books - how not to eat what you&#8217;ve just learned how to cook. ~Andy Rooney</li> <li>A balanced diet is a cookie in each hand. ~Author Unknown</li> <li>My doctor told me to stop having intimate dinners for four. Unless there are three other people. ~Orson Welles</li> <li>The only way to lose weight is to check it as airline baggage. ~Peggy Ryan</li> <li>Never eat more than you can lift. ~Miss Piggy</li> <li>Caffeine isn&#8217;t a drug, it&#8217;s a vitamin! ~Author Unknown</li> <li>In Seattle you haven&#8217;t had enough coffee until you can thread a sewing machine while it&#8217;s running. ~Jeff Bezos</li> <li>Ultimate office automation - networked coffee machines. ~Author Unknown</li> <li>Water is the most essential element of life, because without it you can&#8217;t make coffee. ~Author Unknown</li> <li>Vegetarian - that&#8217;s an old Indian word meaning &#8220;lousy hunter.&#8221; ~Andy Rooney</li> <li>If vegetarians eat vegetables, what do humanitarians eat? ~Author Unknown</li> </ul> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h4>Previous topic</h4> <p class="topless"><a href="../15_dir/$_15-ontomatica-expertise.html" title="previous chapter">Ontomatica Expertise</a></p><h3>Index</h3> <p><a href="../genindex.html">Thesaurus</a></p> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../_sources/12_dir/$_12-epilogue.txt" rel="nofollow">Show Source</a></li> </ul> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <form class="search" action="../search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> <p class="searchtip" style="font-size: 90%"> Enter search terms or a module, class or function name. </p> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../15_dir/$_15-ontomatica-expertise.html" title="Ontomatica Expertise" >previous</a> |</li> <li class="nav-item nav-item-0"><a href="../index.html">CasperJS documentation</a> &raquo;</li> </ul> </div> <div class="footer" role="contentinfo"> &copy; Copyright 2011-2015 Nicolas Perriault and contributors. CasperJS logo by Jeremy Forveille. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.3.1. </div> </body> </html>
{ "content_hash": "234bf3bb12a06048c02e5f8810857bec", "timestamp": "", "source": "github", "line_count": 166, "max_line_length": 195, "avg_line_length": 62.98192771084337, "alnum_prop": 0.6843615494978479, "repo_name": "claus022015/USDA_community", "id": "91b38c2981bf6d33049844b740bc5b181021ee8e", "size": "10456", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_build/html/12_dir/$_12-epilogue.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "14058" }, { "name": "C#", "bytes": "5421" }, { "name": "CSS", "bytes": "103369" }, { "name": "CoffeeScript", "bytes": "5372" }, { "name": "HTML", "bytes": "8500229" }, { "name": "JavaScript", "bytes": "517959" }, { "name": "Makefile", "bytes": "20909" }, { "name": "Python", "bytes": "304934" }, { "name": "Ruby", "bytes": "1220" }, { "name": "Shell", "bytes": "1264" }, { "name": "TeX", "bytes": "326616" } ], "symlink_target": "" }
University ========== Repository for University work and Projects
{ "content_hash": "d01da016f10244f0b859a35aa6c6f5e5", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 43, "avg_line_length": 16.75, "alnum_prop": 0.7164179104477612, "repo_name": "PrimalSpark/University", "id": "5eabc678272ca3e6e85dde1e27fdf7c452410418", "size": "67", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<link rel="import" href="/_polymer/bower_components/polymer/polymer.html"> <link rel="import" href="/_polymer/bower_components/google-apis/google-maps-api.html"> <dom-module id="sky-google-maps-places-autocomplete"> <template> <style> :host { position: relative; display: block; height: 100%; } #map { height: 200px; } </style> <google-maps-api api-key="{{apiKey}}" version="3.exp"></google-maps-api> <div id="map" style="background-color: #e1e1e1"></div> <script> var mapsAPI = document.querySelector('google-maps-api'); mapsAPI.addEventListener('api-load', function(e) { var map = new this.api.Map(document.getElementById('map'), { center: {lat: -34.397, lng: 150.644}, scrollwheel: false, zoom: 8 }); }); </script> </template> <script> Polymer({ is: 'sky-google-maps-places-autocomplete', properties: { apiKey: String, da: String }, getApiKey: function() { return "AIzaSyBaywrpgIGIY8guYt9vqRlzBCAs7LNjMUY"; }, getKey: function(da) { var key = da.split('=')[1].split("\"").join("").split("'").join(""); alert(key); return 'AIzaSyBaywrpgIGIY8guYt9vqRlzBCAs7LNjMUY'; }, hasHelp: function(help) { return help.length > 0; } }); </script> </dom-module>
{ "content_hash": "65e844ac7e31a5add240bf5d69ac8b32", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 86, "avg_line_length": 24.912280701754387, "alnum_prop": 0.5669014084507042, "repo_name": "evandor/skysail", "id": "2fe2fcdd9d10be9ba50e939774101b02a2b0a9a5", "size": "1420", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "skysail.server.ui.bootstrap/webapp/sky-bst/sky-google-maps-places-autocomplete.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "950" }, { "name": "CSS", "bytes": "5012564" }, { "name": "Gherkin", "bytes": "15433" }, { "name": "Groovy", "bytes": "6273" }, { "name": "HTML", "bytes": "695475" }, { "name": "Java", "bytes": "2522250" }, { "name": "JavaScript", "bytes": "34563882" }, { "name": "RAML", "bytes": "7797505" }, { "name": "Scala", "bytes": "86164" }, { "name": "Shell", "bytes": "700281" }, { "name": "Smalltalk", "bytes": "1263" }, { "name": "TypeScript", "bytes": "47012" } ], "symlink_target": "" }
/* https://leetcode.com/problems/count-complete-tree-nodes/description/ Given a complete binary tree, count the number of nodes. Note: Definition of a complete binary tree from Wikipedia: In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. Example: Input: 1 / \ 2 3 / \ / 4 5 6 Output: 6 */ package ltree /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func countNodes(root *TreeNode) int { if root == nil { return 0 } res, lastLevelCount := 0, 1 for tmp := root; tmp != nil; tmp = tmp.Left { if res != 0 { lastLevelCount *= 2 } res += lastLevelCount } start, end := 1, lastLevelCount for start <= end { cur, mid, prefix := root, start+(end-start)>>1, 0 for length := lastLevelCount; length > 1; length /= 2 { if tmp := length / 2; mid <= prefix+tmp { cur = cur.Left } else { cur = cur.Right prefix += tmp } } if cur != nil { start = mid + 1 } else { end = mid - 1 } } return res - (lastLevelCount - end) }
{ "content_hash": "2b3f05c267f6589797817a761070eeab", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 213, "avg_line_length": 20.142857142857142, "alnum_prop": 0.6099290780141844, "repo_name": "TTWShell/algorithms", "id": "86aaa3485bc711585d447d8889c64c08e8cbf92a", "size": "1269", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "leetcode/tree/countNodes.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "943143" }, { "name": "Makefile", "bytes": "368" }, { "name": "Shell", "bytes": "421" } ], "symlink_target": "" }
#import "TiBase.h" #import "TiUIView.h" #import "TiColor.h" #import "TiRect.h" #import "TiUtils.h" #import "ImageLoader.h" #ifdef USE_TI_UI2DMATRIX #import "Ti2DMatrix.h" #endif #if defined(USE_TI_UIIOS3DMATRIX) || defined(USE_TI_UI3DMATRIX) #import "Ti3DMatrix.h" #endif #import "TiViewProxy.h" #import "TiApp.h" #import "UIImage+Resize.h" void InsetScrollViewForKeyboard(UIScrollView * scrollView,CGFloat keyboardTop,CGFloat minimumContentHeight) { VerboseLog(@"ScrollView:%@, keyboardTop:%f minimumContentHeight:%f",scrollView,keyboardTop,minimumContentHeight); CGRect scrollVisibleRect = [scrollView convertRect:[scrollView bounds] toView:[[TiApp app] topMostView]]; //First, find out how much we have to compensate. CGFloat obscuredHeight = scrollVisibleRect.origin.y + scrollVisibleRect.size.height - keyboardTop; //ObscuredHeight is how many vertical pixels the keyboard obscures of the scroll view. Some of this may be acceptable. CGFloat unimportantArea = MAX(scrollVisibleRect.size.height - minimumContentHeight,0); //It's possible that some of the covered area doesn't matter. If it all matters, unimportant is 0. //As such, obscuredHeight is now how much actually matters of scrollVisibleRect. CGFloat bottomInset = MAX(0,obscuredHeight-unimportantArea); [scrollView setContentInset:UIEdgeInsetsMake(0, 0, bottomInset, 0)]; CGPoint offset = [scrollView contentOffset]; if(offset.y + bottomInset < 0 ) { offset.y = -bottomInset; [scrollView setContentOffset:offset animated:YES]; } VerboseLog(@"ScrollVisibleRect(%f,%f),%fx%f; obscuredHeight:%f; unimportantArea:%f", scrollVisibleRect.origin.x,scrollVisibleRect.origin.y,scrollVisibleRect.size.width,scrollVisibleRect.size.height, obscuredHeight,unimportantArea); } void OffsetScrollViewForRect(UIScrollView * scrollView,CGFloat keyboardTop,CGFloat minimumContentHeight,CGRect responderRect) { VerboseLog(@"ScrollView:%@, keyboardTop:%f minimumContentHeight:%f responderRect:(%f,%f),%fx%f;", scrollView,keyboardTop,minimumContentHeight, responderRect.origin.x,responderRect.origin.y,responderRect.size.width,responderRect.size.height); CGRect scrollVisibleRect = [scrollView convertRect:[scrollView bounds] toView:[[TiApp app] topMostView]]; //First, find out how much we have to compensate. CGFloat obscuredHeight = scrollVisibleRect.origin.y + scrollVisibleRect.size.height - keyboardTop; //ObscuredHeight is how many vertical pixels the keyboard obscures of the scroll view. Some of this may be acceptable. //It's possible that some of the covered area doesn't matter. If it all matters, unimportant is 0. //As such, obscuredHeight is now how much actually matters of scrollVisibleRect. VerboseLog(@"ScrollVisibleRect(%f,%f),%fx%f; obscuredHeight:%f;", scrollVisibleRect.origin.x,scrollVisibleRect.origin.y,scrollVisibleRect.size.width,scrollVisibleRect.size.height, obscuredHeight); scrollVisibleRect.size.height -= MAX(0,obscuredHeight); //Okay, the scrollVisibleRect.size now represents the actually visible area. CGPoint offsetPoint = [scrollView contentOffset]; CGPoint offsetForBottomRight; offsetForBottomRight.x = responderRect.origin.x + responderRect.size.width - scrollVisibleRect.size.width; offsetForBottomRight.y = responderRect.origin.y + responderRect.size.height - scrollVisibleRect.size.height; offsetPoint.x = MIN(responderRect.origin.x,MAX(offsetPoint.x,offsetForBottomRight.x)); offsetPoint.y = MIN(responderRect.origin.y,MAX(offsetPoint.y,offsetForBottomRight.y)); VerboseLog(@"OffsetForBottomright:(%f,%f) OffsetPoint:(%f,%f)", offsetForBottomRight.x, offsetForBottomRight.y, offsetPoint.x, offsetPoint.y); CGFloat maxOffset = [scrollView contentInset].bottom + [scrollView contentSize].height - scrollVisibleRect.size.height; if(maxOffset < offsetPoint.y) { offsetPoint.y = MAX(0,maxOffset); } [scrollView setContentOffset:offsetPoint animated:YES]; } void ModifyScrollViewForKeyboardHeightAndContentHeightWithResponderRect(UIScrollView * scrollView,CGFloat keyboardTop,CGFloat minimumContentHeight,CGRect responderRect) { VerboseLog(@"ScrollView:%@, keyboardTop:%f minimumContentHeight:%f responderRect:(%f,%f),%fx%f;", scrollView,keyboardTop,minimumContentHeight, responderRect.origin.x,responderRect.origin.y,responderRect.size.width,responderRect.size.height); CGRect scrollVisibleRect = [scrollView convertRect:[scrollView bounds] toView:[[TiApp app] topMostView]]; //First, find out how much we have to compensate. CGFloat obscuredHeight = scrollVisibleRect.origin.y + scrollVisibleRect.size.height - keyboardTop; //ObscuredHeight is how many vertical pixels the keyboard obscures of the scroll view. Some of this may be acceptable. CGFloat unimportantArea = MAX(scrollVisibleRect.size.height - minimumContentHeight,0); //It's possible that some of the covered area doesn't matter. If it all matters, unimportant is 0. //As such, obscuredHeight is now how much actually matters of scrollVisibleRect. [scrollView setContentInset:UIEdgeInsetsMake(0, 0, MAX(0,obscuredHeight-unimportantArea), 0)]; VerboseLog(@"ScrollVisibleRect(%f,%f),%fx%f; obscuredHeight:%f; unimportantArea:%f", scrollVisibleRect.origin.x,scrollVisibleRect.origin.y,scrollVisibleRect.size.width,scrollVisibleRect.size.height, obscuredHeight,unimportantArea); scrollVisibleRect.size.height -= MAX(0,obscuredHeight); //Okay, the scrollVisibleRect.size now represents the actually visible area. CGPoint offsetPoint = [scrollView contentOffset]; if(!CGRectIsEmpty(responderRect)) { CGPoint offsetForBottomRight; offsetForBottomRight.x = responderRect.origin.x + responderRect.size.width - scrollVisibleRect.size.width; offsetForBottomRight.y = responderRect.origin.y + responderRect.size.height - scrollVisibleRect.size.height; offsetPoint.x = MIN(responderRect.origin.x,MAX(offsetPoint.x,offsetForBottomRight.x)); offsetPoint.y = MIN(responderRect.origin.y,MAX(offsetPoint.y,offsetForBottomRight.y)); VerboseLog(@"OffsetForBottomright:(%f,%f) OffsetPoint:(%f,%f)", offsetForBottomRight.x, offsetForBottomRight.y, offsetPoint.x, offsetPoint.y); } else { offsetPoint.x = MAX(0,offsetPoint.x); offsetPoint.y = MAX(0,offsetPoint.y); VerboseLog(@"OffsetPoint:(%f,%f)",offsetPoint.x, offsetPoint.y); } [scrollView setContentOffset:offsetPoint animated:YES]; } NSArray* listenerArray = nil; @interface TiUIView () -(void)sanitycheckListeners; @end @interface TiUIView(Private) -(void)renderRepeatedBackground:(id)image; @end @implementation TiUIView DEFINE_EXCEPTIONS @synthesize proxy,touchDelegate,backgroundImage,oldSize; #pragma mark Internal Methods #if VIEW_DEBUG -(id)retain { [super retain]; NSLog(@"[VIEW %@] RETAIN: %d", self, [self retainCount]); } -(oneway void)release { NSLog(@"[VIEW %@] RELEASE: %d", self, [self retainCount]-1); [super release]; } #endif -(void)dealloc { [transformMatrix release]; [animation release]; [backgroundImage release]; [gradientLayer release]; [bgdImageLayer release]; [singleTapRecognizer release]; [doubleTapRecognizer release]; [twoFingerTapRecognizer release]; [pinchRecognizer release]; [leftSwipeRecognizer release]; [rightSwipeRecognizer release]; [upSwipeRecognizer release]; [downSwipeRecognizer release]; [longPressRecognizer release]; proxy = nil; touchDelegate = nil; [super dealloc]; } -(void)removeFromSuperview { if ([NSThread isMainThread]) { [super removeFromSuperview]; } else { TiThreadPerformOnMainThread(^{[super removeFromSuperview];}, YES); } } - (id) init { self = [super init]; if (self != nil) { } return self; } -(BOOL)viewSupportsBaseTouchEvents { // give the ability for the subclass to turn off our event handling // if it wants too return YES; } -(void)ensureGestureListeners { if ([(TiViewProxy*)proxy _hasListeners:@"swipe"]) { [[self gestureRecognizerForEvent:@"uswipe"] setEnabled:YES]; [[self gestureRecognizerForEvent:@"dswipe"] setEnabled:YES]; [[self gestureRecognizerForEvent:@"rswipe"] setEnabled:YES]; [[self gestureRecognizerForEvent:@"lswipe"] setEnabled:YES]; } if ([(TiViewProxy*)proxy _hasListeners:@"pinch"]) { [[self gestureRecognizerForEvent:@"pinch"] setEnabled:YES]; } if ([(TiViewProxy*)proxy _hasListeners:@"longpress"]) { [[self gestureRecognizerForEvent:@"longpress"] setEnabled:YES]; } } -(BOOL)proxyHasGestureListeners { return [(TiViewProxy*)proxy _hasListeners:@"swipe"] || [(TiViewProxy*)proxy _hasListeners:@"pinch"] || [(TiViewProxy*)proxy _hasListeners:@"longpress"]; } -(BOOL)proxyHasTapListener { return [proxy _hasListeners:@"singletap"] || [proxy _hasListeners:@"doubletap"] || [proxy _hasListeners:@"twofingertap"]; } -(BOOL)proxyHasTouchListener { return [proxy _hasListeners:@"touchstart"] || [proxy _hasListeners:@"touchcancel"] || [proxy _hasListeners:@"touchend"] || [proxy _hasListeners:@"touchmove"] || [proxy _hasListeners:@"click"] || [proxy _hasListeners:@"dblclick"]; } -(void)updateTouchHandling { BOOL touchEventsSupported = [self viewSupportsBaseTouchEvents]; handlesTouches = touchEventsSupported && ( [self proxyHasTouchListener] || [self proxyHasTapListener] || [self proxyHasGestureListeners]); [self ensureGestureListeners]; // If a user has not explicitly set whether or not the view interacts, base it on whether or // not it handles events, and if not, set it to the interaction default. if (!changedInteraction) { self.userInteractionEnabled = handlesTouches || [self interactionDefault]; } } -(void)initializeState { virtualParentTransform = CGAffineTransformIdentity; [self updateTouchHandling]; self.backgroundColor = [UIColor clearColor]; self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; } -(void)configurationSet { // can be used to trigger things after all properties are set configurationSet = YES; } -(void)setProxy:(TiProxy *)p { proxy = p; [proxy setModelDelegate:self]; [self sanitycheckListeners]; } -(UIImage*)loadImage:(id)image { if (image==nil) return nil; NSURL *url = [TiUtils toURL:image proxy:proxy]; if (url==nil) { NSLog(@"[WARN] could not find image: %@",image); return nil; } return [[ImageLoader sharedLoader] loadImmediateStretchableImage:url withLeftCap:leftCap topCap:topCap]; } -(id)transformMatrix { return transformMatrix; } - (id)accessibilityElement { return self; } #pragma mark - Accessibility API - (void)setAccessibilityLabel_:(id)accessibilityLabel { id accessibilityElement = self.accessibilityElement; if (accessibilityElement != nil) { [accessibilityElement setIsAccessibilityElement:YES]; [accessibilityElement setAccessibilityLabel:[TiUtils stringValue:accessibilityLabel]]; } } - (void)setAccessibilityValue_:(id)accessibilityValue { id accessibilityElement = self.accessibilityElement; if (accessibilityElement != nil) { [accessibilityElement setIsAccessibilityElement:YES]; [accessibilityElement setAccessibilityValue:[TiUtils stringValue:accessibilityValue]]; } } - (void)setAccessibilityHint_:(id)accessibilityHint { id accessibilityElement = self.accessibilityElement; if (accessibilityElement != nil) { [accessibilityElement setIsAccessibilityElement:YES]; [accessibilityElement setAccessibilityHint:[TiUtils stringValue:accessibilityHint]]; } } - (void)setAccessibilityHidden_:(id)accessibilityHidden { self.accessibilityElementsHidden = [TiUtils boolValue:accessibilityHidden def:NO]; } #pragma mark Layout -(void)frameSizeChanged:(CGRect)frame bounds:(CGRect)bounds { if (backgroundRepeat) { [self renderRepeatedBackground:backgroundImage]; } [self updateViewShadowPath]; } -(void)setFrame:(CGRect)frame { [super setFrame:frame]; // this happens when a view is added to another view but not // through the framework (such as a tableview header) and it // means we need to force the layout of our children if (childrenInitialized==NO && CGRectIsEmpty(frame)==NO && [self.proxy isKindOfClass:[TiViewProxy class]]) { childrenInitialized=YES; [(TiViewProxy*)self.proxy layoutChildren:NO]; } } -(void)checkBounds { CGRect newBounds = [self bounds]; if(!CGSizeEqualToSize(oldSize, newBounds.size)) { oldSize = newBounds.size; //TIMOB-11197, TC-1264 if (!animating) { [CATransaction begin]; [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; } if ([self gradientLayer] != self.layer) { [[self gradientLayer] setFrame:newBounds]; } if ([self backgroundImageLayer] != self.layer) { [[self backgroundImageLayer] setFrame:newBounds]; } if (!animating) { [CATransaction commit]; } [self frameSizeChanged:[TiUtils viewPositionRect:self] bounds:newBounds]; } } -(void)setBounds:(CGRect)bounds { [super setBounds:bounds]; [self checkBounds]; } -(void)layoutSubviews { [super layoutSubviews]; [self checkBounds]; } -(void)updateTransform { #ifdef USE_TI_UI2DMATRIX if ([transformMatrix isKindOfClass:[Ti2DMatrix class]]) { self.transform = CGAffineTransformConcat(virtualParentTransform, [(Ti2DMatrix*)transformMatrix matrix]); return; } #endif #if defined(USE_TI_UIIOS3DMATRIX) || defined(USE_TI_UI3DMATRIX) if ([transformMatrix isKindOfClass:[Ti3DMatrix class]]) { self.layer.transform = CATransform3DConcat(CATransform3DMakeAffineTransform(virtualParentTransform),[(Ti3DMatrix*)transformMatrix matrix]); return; } #endif self.transform = virtualParentTransform; } -(void)setVirtualParentTransform:(CGAffineTransform)newTransform { virtualParentTransform = newTransform; [self updateTransform]; } -(void)fillBoundsToRect:(TiRect*)rect { CGRect r = [self bounds]; [rect setRect:r]; } -(void)fillFrameToRect:(TiRect*)rect { CGRect r = [self frame]; [rect setRect:r]; } #pragma mark Public APIs -(void)setTintColor_:(id)color { if ([TiUtils isIOS7OrGreater]) { TiColor *ticolor = [TiUtils colorValue:color]; [self performSelector:@selector(setTintColor:) withObject:[ticolor _color]]; } } -(void)setBorderColor_:(id)color { TiColor *ticolor = [TiUtils colorValue:color]; self.layer.borderWidth = MAX(self.layer.borderWidth,1); self.layer.borderColor = [ticolor _color].CGColor; } -(void)setBorderWidth_:(id)w { TiDimension theDim = TiDimensionFromObject(w); if (TiDimensionIsDip(theDim)) { self.layer.borderWidth = MAX(theDim.value, 0); } else { self.layer.borderWidth = 0; } [self updateClipping]; } -(void)setBackgroundColor_:(id)color { if ([color isKindOfClass:[UIColor class]]) { super.backgroundColor = color; } else { TiColor *ticolor = [TiUtils colorValue:color]; super.backgroundColor = [ticolor _color]; } } -(void)setOpacity_:(id)opacity { self.alpha = [TiUtils floatValue:opacity]; } -(CALayer *)backgroundImageLayer { return bgdImageLayer; } -(CALayer *)gradientLayer { return gradientLayer; } // You might wonder why we don't just use the native feature of -[UIColor colorWithPatternImage:]. // Here's why: // * It doesn't properly handle alpha channels // * You can't combine background tesselations with background colors // * By making the background-repeat flag a boolean swap, we would have to cache, check, and uncache // background colors everywhere - and this starts getting really complicated for some views // (on the off chance somebody wants to swap tesselation AND has a background color they want to replace it with). -(void)renderRepeatedBackground:(id)image { if (![NSThread isMainThread]) { TiThreadPerformOnMainThread(^{ [self renderRepeatedBackground:image]; }, NO); return; } UIImage* bgImage = [TiUtils loadBackgroundImage:image forProxy:proxy]; if (bgImage == nil) { [self backgroundImageLayer].contents = nil; return; } // Due to coordinate system shenanagins (there are multiple translations between the UIKit coordinate system // and the CG coordinate system happening here) we have to manually flip the background image to render // before passing it to the tiling system (via passing it through another UIGraphics context; this orients the // image in the "correct" way for the second pass). // // Note that this means passes through two different graphics contexts. They can be nested, but that makes the code // even uglier. // // NOTE: Doing this begins the image tesselation starting at the upper-left, which is considered the 'origin' for all // drawing operations on iOS (and presumably Android). By removing this code and instead blitting the [bgImage CGImage] // directly into the graphics context, it tesselates from the lower-left. UIGraphicsBeginImageContextWithOptions(bgImage.size, NO, bgImage.scale); CGContextRef imageContext = UIGraphicsGetCurrentContext(); CGContextDrawImage(imageContext, CGRectMake(0, 0, bgImage.size.width , bgImage.size.height), [bgImage CGImage]); UIImage* translatedImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, bgImage.scale); CGContextRef background = UIGraphicsGetCurrentContext(); if (background == nil) { //TIMOB-11564. Either width or height of the bounds is zero UIGraphicsEndImageContext(); return; } CGRect imageRect = CGRectMake(0, 0, bgImage.size.width, bgImage.size.height); CGContextDrawTiledImage(background, imageRect, [translatedImage CGImage]); UIImage* renderedBg = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); [self backgroundImageLayer].contents = (id)renderedBg.CGImage; } -(void)setBackgroundImage_:(id)image { UIImage* bgImage = [TiUtils loadBackgroundImage:image forProxy:proxy]; if (bgImage == nil) { [bgdImageLayer removeFromSuperlayer]; RELEASE_TO_NIL(bgdImageLayer); return; } if (bgdImageLayer == nil) { bgdImageLayer = [[CALayer alloc] init]; [bgdImageLayer setFrame:[self bounds]]; bgdImageLayer.masksToBounds = YES; bgdImageLayer.cornerRadius = self.layer.cornerRadius; if (gradientLayer != nil) { [[self gradientWrapperView].layer insertSublayer:bgdImageLayer above:gradientLayer]; } else { [[self gradientWrapperView].layer insertSublayer:bgdImageLayer atIndex:0]; } } if (backgroundRepeat) { [self renderRepeatedBackground:bgImage]; } else { [self backgroundImageLayer].contents = (id)bgImage.CGImage; if (bgImage != nil) { [self backgroundImageLayer].contentsScale = [bgImage scale]; [self backgroundImageLayer].contentsCenter = TiDimensionLayerContentCenter(topCap, leftCap, topCap, leftCap, [bgImage size]); if (!CGPointEqualToPoint([self backgroundImageLayer].contentsCenter.origin,CGPointZero)) { [self backgroundImageLayer].magnificationFilter = @"nearest"; } else { [self backgroundImageLayer].magnificationFilter = @"linear"; } } } self.backgroundImage = bgImage; } -(void)setBackgroundRepeat_:(id)repeat { backgroundRepeat = [TiUtils boolValue:repeat def:NO]; [self setBackgroundImage_:backgroundImage]; } -(void)setBackgroundLeftCap_:(id)value { TiDimension cap = TiDimensionFromObject(value); if (!TiDimensionEqual(leftCap, cap)) { leftCap = cap; [self setBackgroundImage_:backgroundImage]; } } -(void)setBackgroundTopCap_:(id)value { TiDimension cap = TiDimensionFromObject(value); if (!TiDimensionEqual(topCap, cap)) { topCap = cap; [self setBackgroundImage_:backgroundImage]; } } -(void)setBorderRadius_:(id)radius { TiDimension theDim = TiDimensionFromObject(radius); if (TiDimensionIsDip(theDim)) { self.layer.cornerRadius = MAX(theDim.value,0); } else { self.layer.cornerRadius = 0; } if (bgdImageLayer != nil) { bgdImageLayer.cornerRadius = self.layer.cornerRadius; } if (gradientLayer != nil) { gradientLayer.cornerRadius = self.layer.cornerRadius; } [self updateClipping]; } -(void)setAnchorPoint_:(id)point { self.layer.anchorPoint = [TiUtils pointValue:point]; } -(void)setTransform_:(id)transform_ { RELEASE_TO_NIL(transformMatrix); transformMatrix = [transform_ retain]; [self updateTransform]; } -(void)setCenter_:(id)point { self.center = [TiUtils pointValue:point]; } -(void)setVisible_:(id)visible { BOOL oldVal = self.hidden; self.hidden = ![TiUtils boolValue:visible]; //Redraw ourselves if changing from invisible to visible, to handle any changes made if (!self.hidden && oldVal) { TiViewProxy* viewProxy = (TiViewProxy*)[self proxy]; [viewProxy willEnqueue]; } } -(void)setTouchEnabled_:(id)arg { self.userInteractionEnabled = [TiUtils boolValue:arg def:[self interactionDefault]]; changedInteraction = YES; } -(BOOL) touchEnabled { return touchEnabled; } -(UIView *)gradientWrapperView { return self; } -(void)setBackgroundGradient_:(id)arg { if (arg == nil) { [gradientLayer removeFromSuperlayer]; RELEASE_TO_NIL(gradientLayer); } else if (gradientLayer == nil) { gradientLayer = [[TiGradientLayer alloc] init]; [(TiGradientLayer *)gradientLayer setGradient:arg]; [gradientLayer setNeedsDisplayOnBoundsChange:YES]; [gradientLayer setFrame:[self bounds]]; [gradientLayer setNeedsDisplay]; gradientLayer.cornerRadius = self.layer.cornerRadius; gradientLayer.masksToBounds = YES; [[self gradientWrapperView].layer insertSublayer:gradientLayer atIndex:0]; } else { [(TiGradientLayer *)gradientLayer setGradient:arg]; [gradientLayer setNeedsDisplay]; } } -(void)updateClipping { if (clipMode != 0) { //Explicitly overridden self.clipsToBounds = (clipMode > 0); } else { if ([self shadowLayer].shadowOpacity > 0) { //If shadow is visible, disble clipping self.clipsToBounds = NO; } else if (self.layer.borderWidth > 0 || self.layer.cornerRadius > 0) { //If borderWidth > 0, or borderRadius > 0 enable clipping self.clipsToBounds = YES; } else if ([[self proxy] isKindOfClass:[TiViewProxy class]]){ self.clipsToBounds = ( [[((TiViewProxy*)self.proxy) children] count] > 0 ); } else { DeveloperLog(@"[WARN] Proxy is nil or not of kind TiViewProxy. Check"); self.clipsToBounds = NO; } } } -(void)setClipMode_:(id)arg { [[self proxy] replaceValue:arg forKey:@"clipMode" notification:NO]; clipMode = [TiUtils intValue:arg def:0]; [self updateClipping]; } /** This section of code for shadow support adapted from contributions by Martin Guillon See https://github.com/appcelerator/_tiimagefactory_mobile/pull/2996 */ -(CALayer *)shadowLayer { return [self layer]; } -(void)setViewShadowOffset_:(id)arg { [[self proxy] replaceValue:arg forKey:@"viewShadowOffset" notification:NO]; CGPoint p = [TiUtils pointValue:arg]; [[self shadowLayer] setShadowOffset:CGSizeMake(p.x, p.y)]; } -(void)setViewShadowRadius_:(id)arg { [[self proxy] replaceValue:arg forKey:@"viewShadowRadius" notification:NO]; [[self shadowLayer] setShadowRadius:[TiUtils floatValue:arg def:0.0]]; } -(void)setViewShadowColor_:(id)arg { [[self proxy] replaceValue:arg forKey:@"viewShadowColor" notification:NO]; TiColor* theColor = [TiUtils colorValue:arg]; if (theColor == nil) { [[self shadowLayer] setShadowColor:nil]; [[self shadowLayer] setShadowOpacity:0.0]; } else { CGFloat alpha = CGColorGetAlpha([[theColor color] CGColor]); [[self shadowLayer] setShadowColor:[[theColor color] CGColor]]; [[self shadowLayer] setShadowOpacity:alpha]; [self updateViewShadowPath]; } [self updateClipping]; } -(void)updateViewShadowPath { if ([self shadowLayer].shadowOpacity > 0.0f) { //to speedup things [self shadowLayer].shadowPath =[UIBezierPath bezierPathWithRoundedRect:[self bounds] cornerRadius:self.layer.cornerRadius].CGPath; } } -(void)didAddSubview:(UIView*)view { // So, it turns out that adding a subview places it beneath the gradient layer. // Every time we add a new subview, we have to make sure the gradient stays where it belongs... if (gradientLayer != nil) { [[self gradientWrapperView].layer insertSublayer:gradientLayer atIndex:0]; if (bgdImageLayer != nil) { [[self gradientWrapperView].layer insertSublayer:bgdImageLayer above:gradientLayer]; } } else if (bgdImageLayer != nil) { [[self gradientWrapperView].layer insertSublayer:bgdImageLayer atIndex:0]; } } -(void)animate:(TiAnimation *)newAnimation { RELEASE_TO_NIL(animation); if ([self.proxy isKindOfClass:[TiViewProxy class]] && [(TiViewProxy*)self.proxy viewReady]==NO) { DebugLog(@"[DEBUG] Ti.View.animate() called before view %@ was ready: Will re-attempt", self); if (animationDelayGuard++ > 5) { DebugLog(@"[DEBUG] Animation guard triggered, exceeded timeout to perform animation."); animationDelayGuard = 0; return; } [self performSelector:@selector(animate:) withObject:newAnimation afterDelay:0.01]; return; } animationDelayGuard = 0; BOOL resetState = NO; if ([self.proxy isKindOfClass:[TiViewProxy class]] && [(TiViewProxy*)self.proxy willBeRelaying]) { DeveloperLog(@"RESETTING STATE"); resetState = YES; } animationDelayGuardForLayout = 0; if (newAnimation != nil) { RELEASE_TO_NIL(animation); animation = [newAnimation retain]; animation.resetState = resetState; [animation animate:self]; } else { DebugLog(@"[WARN] Ti.View.animate() (view %@) could not make animation from: %@", self, newAnimation); } } -(void)animationStarted { animating = YES; } -(void)animationCompleted { animating = NO; } -(BOOL)animating { return animating; } #pragma mark Property Change Support -(SEL)selectorForProperty:(NSString*)key { NSString *method = [NSString stringWithFormat:@"set%@%@_:", [[key substringToIndex:1] uppercaseString], [key substringFromIndex:1]]; return NSSelectorFromString(method); } -(void)readProxyValuesWithKeys:(id<NSFastEnumeration>)keys { DoProxyDelegateReadValuesWithKeysFromProxy(self, keys, proxy); } -(void)propertyChanged:(NSString*)key oldValue:(id)oldValue newValue:(id)newValue proxy:(TiProxy*)proxy_ { DoProxyDelegateChangedValuesWithProxy(self, key, oldValue, newValue, proxy_); } //Todo: Generalize. -(void)setKrollValue:(id)value forKey:(NSString *)key withObject:(id)props { if(value == [NSNull null]) { value = nil; } SEL method = SetterWithObjectForKrollProperty(key); if([self respondsToSelector:method]) { [self performSelector:method withObject:value withObject:props]; return; } method = SetterForKrollProperty(key); if([self respondsToSelector:method]) { [self performSelector:method withObject:value]; } } -(void)transferProxy:(TiViewProxy*)newProxy deep:(BOOL)deep { TiViewProxy * oldProxy = (TiViewProxy *)[self proxy]; // We can safely skip everything if we're transferring to ourself. if (oldProxy != newProxy) { NSArray * oldProperties = (NSArray *)[oldProxy allKeys]; NSArray * newProperties = (NSArray *)[newProxy allKeys]; NSArray * keySequence = [newProxy keySequence]; [oldProxy retain]; [self retain]; [newProxy setReproxying:YES]; [oldProxy setView:nil]; [newProxy setView:self]; [self setProxy:[newProxy retain]]; //The important sequence first: for (NSString * thisKey in keySequence) { id newValue = [newProxy valueForKey:thisKey]; id oldValue = [oldProxy valueForKey:thisKey]; if ((oldValue != newValue) && ![oldValue isEqual:newValue]) { [self setKrollValue:newValue forKey:thisKey withObject:nil]; } } for (NSString * thisKey in oldProperties) { if([newProperties containsObject:thisKey] || [keySequence containsObject:thisKey]) { continue; } [self setKrollValue:nil forKey:thisKey withObject:nil]; } for (NSString * thisKey in newProperties) { if ([keySequence containsObject:thisKey]) { continue; } // Always set the new value, even if 'equal' - some view setters (as in UIImageView) // use internal voodoo to determine what to display. // TODO: We may be able to take this out once the imageView.url property is taken out, and change it back to an equality test. id newValue = [newProxy valueForUndefinedKey:thisKey]; [self setKrollValue:newValue forKey:thisKey withObject:nil]; } if (deep) { NSArray *subProxies = [newProxy children]; [[oldProxy children] enumerateObjectsUsingBlock:^(TiViewProxy *oldSubProxy, NSUInteger idx, BOOL *stop) { TiViewProxy *newSubProxy = idx < [subProxies count] ? [subProxies objectAtIndex:idx] : nil; [[oldSubProxy view] transferProxy:newSubProxy deep:YES]; }]; } [oldProxy release]; [newProxy setReproxying:NO]; [self release]; } } -(BOOL)validateTransferToProxy:(TiViewProxy*)newProxy deep:(BOOL)deep { TiViewProxy * oldProxy = (TiViewProxy *)[self proxy]; if (oldProxy == newProxy) { return YES; } if (![newProxy isMemberOfClass:[oldProxy class]]) { return NO; } __block BOOL result = YES; if (deep) { NSArray *subProxies = [newProxy children]; NSArray *oldSubProxies = [oldProxy children]; if ([subProxies count] != [oldSubProxies count]) { return NO; } [oldSubProxies enumerateObjectsUsingBlock:^(TiViewProxy *oldSubProxy, NSUInteger idx, BOOL *stop) { TiViewProxy *newSubProxy = [subProxies objectAtIndex:idx]; result = [[oldSubProxy view] validateTransferToProxy:newSubProxy deep:YES]; if (!result) { *stop = YES; } }]; } return result; } -(id)proxyValueForKey:(NSString *)key { return [proxy valueForKey:key]; } #pragma mark First Responder delegation -(void)makeRootViewFirstResponder { [[[TiApp controller] view] becomeFirstResponder]; } #pragma mark Recognizers -(UITapGestureRecognizer*)singleTapRecognizer; { if (singleTapRecognizer == nil) { singleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(recognizedTap:)]; [self configureGestureRecognizer:singleTapRecognizer]; [self addGestureRecognizer:singleTapRecognizer]; if (doubleTapRecognizer != nil) { [singleTapRecognizer requireGestureRecognizerToFail:doubleTapRecognizer]; } } return singleTapRecognizer; } -(UITapGestureRecognizer*)doubleTapRecognizer; { if (doubleTapRecognizer == nil) { doubleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(recognizedTap:)]; [doubleTapRecognizer setNumberOfTapsRequired:2]; [self configureGestureRecognizer:doubleTapRecognizer]; [self addGestureRecognizer:doubleTapRecognizer]; if (singleTapRecognizer != nil) { [singleTapRecognizer requireGestureRecognizerToFail:doubleTapRecognizer]; } } return doubleTapRecognizer; } -(UITapGestureRecognizer*)twoFingerTapRecognizer; { if (twoFingerTapRecognizer == nil) { twoFingerTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(recognizedTap:)]; [twoFingerTapRecognizer setNumberOfTouchesRequired:2]; [self configureGestureRecognizer:twoFingerTapRecognizer]; [self addGestureRecognizer:twoFingerTapRecognizer]; } return twoFingerTapRecognizer; } -(UIPinchGestureRecognizer*)pinchRecognizer; { if (pinchRecognizer == nil) { pinchRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(recognizedPinch:)]; [self configureGestureRecognizer:pinchRecognizer]; [self addGestureRecognizer:pinchRecognizer]; } return pinchRecognizer; } -(UISwipeGestureRecognizer*)leftSwipeRecognizer; { if (leftSwipeRecognizer == nil) { leftSwipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(recognizedSwipe:)]; [leftSwipeRecognizer setDirection:UISwipeGestureRecognizerDirectionLeft]; [self configureGestureRecognizer:leftSwipeRecognizer]; [self addGestureRecognizer:leftSwipeRecognizer]; } return leftSwipeRecognizer; } -(UISwipeGestureRecognizer*)rightSwipeRecognizer; { if (rightSwipeRecognizer == nil) { rightSwipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(recognizedSwipe:)]; [rightSwipeRecognizer setDirection:UISwipeGestureRecognizerDirectionRight]; [self configureGestureRecognizer:rightSwipeRecognizer]; [self addGestureRecognizer:rightSwipeRecognizer]; } return rightSwipeRecognizer; } -(UISwipeGestureRecognizer*)upSwipeRecognizer; { if (upSwipeRecognizer == nil) { upSwipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(recognizedSwipe:)]; [upSwipeRecognizer setDirection:UISwipeGestureRecognizerDirectionUp]; [self configureGestureRecognizer:upSwipeRecognizer]; [self addGestureRecognizer:upSwipeRecognizer]; } return upSwipeRecognizer; } -(UISwipeGestureRecognizer*)downSwipeRecognizer; { if (downSwipeRecognizer == nil) { downSwipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(recognizedSwipe:)]; [downSwipeRecognizer setDirection:UISwipeGestureRecognizerDirectionDown]; [self configureGestureRecognizer:downSwipeRecognizer]; [self addGestureRecognizer:downSwipeRecognizer]; } return downSwipeRecognizer; } -(UILongPressGestureRecognizer*)longPressRecognizer; { if (longPressRecognizer == nil) { longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(recognizedLongPress:)]; [self configureGestureRecognizer:longPressRecognizer]; [self addGestureRecognizer:longPressRecognizer]; } return longPressRecognizer; } -(void)recognizedTap:(UITapGestureRecognizer*)recognizer { CGPoint tapPoint = [recognizer locationInView:self]; NSDictionary *event = [TiUtils pointToDictionary:tapPoint]; if ([recognizer numberOfTouchesRequired] == 2) { [proxy fireEvent:@"twofingertap" withObject:event]; } else if ([recognizer numberOfTapsRequired] == 2) { //Because double-tap suppresses touchStart and double-click, we must do this: if ([proxy _hasListeners:@"touchstart"]) { [proxy fireEvent:@"touchstart" withObject:event propagate:YES]; } if ([proxy _hasListeners:@"dblclick"]) { [proxy fireEvent:@"dblclick" withObject:event propagate:YES]; } [proxy fireEvent:@"doubletap" withObject:event]; } else { [proxy fireEvent:@"singletap" withObject:event]; } } -(void)recognizedPinch:(UIPinchGestureRecognizer*)recognizer { NSDictionary *event = [NSDictionary dictionaryWithObjectsAndKeys: NUMDOUBLE(recognizer.scale), @"scale", NUMDOUBLE(recognizer.velocity), @"velocity", nil]; [self.proxy fireEvent:@"pinch" withObject:event]; } -(void)recognizedLongPress:(UILongPressGestureRecognizer*)recognizer { if ([recognizer state] == UIGestureRecognizerStateBegan) { CGPoint p = [recognizer locationInView:self]; NSDictionary *event = [NSDictionary dictionaryWithObjectsAndKeys: NUMFLOAT(p.x), @"x", NUMFLOAT(p.y), @"y", nil]; [self.proxy fireEvent:@"longpress" withObject:event]; } } -(void)recognizedSwipe:(UISwipeGestureRecognizer *)recognizer { NSString* swipeString; switch ([recognizer direction]) { case UISwipeGestureRecognizerDirectionUp: swipeString = @"up"; break; case UISwipeGestureRecognizerDirectionDown: swipeString = @"down"; break; case UISwipeGestureRecognizerDirectionLeft: swipeString = @"left"; break; case UISwipeGestureRecognizerDirectionRight: swipeString = @"right"; break; default: swipeString = @"unknown"; break; } CGPoint tapPoint = [recognizer locationInView:self]; NSMutableDictionary *event = [[TiUtils pointToDictionary:tapPoint] mutableCopy]; [event setValue:swipeString forKey:@"direction"]; [proxy fireEvent:@"swipe" withObject:event]; [event release]; } #pragma mark Touch Events - (BOOL)interactionDefault { return YES; } - (BOOL)interactionEnabled { return self.userInteractionEnabled; } - (BOOL)hasTouchableListener { return handlesTouches; } - (UIView *)hitTest:(CGPoint) point withEvent:(UIEvent *)event { BOOL hasTouchListeners = [self hasTouchableListener]; // if we don't have any touch listeners, see if interaction should // be handled at all.. NOTE: we don't turn off the views interactionEnabled // property since we need special handling ourselves and if we turn it off // on the view, we'd never get this event if (hasTouchListeners == NO && [self interactionEnabled]==NO) { return nil; } // OK, this is problematic because of the situation where: // touchDelegate --> view --> button // The touch never reaches the button, because the touchDelegate is as deep as the touch goes. /* // delegate to our touch delegate if we're hit but it's not for us if (hasTouchListeners==NO && touchDelegate!=nil) { return touchDelegate; } */ return [super hitTest:point withEvent:event]; } // TODO: Revisit this design decision in post-1.3.0 -(void)handleControlEvents:(UIControlEvents)events { // For subclasses (esp. buttons) to override when they have event handlers. TiViewProxy* parentProxy = [(TiViewProxy*)proxy parent]; if ([parentProxy viewAttached] && [parentProxy canHaveControllerParent]) { [[parentProxy view] handleControlEvents:events]; } } // For subclasses -(BOOL)touchedContentViewWithEvent:(UIEvent *)event { return NO; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { if ([[event touchesForView:self] count] > 0 || [self touchedContentViewWithEvent:event]) { [self processTouchesBegan:touches withEvent:event]; } [super touchesBegan:touches withEvent:event]; } - (void)processTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; if (handlesTouches) { NSDictionary *evt = [TiUtils pointToDictionary:[touch locationInView:self]]; if ([proxy _hasListeners:@"touchstart"]) { [proxy fireEvent:@"touchstart" withObject:evt propagate:YES]; [self handleControlEvents:UIControlEventTouchDown]; } } } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { if ([[event touchesForView:self] count] > 0 || [self touchedContentViewWithEvent:event]) { [self processTouchesMoved:touches withEvent:event]; } [super touchesMoved:touches withEvent:event]; } - (void)processTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; if (handlesTouches) { NSDictionary *evt = [TiUtils pointToDictionary:[touch locationInView:self]]; if ([proxy _hasListeners:@"touchmove"]) { [proxy fireEvent:@"touchmove" withObject:evt propagate:YES]; } } } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { if ([[event touchesForView:self] count] > 0 || [self touchedContentViewWithEvent:event]) { [self processTouchesEnded:touches withEvent:event]; } [super touchesEnded:touches withEvent:event]; } - (void)processTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { if (handlesTouches) { UITouch *touch = [touches anyObject]; NSDictionary *evt = [TiUtils pointToDictionary:[touch locationInView:self]]; if ([proxy _hasListeners:@"touchend"]) { [proxy fireEvent:@"touchend" withObject:evt propagate:YES]; [self handleControlEvents:UIControlEventTouchCancel]; } // Click handling is special; don't propagate if we have a delegate, // but DO invoke the touch delegate. // clicks should also be handled by any control the view is embedded in. if ([touch tapCount] == 1 && [proxy _hasListeners:@"click"]) { if (touchDelegate == nil) { [proxy fireEvent:@"click" withObject:evt propagate:YES]; return; } } else if ([touch tapCount] == 2 && [proxy _hasListeners:@"dblclick"]) { [proxy fireEvent:@"dblclick" withObject:evt propagate:YES]; return; } } } - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { if ([[event touchesForView:self] count] > 0 || [self touchedContentViewWithEvent:event]) { [self processTouchesCancelled:touches withEvent:event]; } [super touchesCancelled:touches withEvent:event]; } - (void)processTouchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { if (handlesTouches) { UITouch *touch = [touches anyObject]; CGPoint point = [touch locationInView:self]; NSDictionary *evt = [TiUtils pointToDictionary:point]; if ([proxy _hasListeners:@"touchcancel"]) { [proxy fireEvent:@"touchcancel" withObject:evt propagate:YES]; } } } #pragma mark Listener management -(void)removeGestureRecognizerOfClass:(Class)c { for (UIGestureRecognizer* r in [self gestureRecognizers]) { if ([r isKindOfClass:c]) { [self removeGestureRecognizer:r]; break; } } } -(void)configureGestureRecognizer:(UIGestureRecognizer*)gestureRecognizer { [gestureRecognizer setDelaysTouchesBegan:NO]; [gestureRecognizer setDelaysTouchesEnded:NO]; [gestureRecognizer setCancelsTouchesInView:NO]; } - (UIGestureRecognizer *)gestureRecognizerForEvent:(NSString *)event { if ([event isEqualToString:@"singletap"]) { return [self singleTapRecognizer]; } if ([event isEqualToString:@"doubletap"]) { return [self doubleTapRecognizer]; } if ([event isEqualToString:@"twofingertap"]) { return [self twoFingerTapRecognizer]; } if ([event isEqualToString:@"lswipe"]) { return [self leftSwipeRecognizer]; } if ([event isEqualToString:@"rswipe"]) { return [self rightSwipeRecognizer]; } if ([event isEqualToString:@"uswipe"]) { return [self upSwipeRecognizer]; } if ([event isEqualToString:@"dswipe"]) { return [self downSwipeRecognizer]; } if ([event isEqualToString:@"pinch"]) { return [self pinchRecognizer]; } if ([event isEqualToString:@"longpress"]) { return [self longPressRecognizer]; } return nil; } -(void)handleListenerAddedWithEvent:(NSString *)event { ENSURE_UI_THREAD_1_ARG(event); [self updateTouchHandling]; if ([event isEqualToString:@"swipe"]) { [[self gestureRecognizerForEvent:@"uswipe"] setEnabled:YES]; [[self gestureRecognizerForEvent:@"dswipe"] setEnabled:YES]; [[self gestureRecognizerForEvent:@"rswipe"] setEnabled:YES]; [[self gestureRecognizerForEvent:@"lswipe"] setEnabled:YES]; } else { [[self gestureRecognizerForEvent:event] setEnabled:YES]; } } -(void)handleListenerRemovedWithEvent:(NSString *)event { ENSURE_UI_THREAD_1_ARG(event); // unfortunately on a remove, we have to check all of them // since we might be removing one but we still have others [self updateTouchHandling]; if ([event isEqualToString:@"swipe"]) { [[self gestureRecognizerForEvent:@"uswipe"] setEnabled:NO]; [[self gestureRecognizerForEvent:@"dswipe"] setEnabled:NO]; [[self gestureRecognizerForEvent:@"rswipe"] setEnabled:NO]; [[self gestureRecognizerForEvent:@"lswipe"] setEnabled:NO]; } else { [[self gestureRecognizerForEvent:event] setEnabled:NO]; } } -(void)listenerAdded:(NSString*)event count:(int)count { if (count == 1 && [self viewSupportsBaseTouchEvents]) { [self handleListenerAddedWithEvent:event]; } } -(void)listenerRemoved:(NSString*)event count:(int)count { if (count == 0) { [self handleListenerRemovedWithEvent:event]; } } -(void)sanitycheckListeners //TODO: This can be optimized and unwound later. { if(listenerArray == nil){ listenerArray = [[NSArray alloc] initWithObjects: @"singletap", @"doubletap",@"twofingertap",@"swipe",@"pinch",@"longpress",nil]; } for (NSString * eventName in listenerArray) { if ([proxy _hasListeners:eventName]) { [self handleListenerAddedWithEvent:eventName]; } } } @end
{ "content_hash": "9c64dc2eb956b5e81e789b6fe22cad4b", "timestamp": "", "source": "github", "line_count": 1468, "max_line_length": 168, "avg_line_length": 30.469346049046322, "alnum_prop": 0.7180576359856021, "repo_name": "gtlaserbeast/imageCompression", "id": "fb34676a3e2483253c825a8deebaa281b0366289", "size": "45051", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "build/iphone/Classes/TiUIView.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "110855" }, { "name": "C++", "bytes": "19410" }, { "name": "D", "bytes": "703566" }, { "name": "JavaScript", "bytes": "127429" }, { "name": "Objective-C", "bytes": "3421977" }, { "name": "Objective-C++", "bytes": "8645" }, { "name": "Shell", "bytes": "1286" } ], "symlink_target": "" }
jest.mock('../../../../services/note.service'); const noteService = require('../../../../services/note.service'); const deleteNoteProcessResolver = require('../deleteNote.process.resolver'); it('should call createNote with provided text and ' + 'return created note', () => { noteService.deleteNoteById.mockReturnValue('deleted note'); const actual = deleteNoteProcessResolver({}, { id: 1 }); expect(actual).toEqual('deleted note'); expect(noteService.deleteNoteById).toHaveBeenCalledWith(1); });
{ "content_hash": "418e7d464a32eb3bfa4621431ab1d97e", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 76, "avg_line_length": 34.13333333333333, "alnum_prop": 0.705078125, "repo_name": "alexandarnikita/wen", "id": "55542330e49a1ac2e7edc945867bfbb0da68c64e", "size": "512", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/graphql/resolvers/deleteNote/test/deleteNote.process.resolver.test.js", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "2442" }, { "name": "JavaScript", "bytes": "180851" }, { "name": "Nginx", "bytes": "426" }, { "name": "Shell", "bytes": "1435" } ], "symlink_target": "" }
package org.antlr.tool; import org.antlr.runtime.Token; import org.stringtemplate.v4.ST; /** A problem with the symbols and/or meaning of a grammar such as rule * redefinition. */ public class GrammarSemanticsMessage extends Message { public Grammar g; /** Most of the time, we'll have a token such as an undefined rule ref * and so this will be set. */ public Token offendingToken; public GrammarSemanticsMessage(int msgID, Grammar g, Token offendingToken) { this(msgID,g,offendingToken,null,null); } public GrammarSemanticsMessage(int msgID, Grammar g, Token offendingToken, Object arg) { this(msgID,g,offendingToken,arg,null); } public GrammarSemanticsMessage(int msgID, Grammar g, Token offendingToken, Object arg, Object arg2) { super(msgID,arg,arg2); this.g = g; this.offendingToken = offendingToken; } public String toString() { line = 0; column = 0; if ( offendingToken!=null ) { line = offendingToken.getLine(); column = offendingToken.getCharPositionInLine(); } if ( g!=null ) { file = g.getFileName(); } ST st = getMessageTemplate(); if ( arg!=null ) { st.add("arg", arg); } if ( arg2!=null ) { st.add("arg2", arg2); } return super.toString(st); } }
{ "content_hash": "5387f320f5abe2eb25bccb3d0efbedad", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 71, "avg_line_length": 21.14516129032258, "alnum_prop": 0.6552250190694127, "repo_name": "stumoodie/VisualLanguageToolkit", "id": "1027182a22629002d2c432ab764f066b9e17c632", "size": "2827", "binary": false, "copies": "11", "ref": "refs/heads/master", "path": "lib/antlr-3.4/tool/src/main/java/org/antlr/tool/GrammarSemanticsMessage.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "250359" }, { "name": "C", "bytes": "711091" }, { "name": "C#", "bytes": "1841394" }, { "name": "C++", "bytes": "34675" }, { "name": "CSS", "bytes": "56807" }, { "name": "Erlang", "bytes": "158" }, { "name": "Java", "bytes": "6166480" }, { "name": "JavaScript", "bytes": "223551" }, { "name": "M", "bytes": "2106" }, { "name": "Objective-C", "bytes": "2837265" }, { "name": "PHP", "bytes": "56" }, { "name": "Pascal", "bytes": "491163" }, { "name": "Perl", "bytes": "112155" }, { "name": "Python", "bytes": "786230" }, { "name": "Ruby", "bytes": "728969" }, { "name": "Shell", "bytes": "12617" }, { "name": "Smalltalk", "bytes": "846" } ], "symlink_target": "" }
namespace Demo.ADTProcessing.Worker { class Program { static void Main(string[] args) { var worker = new Worker(); worker.Run(); } } }
{ "content_hash": "bba05bcaf22182332642c73137a72637", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 39, "avg_line_length": 17.818181818181817, "alnum_prop": 0.4846938775510204, "repo_name": "toddmeinershagen/Demo.ADTProcessing", "id": "24228a2d36627cbf2cb1c73668450050bf2f6d7a", "size": "198", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Demo.ADTProcessing.Worker/Program.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "312" }, { "name": "C#", "bytes": "68819" }, { "name": "PowerShell", "bytes": "1320" } ], "symlink_target": "" }
<?php // Controller class generated automatically by MDA process namespace MyCompany\MyProject\AppBundle\Controller; // Start of user code imports use Symfony\Bundle\FrameworkBundle\Controller\Controller; use JMS\SecurityExtraBundle\Annotation\Secure; use Symfony\Component\Security\Core\Exception\AccessDeniedException; use Symfony\Component\Security\Core\SecurityContext; use Symfony\Component\HttpFoundation\Response; // End of user code /* * */ class ViewController extends Controller { public $logo = "logo.gif"; public $copyright = "Société Générale BHFM"; public $contact = "Animation.cards@socgen.com"; public $userid = "#sys_userid#"; public $versioning = "V1.5.110924.c"; private $title = "#app_title#"; public $scope = "#sys_scope#"; /* * */ public function headerAction() { $out = "Output variable to be defined"; return $this->render('MyCompanyMyProjectAppBundle:View:header.html.twig', array('out' => $out )); } /* * */ public function contentAction() { $out = "Output variable to be defined"; return $this->render('MyCompanyMyProjectAppBundle:View:content.html.twig', array('out' => $out )); } /* * */ public function footerAction() { $out = "Output variable to be defined"; return $this->render('MyCompanyMyProjectAppBundle:View:footer.html.twig', array('out' => $out )); } /* * */ public function copyrightAction() { return $this->render('MyCompanyMyProjectAppBundle:ViewPart:copyright.html.twig', array('copyright' => $this->copyright)); } /* * */ public function versioningAction() { return $this->render('MyCompanyMyProjectAppBundle:ViewPart:versioning.html.twig', array('versioning' => $this->versioning)); } /* * */ public function contactAction() { return $this->render('MyCompanyMyProjectAppBundle:ViewPart:contact.html.twig', array('contact' => $this->contact)); } /* * */ public function emailAction($arg) { $out = $arg; return $this->render('MyCompanyMyProjectAppBundle:ViewPart:email.html.twig', array('out' => $out )); } /* * */ public function tokenAction($arg) { $out = $arg; return $this->render('MyCompanyMyProjectAppBundle:ViewPart:token.html.twig', array('out' => $out )); } /* * */ public function titleAction() { return $this->render('MyCompanyMyProjectAppBundle:ViewPart:title.html.twig', array('title' => $this->title)); } /* * */ public function logoAction() { return $this->render('MyCompanyMyProjectAppBundle:ViewPart:logo.html.twig', array('logo' => $this->logo)); } /* * */ public function imageAction($arg) { $out = $arg; return $this->render('MyCompanyMyProjectAppBundle:ViewPart:image.html.twig', array('out' => $out )); } /* * */ public function menuAction() { $out = "Output variable to be defined"; return $this->render('MyCompanyMyProjectAppBundle:ViewPart:menu.html.twig', array('out' => $out )); } /* * */ public function welcomeAction() { $out = "Output variable to be defined"; return $this->render('MyCompanyMyProjectAppBundle:ViewPart:welcome.html.twig', array('out' => $out )); } /* * */ public function translateAction($text,$domain) { $domain = $this->get('translator')->trans($text, array(), $domain); $out = $text; $out = $domain; return new Response($out ); } /* * */ public function useridAction() { $user = $this->get('security.context')->getToken()->getUser(); $this->userid = $this->get('translator')->trans($this->userid, array('%userid%' => $user->getUsername()), 'system'); return $this->render('MyCompanyMyProjectAppBundle:ViewPart:userid.html.twig', array('userid' => $this->userid)); } /* * */ public function scopeAction() { $user = $this->get('security.context')->getToken()->getUser(); $role = explode("_",implode("",$user->getRoles())); $scope = $role[3]; if($scope=='ANY') $scope = 'BHFM'; $this->scope = $this->get('translator')->trans($this->scope, array('%scope%' => $scope), 'system'); return $this->render('MyCompanyMyProjectAppBundle:ViewPart:scope.html.twig', array('scope' => $this->scope)); } /* * */ public function getTitle() { return $this->title; } } ?>
{ "content_hash": "658e2ffdad25721bf22bfb0194822dc5", "timestamp": "", "source": "github", "line_count": 222, "max_line_length": 102, "avg_line_length": 21.86036036036036, "alnum_prop": 0.5724294250978776, "repo_name": "ithone/pam", "id": "4a3c8b20678a4ef8dd42b4506042c86525929d34", "size": "4857", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/MyCompany/MyProject/AppBundle/Controller/ViewController.php", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "487640" }, { "name": "PHP", "bytes": "367769" } ], "symlink_target": "" }
var Dispatcher = require('flux').Dispatcher; module.exports = new Dispatcher();
{ "content_hash": "efdd8ebfe6db45bf1408142acdb42532", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 44, "avg_line_length": 20.5, "alnum_prop": 0.7317073170731707, "repo_name": "lumc-nested/nested-editor", "id": "c2daad79e5070a427043e73cdd7ac8f69d14c9e2", "size": "82", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/scripts/dispatchers/AppDispatcher.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6536" }, { "name": "HTML", "bytes": "640" }, { "name": "JavaScript", "bytes": "659777" } ], "symlink_target": "" }
/* * The Plaid API * * The Plaid REST API. Please see https://plaid.com/docs/api for more details. * * API version: 2020-09-14_1.205.3 */ // Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. package plaid import ( "encoding/json" "fmt" ) // FDXPartyRegistry The registry containing the party’s registration with name and id type FDXPartyRegistry string var _ = fmt.Printf // List of FDXPartyRegistry const ( FDXPARTYREGISTRY_FDX FDXPartyRegistry = "FDX" FDXPARTYREGISTRY_GLEIF FDXPartyRegistry = "GLEIF" FDXPARTYREGISTRY_ICANN FDXPartyRegistry = "ICANN" FDXPARTYREGISTRY_PRIVATE FDXPartyRegistry = "PRIVATE" ) var allowedFDXPartyRegistryEnumValues = []FDXPartyRegistry{ "FDX", "GLEIF", "ICANN", "PRIVATE", } func (v *FDXPartyRegistry) UnmarshalJSON(src []byte) error { var value string err := json.Unmarshal(src, &value) if err != nil { return err } enumTypeValue := FDXPartyRegistry(value) *v = enumTypeValue return nil } // NewFDXPartyRegistryFromValue returns a pointer to a valid FDXPartyRegistry // for the value passed as argument, or an error if the value passed is not allowed by the enum func NewFDXPartyRegistryFromValue(v string) (*FDXPartyRegistry, error) { ev := FDXPartyRegistry(v) return &ev, nil } // IsValid return true if the value is valid for the enum, false otherwise func (v FDXPartyRegistry) IsValid() bool { for _, existing := range allowedFDXPartyRegistryEnumValues { if existing == v { return true } } return false } // Ptr returns reference to FDXPartyRegistry value func (v FDXPartyRegistry) Ptr() *FDXPartyRegistry { return &v } type NullableFDXPartyRegistry struct { value *FDXPartyRegistry isSet bool } func (v NullableFDXPartyRegistry) Get() *FDXPartyRegistry { return v.value } func (v *NullableFDXPartyRegistry) Set(val *FDXPartyRegistry) { v.value = val v.isSet = true } func (v NullableFDXPartyRegistry) IsSet() bool { return v.isSet } func (v *NullableFDXPartyRegistry) Unset() { v.value = nil v.isSet = false } func NewNullableFDXPartyRegistry(val *FDXPartyRegistry) *NullableFDXPartyRegistry { return &NullableFDXPartyRegistry{value: val, isSet: true} } func (v NullableFDXPartyRegistry) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableFDXPartyRegistry) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
{ "content_hash": "3e335b24e506bb3bebaedb625518bc9e", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 95, "avg_line_length": 21.81081081081081, "alnum_prop": 0.7422552664188352, "repo_name": "plaid/plaid-go", "id": "ee103c6a7032023c5bdf8aeb36f005ae09fd0b37", "size": "2423", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "plaid/model_fdx_party_registry.go", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "129" }, { "name": "Go", "bytes": "61884" }, { "name": "Makefile", "bytes": "114" }, { "name": "Mustache", "bytes": "46930" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <HTML style="overflow:auto;"> <HEAD> <meta name="generator" content="JDiff v1.1.0"> <!-- Generated by the JDiff Javadoc doclet --> <!-- (http://www.jdiff.org) --> <meta name="description" content="JDiff is a Javadoc doclet which generates an HTML report of all the packages, classes, constructors, methods, and fields which have been removed, added or changed in any way, including their documentation, when two APIs are compared."> <meta name="keywords" content="diff, jdiff, javadiff, java diff, java difference, API difference, difference between two APIs, API diff, Javadoc, doclet"> <TITLE> android.view.ContextThemeWrapper </TITLE> <link href="../../../../assets/android-developer-docs.css" rel="stylesheet" type="text/css" /> <link href="../stylesheet-jdiff.css" rel="stylesheet" type="text/css" /> <noscript> <style type="text/css"> body{overflow:auto;} #body-content{position:relative; top:0;} #doc-content{overflow:visible;border-left:3px solid #666;} #side-nav{padding:0;} #side-nav .toggle-list ul {display:block;} #resize-packages-nav{border-bottom:3px solid #666;} </style> </noscript> <style type="text/css"> </style> </HEAD> <BODY> <!-- Start of nav bar --> <a name="top"></a> <div id="header" style="margin-bottom:0;padding-bottom:0;"> <div id="headerLeft"> <a href="../../../../index.html" tabindex="-1" target="_top"><img src="../../../../assets/images/bg_logo.png" alt="Android Developers" /></a> </div> <div id="headerRight"> <div id="headerLinks"> <!-- <img src="/assets/images/icon_world.jpg" alt="" /> --> <span class="text"> <!-- &nbsp;<a href="#">English</a> | --> <nobr><a href="http://developer.android.com" target="_top">Android Developers</a> | <a href="http://www.android.com" target="_top">Android.com</a></nobr> </span> </div> <div class="and-diff-id" style="margin-top:6px;margin-right:8px;"> <table class="diffspectable"> <tr> <td colspan="2" class="diffspechead">API Diff Specification</td> </tr> <tr> <td class="diffspec" style="padding-top:.25em">To Level:</td> <td class="diffvaluenew" style="padding-top:.25em">17</td> </tr> <tr> <td class="diffspec">From Level:</td> <td class="diffvalueold">16</td> </tr> <tr> <td class="diffspec">Generated</td> <td class="diffvalue">2012.11.12 19:50</td> </tr> </table> </div><!-- End and-diff-id --> <div class="and-diff-id" style="margin-right:8px;"> <table class="diffspectable"> <tr> <td class="diffspec" colspan="2"><a href="jdiff_statistics.html">Statistics</a> </tr> </table> </div> <!-- End and-diff-id --> </div> <!-- End headerRight --> </div> <!-- End header --> <div id="body-content" xstyle="padding:12px;padding-right:18px;"> <div id="doc-content" style="position:relative;"> <div id="mainBodyFluid"> <H2> Class android.view.<A HREF="../../../../reference/android/view/ContextThemeWrapper.html" target="_top"><font size="+2"><code>ContextThemeWrapper</code></font></A> </H2> <a NAME="constructors"></a> <a NAME="methods"></a> <p> <a NAME="Added"></a> <TABLE summary="Added Methods" WIDTH="100%"> <TR> <TH VALIGN="TOP" COLSPAN=2>Added Methods</FONT></TD> </TH> <TR BGCOLOR="#FFFFFF" CLASS="TableRowColor"> <TD VALIGN="TOP" WIDTH="25%"> <A NAME="android.view.ContextThemeWrapper.applyOverrideConfiguration_added(android.content.res.Configuration)"></A> <nobr><code>void</code>&nbsp;<A HREF="../../../../reference/android/view/ContextThemeWrapper.html#applyOverrideConfiguration(android.content.res.Configuration)" target="_top"><code>applyOverrideConfiguration</code></A>(<code>Configuration</code>)</nobr> </TD> <TD>&nbsp;</TD> </TR> </TABLE> &nbsp; <a NAME="fields"></a> </div> <div id="footer"> <div id="copyright"> Except as noted, this content is licensed under <a href="http://creativecommons.org/licenses/by/2.5/"> Creative Commons Attribution 2.5</a>. For details and restrictions, see the <a href="/license.html">Content License</a>. </div> <div id="footerlinks"> <p> <a href="http://www.android.com/terms.html">Site Terms of Service</a> - <a href="http://www.android.com/privacy.html">Privacy Policy</a> - <a href="http://www.android.com/branding.html">Brand Guidelines</a> </p> </div> </div> <!-- end footer --> </div><!-- end doc-content --> </div> <!-- end body-content --> <script src="//www.google-analytics.com/ga.js" type="text/javascript"> </script> <script type="text/javascript"> try { var pageTracker = _gat._getTracker("UA-5831155-1"); pageTracker._setAllowAnchor(true); pageTracker._initData(); pageTracker._trackPageview(); } catch(e) {} </script> </BODY> </HTML>
{ "content_hash": "9e51cedfb9e413e77f06989510c00b0e", "timestamp": "", "source": "github", "line_count": 122, "max_line_length": 269, "avg_line_length": 39.92622950819672, "alnum_prop": 0.6403202627797167, "repo_name": "AzureZhao/android-developer-cn", "id": "ee15d0791cb72ce012bef2828de6016d79902a93", "size": "4871", "binary": false, "copies": "6", "ref": "refs/heads/4.4.zh_cn", "path": "sdk/api_diff/17/changes/android.view.ContextThemeWrapper.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "225261" }, { "name": "HTML", "bytes": "481791360" }, { "name": "JavaScript", "bytes": "640571" } ], "symlink_target": "" }
/* global define, module, require, exports */ (function (root, factory) { if (typeof define === 'function' && define.amd) { define(['jquery', 'd3', 'nf.CanvasUtils', 'nf.Common', 'nf.Dialog', 'nf.Client', 'nf.ErrorHandler', 'nf.Clipboard', 'nf.Snippet', 'nf.GoTo', 'nf.ng.Bridge', 'nf.Shell', 'nf.ComponentState', 'nf.Draggable', 'nf.Birdseye', 'nf.Connection', 'nf.Graph', 'nf.ProcessGroupConfiguration', 'nf.ProcessorConfiguration', 'nf.ProcessorDetails', 'nf.LabelConfiguration', 'nf.RemoteProcessGroupConfiguration', 'nf.RemoteProcessGroupDetails', 'nf.PortConfiguration', 'nf.PortDetails', 'nf.ConnectionConfiguration', 'nf.ConnectionDetails', 'nf.PolicyManagement', 'nf.RemoteProcessGroup', 'nf.Label', 'nf.Processor', 'nf.RemoteProcessGroupPorts', 'nf.ComponentVersion', 'nf.QueueListing', 'nf.StatusHistory'], function ($, d3, nfCanvasUtils, nfCommon, nfDialog, nfClient, nfErrorHandler, nfClipboard, nfSnippet, nfGoto, nfNgBridge, nfShell, nfComponentState, nfDraggable, nfBirdseye, nfConnection, nfGraph, nfProcessGroupConfiguration, nfProcessorConfiguration, nfProcessorDetails, nfLabelConfiguration, nfRemoteProcessGroupConfiguration, nfRemoteProcessGroupDetails, nfPortConfiguration, nfPortDetails, nfConnectionConfiguration, nfConnectionDetails, nfPolicyManagement, nfRemoteProcessGroup, nfLabel, nfProcessor, nfRemoteProcessGroupPorts, nfComponentVersion, nfQueueListing, nfStatusHistory) { return (nf.Actions = factory($, d3, nfCanvasUtils, nfCommon, nfDialog, nfClient, nfErrorHandler, nfClipboard, nfSnippet, nfGoto, nfNgBridge, nfShell, nfComponentState, nfDraggable, nfBirdseye, nfConnection, nfGraph, nfProcessGroupConfiguration, nfProcessorConfiguration, nfProcessorDetails, nfLabelConfiguration, nfRemoteProcessGroupConfiguration, nfRemoteProcessGroupDetails, nfPortConfiguration, nfPortDetails, nfConnectionConfiguration, nfConnectionDetails, nfPolicyManagement, nfRemoteProcessGroup, nfLabel, nfProcessor, nfRemoteProcessGroupPorts, nfComponentVersion, nfQueueListing, nfStatusHistory)); }); } else if (typeof exports === 'object' && typeof module === 'object') { module.exports = (nf.Actions = factory(require('jquery'), require('d3'), require('nf.CanvasUtils'), require('nf.Common'), require('nf.Dialog'), require('nf.Client'), require('nf.ErrorHandler'), require('nf.Clipboard'), require('nf.Snippet'), require('nf.GoTo'), require('nf.ng.Bridge'), require('nf.Shell'), require('nf.ComponentState'), require('nf.Draggable'), require('nf.Birdseye'), require('nf.Connection'), require('nf.Graph'), require('nf.ProcessGroupConfiguration'), require('nf.ProcessorConfiguration'), require('nf.ProcessorDetails'), require('nf.LabelConfiguration'), require('nf.RemoteProcessGroupConfiguration'), require('nf.RemoteProcessGroupDetails'), require('nf.PortConfiguration'), require('nf.PortDetails'), require('nf.ConnectionConfiguration'), require('nf.ConnectionDetails'), require('nf.PolicyManagement'), require('nf.RemoteProcessGroup'), require('nf.Label'), require('nf.Processor'), require('nf.RemoteProcessGroupPorts'), require('nf.ComponentVersion'), require('nf.QueueListing'), require('nf.StatusHistory'))); } else { nf.Actions = factory(root.$, root.d3, root.nf.CanvasUtils, root.nf.Common, root.nf.Dialog, root.nf.Client, root.nf.ErrorHandler, root.nf.Clipboard, root.nf.Snippet, root.nf.GoTo, root.nf.ng.Bridge, root.nf.Shell, root.nf.ComponentState, root.nf.Draggable, root.nf.Birdseye, root.nf.Connection, root.nf.Graph, root.nf.ProcessGroupConfiguration, root.nf.ProcessorConfiguration, root.nf.ProcessorDetails, root.nf.LabelConfiguration, root.nf.RemoteProcessGroupConfiguration, root.nf.RemoteProcessGroupDetails, root.nf.PortConfiguration, root.nf.PortDetails, root.nf.ConnectionConfiguration, root.nf.ConnectionDetails, root.nf.PolicyManagement, root.nf.RemoteProcessGroup, root.nf.Label, root.nf.Processor, root.nf.RemoteProcessGroupPorts, root.nf.ComponentVersion, root.nf.QueueListing, root.nf.StatusHistory); } }(this, function ($, d3, nfCanvasUtils, nfCommon, nfDialog, nfClient, nfErrorHandler, nfClipboard, nfSnippet, nfGoto, nfNgBridge, nfShell, nfComponentState, nfDraggable, nfBirdseye, nfConnection, nfGraph, nfProcessGroupConfiguration, nfProcessorConfiguration, nfProcessorDetails, nfLabelConfiguration, nfRemoteProcessGroupConfiguration, nfRemoteProcessGroupDetails, nfPortConfiguration, nfPortDetails, nfConnectionConfiguration, nfConnectionDetails, nfPolicyManagement, nfRemoteProcessGroup, nfLabel, nfProcessor, nfRemoteProcessGroupPorts, nfComponentVersion, nfQueueListing, nfStatusHistory) { 'use strict'; var config = { urls: { api: '../nifi-api', controller: '../nifi-api/controller' } }; /** * Initializes the drop request status dialog. */ var initializeDropRequestStatusDialog = function () { // configure the drop request status dialog $('#drop-request-status-dialog').modal({ scrollableContentStyle: 'scrollable', handler: { close: function () { // clear the current button model $('#drop-request-status-dialog').modal('setButtonModel', []); } } }); }; /** * Updates the resource with the specified entity. * * @param {string} uri * @param {object} entity */ var updateResource = function (uri, entity) { return $.ajax({ type: 'PUT', url: uri, data: JSON.stringify(entity), dataType: 'json', contentType: 'application/json' }).fail(function (xhr, status, error) { nfDialog.showOkDialog({ headerText: 'Update Resource', dialogContent: nfCommon.escapeHtml(xhr.responseText) }); }); }; // create a method for updating process groups and processors var updateProcessGroup = function (response) { $.ajax({ type: 'GET', url: config.urls.api + '/flow/process-groups/' + encodeURIComponent(response.id), dataType: 'json' }).done(function (response) { nfGraph.set(response.processGroupFlow.flow); }); }; // determine if the source of this connection is part of the selection var isSourceSelected = function (connection, selection) { return selection.filter(function (d) { return nfCanvasUtils.getConnectionSourceComponentId(connection) === d.id; }).size() > 0; }; var nfActions = { /** * Initializes the actions. */ init: function () { initializeDropRequestStatusDialog(); }, /** * Enters the specified process group. * * @param {selection} selection The the currently selected component */ enterGroup: function (selection) { if (selection.size() === 1 && nfCanvasUtils.isProcessGroup(selection)) { var selectionData = selection.datum(); nfCanvasUtils.getComponentByType('ProcessGroup').enterGroup(selectionData.id); } }, /** * Exits the current process group but entering the parent group. */ leaveGroup: function () { nfCanvasUtils.getComponentByType('ProcessGroup').enterGroup(nfCanvasUtils.getParentGroupId()); }, /** * Refresh the flow of the remote process group in the specified selection. * * @param {selection} selection */ refreshRemoteFlow: function (selection) { if (selection.size() === 1 && nfCanvasUtils.isRemoteProcessGroup(selection)) { var d = selection.datum(); var refreshTimestamp = d.component.flowRefreshed; var setLastRefreshed = function (lastRefreshed) { // set the new value in case the component is redrawn during the refresh d.component.flowRefreshed = lastRefreshed; // update the UI to show last refreshed if appropriate if (selection.classed('visible')) { selection.select('text.remote-process-group-last-refresh') .text(function () { return lastRefreshed; }); } }; var poll = function (nextDelay) { $.ajax({ type: 'GET', url: d.uri, dataType: 'json' }).done(function (response) { var remoteProcessGroup = response.component; // the timestamp has not updated yet, poll again if (refreshTimestamp === remoteProcessGroup.flowRefreshed) { schedule(nextDelay); } else { nfRemoteProcessGroup.set(response); // reload the group's connections var connections = nfConnection.getComponentConnections(remoteProcessGroup.id); $.each(connections, function (_, connection) { if (connection.permissions.canRead) { nfConnection.reload(connection.id); } }); } }); }; var schedule = function (delay) { if (delay <= 32) { setTimeout(function () { poll(delay * 2); }, delay * 1000); } else { // reset to the previous value since the contents could not be updated (set to null?) setLastRefreshed(refreshTimestamp); } }; setLastRefreshed('Refreshing...'); poll(1); } }, /** * Opens the remote process group in the specified selection. * * @param {selection} selection The selection */ openUri: function (selection) { if (selection.size() === 1 && nfCanvasUtils.isRemoteProcessGroup(selection)) { var selectionData = selection.datum(); var uri = selectionData.component.targetUri; if (!nfCommon.isBlank(uri)) { window.open(encodeURI(uri)); } else { nfDialog.showOkDialog({ headerText: 'Remote Process Group', dialogContent: 'No target URI defined.' }); } } }, /** * Shows and selects the source of the connection in the specified selection. * * @param {selection} selection The selection */ showSource: function (selection) { if (selection.size() === 1 && nfCanvasUtils.isConnection(selection)) { var selectionData = selection.datum(); // the source is in the current group if (selectionData.sourceGroupId === nfCanvasUtils.getGroupId()) { var source = d3.select('#id-' + selectionData.sourceId); nfActions.show(source); } else if (selectionData.sourceType === 'REMOTE_OUTPUT_PORT') { // if the source is remote var remoteSource = d3.select('#id-' + selectionData.sourceGroupId); nfActions.show(remoteSource); } else { // if the source is local but in a sub group nfCanvasUtils.showComponent(selectionData.sourceGroupId, selectionData.sourceId); } } }, /** * Shows and selects the destination of the connection in the specified selection. * * @param {selection} selection The selection */ showDestination: function (selection) { if (selection.size() === 1 && nfCanvasUtils.isConnection(selection)) { var selectionData = selection.datum(); // the destination is in the current group or its remote if (selectionData.destinationGroupId === nfCanvasUtils.getGroupId()) { var destination = d3.select('#id-' + selectionData.destinationId); nfActions.show(destination); } else if (selectionData.destinationType === 'REMOTE_INPUT_PORT') { // if the destination is remote var remoteDestination = d3.select('#id-' + selectionData.destinationGroupId); nfActions.show(remoteDestination); } else { // if the destination is local but in a sub group nfCanvasUtils.showComponent(selectionData.destinationGroupId, selectionData.destinationId); } } }, /** * Shows the downstream components from the specified selection. * * @param {selection} selection The selection */ showDownstream: function (selection) { if (selection.size() === 1 && !nfCanvasUtils.isConnection(selection)) { // open the downstream dialog according to the selection if (nfCanvasUtils.isProcessor(selection)) { nfGoto.showDownstreamFromProcessor(selection); } else if (nfCanvasUtils.isFunnel(selection)) { nfGoto.showDownstreamFromFunnel(selection); } else if (nfCanvasUtils.isInputPort(selection)) { nfGoto.showDownstreamFromInputPort(selection); } else if (nfCanvasUtils.isOutputPort(selection)) { nfGoto.showDownstreamFromOutputPort(selection); } else if (nfCanvasUtils.isProcessGroup(selection) || nfCanvasUtils.isRemoteProcessGroup(selection)) { nfGoto.showDownstreamFromGroup(selection); } } }, /** * Shows the upstream components from the specified selection. * * @param {selection} selection The selection */ showUpstream: function (selection) { if (selection.size() === 1 && !nfCanvasUtils.isConnection(selection)) { // open the downstream dialog according to the selection if (nfCanvasUtils.isProcessor(selection)) { nfGoto.showUpstreamFromProcessor(selection); } else if (nfCanvasUtils.isFunnel(selection)) { nfGoto.showUpstreamFromFunnel(selection); } else if (nfCanvasUtils.isInputPort(selection)) { nfGoto.showUpstreamFromInputPort(selection); } else if (nfCanvasUtils.isOutputPort(selection)) { nfGoto.showUpstreamFromOutputPort(selection); } else if (nfCanvasUtils.isProcessGroup(selection) || nfCanvasUtils.isRemoteProcessGroup(selection)) { nfGoto.showUpstreamFromGroup(selection); } } }, /** * Shows and selects the component in the specified selection. * * @param {selection} selection The selection */ show: function (selection) { // deselect the current selection var currentlySelected = nfCanvasUtils.getSelection(); currentlySelected.classed('selected', false); // select only the component/connection in question selection.classed('selected', true); if (selection.size() === 1) { nfActions.center(selection); } else { nfNgBridge.injector.get('navigateCtrl').zoomFit(); } // update URL deep linking params nfCanvasUtils.setURLParameters(nfCanvasUtils.getGroupId(), selection); // inform Angular app that values have changed nfNgBridge.digest(); }, /** * Selects all components in the specified selection. * * @param {selection} selection Selection of components to select */ select: function (selection) { selection.classed('selected', true); }, /** * Selects all components. */ selectAll: function () { nfActions.select(d3.selectAll('g.component, g.connection')); }, /** * Centers the component in the specified selection. * * @argument {selection} selection The selection */ center: function (selection) { if (selection.size() === 1) { var box; if (nfCanvasUtils.isConnection(selection)) { var x, y; var d = selection.datum(); // get the position of the connection label if (d.bends.length > 0) { var i = Math.min(Math.max(0, d.labelIndex), d.bends.length - 1); x = d.bends[i].x; y = d.bends[i].y; } else { x = (d.start.x + d.end.x) / 2; y = (d.start.y + d.end.y) / 2; } box = { x: x, y: y, width: 1, height: 1 }; } else { var selectionData = selection.datum(); var selectionPosition = selectionData.position; box = { x: selectionPosition.x, y: selectionPosition.y, width: selectionData.dimensions.width, height: selectionData.dimensions.height }; } // center on the component nfCanvasUtils.centerBoundingBox(box); // refresh the canvas nfCanvasUtils.refreshCanvasView({ transition: true }); } }, /** * Enables all eligible selected components. * * @argument {selection} selection The selection */ enable: function (selection) { var componentsToEnable = nfCanvasUtils.filterEnable(selection); if (componentsToEnable.empty()) { nfDialog.showOkDialog({ headerText: 'Enable Components', dialogContent: 'No eligible components are selected. Please select the components to be enabled and ensure they are no longer running.' }); } else { var enableRequests = []; // enable the selected processors componentsToEnable.each(function (d) { var selected = d3.select(this); // build the entity var entity = { 'revision': nfClient.getRevision(d), 'component': { 'id': d.id, 'state': 'STOPPED' } }; enableRequests.push(updateResource(d.uri, entity).done(function (response) { nfCanvasUtils.getComponentByType(d.type).set(response); })); }); // inform Angular app once the updates have completed if (enableRequests.length > 0) { $.when.apply(window, enableRequests).always(function () { nfNgBridge.digest(); }); } } }, /** * Disables all eligible selected components. * * @argument {selection} selection The selection */ disable: function (selection) { var componentsToDisable = nfCanvasUtils.filterDisable(selection); if (componentsToDisable.empty()) { nfDialog.showOkDialog({ headerText: 'Disable Components', dialogContent: 'No eligible components are selected. Please select the components to be disabled and ensure they are no longer running.' }); } else { var disableRequests = []; // disable the selected components componentsToDisable.each(function (d) { var selected = d3.select(this); // build the entity var entity = { 'revision': nfClient.getRevision(d), 'component': { 'id': d.id, 'state': 'DISABLED' } }; disableRequests.push(updateResource(d.uri, entity).done(function (response) { nfCanvasUtils.getComponentByType(d.type).set(response); })); }); // inform Angular app once the updates have completed if (disableRequests.length > 0) { $.when.apply(window, disableRequests).always(function () { nfNgBridge.digest(); }); } } }, /** * Opens provenance with the component in the specified selection. * * @argument {selection} selection The selection */ openProvenance: function (selection) { if (selection.size() === 1) { var selectionData = selection.datum(); // open the provenance page with the specified component nfShell.showPage('provenance?' + $.param({ componentId: selectionData.id })); } }, /** * Starts the components in the specified selection. * * @argument {selection} selection The selection */ start: function (selection) { if (selection.empty()) { // build the entity var entity = { 'id': nfCanvasUtils.getGroupId(), 'state': 'RUNNING' }; updateResource(config.urls.api + '/flow/process-groups/' + encodeURIComponent(nfCanvasUtils.getGroupId()), entity).done(updateProcessGroup); } else { var componentsToStart = selection.filter(function (d) { return nfCanvasUtils.isRunnable(d3.select(this)); }); // ensure there are startable components selected if (componentsToStart.empty()) { nfDialog.showOkDialog({ headerText: 'Start Components', dialogContent: 'No eligible components are selected. Please select the components to be started and ensure they are no longer running.' }); } else { var startRequests = []; // start each selected component componentsToStart.each(function (d) { var selected = d3.select(this); // prepare the request var uri, entity; if (nfCanvasUtils.isProcessGroup(selected)) { uri = config.urls.api + '/flow/process-groups/' + encodeURIComponent(d.id); entity = { 'id': d.id, 'state': 'RUNNING' } } else { uri = d.uri; entity = { 'revision': nfClient.getRevision(d), 'component': { 'id': d.id, 'state': 'RUNNING' } }; } startRequests.push(updateResource(uri, entity).done(function (response) { if (nfCanvasUtils.isProcessGroup(selected)) { nfCanvasUtils.getComponentByType('ProcessGroup').reload(d.id); } else { nfCanvasUtils.getComponentByType(d.type).set(response); } })); }); // inform Angular app once the updates have completed if (startRequests.length > 0) { $.when.apply(window, startRequests).always(function () { nfNgBridge.digest(); }); } } } }, /** * Stops the components in the specified selection. * * @argument {selection} selection The selection */ stop: function (selection) { if (selection.empty()) { // build the entity var entity = { 'id': nfCanvasUtils.getGroupId(), 'state': 'STOPPED' }; updateResource(config.urls.api + '/flow/process-groups/' + encodeURIComponent(nfCanvasUtils.getGroupId()), entity).done(updateProcessGroup); } else { var componentsToStop = selection.filter(function (d) { return nfCanvasUtils.isStoppable(d3.select(this)); }); // ensure there are some component to stop if (componentsToStop.empty()) { nfDialog.showOkDialog({ headerText: 'Stop Components', dialogContent: 'No eligible components are selected. Please select the components to be stopped.' }); } else { var stopRequests = []; // stop each selected component componentsToStop.each(function (d) { var selected = d3.select(this); // prepare the request var uri, entity; if (nfCanvasUtils.isProcessGroup(selected)) { uri = config.urls.api + '/flow/process-groups/' + encodeURIComponent(d.id); entity = { 'id': d.id, 'state': 'STOPPED' }; } else { uri = d.uri; entity = { 'revision': nfClient.getRevision(d), 'component': { 'id': d.id, 'state': 'STOPPED' } }; } stopRequests.push(updateResource(uri, entity).done(function (response) { if (nfCanvasUtils.isProcessGroup(selected)) { nfCanvasUtils.getComponentByType('ProcessGroup').reload(d.id); } else { nfCanvasUtils.getComponentByType(d.type).set(response); } })); }); // inform Angular app once the updates have completed if (stopRequests.length > 0) { $.when.apply(window, stopRequests).always(function () { nfNgBridge.digest(); }); } } } }, /** * Enables transmission for the components in the specified selection. * * @argument {selection} selection The selection */ enableTransmission: function (selection) { var componentsToEnable = selection.filter(function (d) { return nfCanvasUtils.canStartTransmitting(d3.select(this)); }); // start each selected component componentsToEnable.each(function (d) { // build the entity var entity = { 'revision': nfClient.getRevision(d), 'component': { 'id': d.id, 'transmitting': true } }; // start transmitting updateResource(d.uri, entity).done(function (response) { nfRemoteProcessGroup.set(response); }); }); }, /** * Disables transmission for the components in the specified selection. * * @argument {selection} selection The selection */ disableTransmission: function (selection) { var componentsToDisable = selection.filter(function (d) { return nfCanvasUtils.canStopTransmitting(d3.select(this)); }); // stop each selected component componentsToDisable.each(function (d) { // build the entity var entity = { 'revision': nfClient.getRevision(d), 'component': { 'id': d.id, 'transmitting': false } }; updateResource(d.uri, entity).done(function (response) { nfRemoteProcessGroup.set(response); }); }); }, /** * Shows the configuration dialog for the specified selection. * * @param {selection} selection Selection of the component to be configured */ showConfiguration: function (selection) { if (selection.empty()) { nfProcessGroupConfiguration.showConfiguration(nfCanvasUtils.getGroupId()); } else if (selection.size() === 1) { var selectionData = selection.datum(); if (nfCanvasUtils.isProcessor(selection)) { nfProcessorConfiguration.showConfiguration(selection); } else if (nfCanvasUtils.isLabel(selection)) { nfLabelConfiguration.showConfiguration(selection); } else if (nfCanvasUtils.isProcessGroup(selection)) { nfProcessGroupConfiguration.showConfiguration(selectionData.id); } else if (nfCanvasUtils.isRemoteProcessGroup(selection)) { nfRemoteProcessGroupConfiguration.showConfiguration(selection); } else if (nfCanvasUtils.isInputPort(selection) || nfCanvasUtils.isOutputPort(selection)) { nfPortConfiguration.showConfiguration(selection); } else if (nfCanvasUtils.isConnection(selection)) { nfConnectionConfiguration.showConfiguration(selection); } } }, /** * Opens the policy management page for the selected component. * * @param selection */ managePolicies: function(selection) { if (selection.size() <= 1) { nfPolicyManagement.showComponentPolicy(selection); } }, // Defines an action for showing component details (like configuration but read only). showDetails: function (selection) { if (selection.empty()) { nfProcessGroupConfiguration.showConfiguration(nfCanvasUtils.getGroupId()); } else if (selection.size() === 1) { var selectionData = selection.datum(); if (nfCanvasUtils.isProcessor(selection)) { nfProcessorDetails.showDetails(nfCanvasUtils.getGroupId(), selectionData.id); } else if (nfCanvasUtils.isProcessGroup(selection)) { nfProcessGroupConfiguration.showConfiguration(selectionData.id); } else if (nfCanvasUtils.isRemoteProcessGroup(selection)) { nfRemoteProcessGroupDetails.showDetails(selection); } else if (nfCanvasUtils.isInputPort(selection) || nfCanvasUtils.isOutputPort(selection)) { nfPortDetails.showDetails(selection); } else if (nfCanvasUtils.isConnection(selection)) { nfConnectionDetails.showDetails(nfCanvasUtils.getGroupId(), selectionData.id); } } }, /** * Shows the usage documentation for the component in the specified selection. * * @param {selection} selection The selection */ showUsage: function (selection) { if (selection.size() === 1 && nfCanvasUtils.isProcessor(selection)) { var selectionData = selection.datum(); nfShell.showPage('../nifi-docs/documentation?' + $.param({ select: selectionData.component.type, group: selectionData.component.bundle.group, artifact: selectionData.component.bundle.artifact, version: selectionData.component.bundle.version })); } }, /** * Shows the stats for the specified selection. * * @argument {selection} selection The selection */ showStats: function (selection) { if (selection.size() === 1) { var selectionData = selection.datum(); if (nfCanvasUtils.isProcessor(selection)) { nfStatusHistory.showProcessorChart(nfCanvasUtils.getGroupId(), selectionData.id); } else if (nfCanvasUtils.isProcessGroup(selection)) { nfStatusHistory.showProcessGroupChart(nfCanvasUtils.getGroupId(), selectionData.id); } else if (nfCanvasUtils.isRemoteProcessGroup(selection)) { nfStatusHistory.showRemoteProcessGroupChart(nfCanvasUtils.getGroupId(), selectionData.id); } else if (nfCanvasUtils.isConnection(selection)) { nfStatusHistory.showConnectionChart(nfCanvasUtils.getGroupId(), selectionData.id); } } }, /** * Opens the remote ports dialog for the remote process group in the specified selection. * * @param {selection} selection The selection */ remotePorts: function (selection) { if (selection.size() === 1 && nfCanvasUtils.isRemoteProcessGroup(selection)) { nfRemoteProcessGroupPorts.showPorts(selection); } }, /** * Reloads the status for the entire canvas (components and flow.) */ reload: function () { nfCanvasUtils.reload({ 'transition': true }); }, /** * Deletes the component in the specified selection. * * @param {selection} selection The selection containing the component to be removed */ 'delete': function (selection) { if (nfCommon.isUndefined(selection) || selection.empty()) { nfDialog.showOkDialog({ headerText: 'Reload', dialogContent: 'No eligible components are selected. Please select the components to be deleted.' }); } else { if (selection.size() === 1) { var selectionData = selection.datum(); var revision = nfClient.getRevision(selectionData); $.ajax({ type: 'DELETE', url: selectionData.uri + '?' + $.param({ version: revision.version, clientId: revision.clientId }), dataType: 'json' }).done(function (response) { // remove the component/connection in question nfCanvasUtils.getComponentByType(selectionData.type).remove(selectionData.id); // if the selection is a connection, reload the source and destination accordingly if (nfCanvasUtils.isConnection(selection) === false) { var connections = nfConnection.getComponentConnections(selectionData.id); if (connections.length > 0) { var ids = []; $.each(connections, function (_, connection) { ids.push(connection.id); }); // remove the corresponding connections nfConnection.remove(ids); } } // update URL deep linking params nfCanvasUtils.setURLParameters(); // refresh the birdseye nfBirdseye.refresh(); // inform Angular app values have changed nfNgBridge.digest(); }).fail(nfErrorHandler.handleAjaxError); } else { var parentGroupId = nfCanvasUtils.getGroupId(); // create a snippet for the specified component and link to the data flow var snippet = nfSnippet.marshal(selection, parentGroupId); nfSnippet.create(snippet).done(function (response) { // remove the snippet, effectively removing the components nfSnippet.remove(response.snippet.id).done(function () { var components = d3.map(); // add the id to the type's array var addComponent = function (type, id) { if (!components.has(type)) { components.set(type, []); } components.get(type).push(id); }; // go through each component being removed selection.each(function (d) { // remove the corresponding entry addComponent(d.type, d.id); // if this is not a connection, see if it has any connections that need to be removed if (d.type !== 'Connection') { var connections = nfConnection.getComponentConnections(d.id); if (connections.length > 0) { $.each(connections, function (_, connection) { addComponent('Connection', connection.id); }); } } }); // remove all the non connections in the snippet first components.forEach(function (type, ids) { if (type !== 'Connection') { nfCanvasUtils.getComponentByType(type).remove(ids); } }); // then remove all the connections if (components.has('Connection')) { nfConnection.remove(components.get('Connection')); } // update URL deep linking params nfCanvasUtils.setURLParameters(); // refresh the birdseye nfBirdseye.refresh(); // inform Angular app values have changed nfNgBridge.digest(); }).fail(nfErrorHandler.handleAjaxError); }).fail(nfErrorHandler.handleAjaxError); } } }, /** * Deletes the flow files in the specified connection. * * @param {type} selection */ emptyQueue: function (selection) { if (selection.size() !== 1 || !nfCanvasUtils.isConnection(selection)) { return; } // prompt the user before emptying the queue nfDialog.showYesNoDialog({ headerText: 'Empty Queue', dialogContent: 'Are you sure you want to empty this queue? All FlowFiles waiting at the time of the request will be removed.', noText: 'Cancel', yesText: 'Empty', yesHandler: function () { // get the connection data var connection = selection.datum(); var MAX_DELAY = 4; var cancelled = false; var dropRequest = null; var dropRequestTimer = null; // updates the progress bar var updateProgress = function (percentComplete) { // remove existing labels var progressBar = $('#drop-request-percent-complete'); progressBar.find('div.progress-label').remove(); progressBar.find('md-progress-linear').remove(); // update the progress bar var label = $('<div class="progress-label"></div>').text(percentComplete + '%'); (nfNgBridge.injector.get('$compile')($('<md-progress-linear ng-cloak ng-value="' + percentComplete + '" class="md-hue-2" md-mode="determinate" aria-label="Drop request percent complete"></md-progress-linear>'))(nfNgBridge.rootScope)).appendTo(progressBar); progressBar.append(label); }; // update the button model of the drop request status dialog $('#drop-request-status-dialog').modal('setButtonModel', [{ buttonText: 'Stop', color: { base: '#728E9B', hover: '#004849', text: '#ffffff' }, handler: { click: function () { cancelled = true; // we are waiting for the next poll attempt if (dropRequestTimer !== null) { // cancel it clearTimeout(dropRequestTimer); // cancel the drop request completeDropRequest(); } } } }]); // completes the drop request by removing it and showing how many flowfiles were deleted var completeDropRequest = function () { // reload the connection status nfConnection.reloadStatus(connection.id); // clean up as appropriate if (nfCommon.isDefinedAndNotNull(dropRequest)) { $.ajax({ type: 'DELETE', url: dropRequest.uri, dataType: 'json' }).done(function (response) { // report the results of this drop request dropRequest = response.dropRequest; // build the results var droppedTokens = dropRequest.dropped.split(/ \/ /); var results = $('<div></div>'); $('<span class="label"></span>').text(droppedTokens[0]).appendTo(results); $('<span></span>').text(' FlowFiles (' + droppedTokens[1] + ')').appendTo(results); // if the request did not complete, include the original if (dropRequest.percentCompleted < 100) { var originalTokens = dropRequest.original.split(/ \/ /); $('<span class="label"></span>').text(' out of ' + originalTokens[0]).appendTo(results); $('<span></span>').text(' (' + originalTokens[1] + ')').appendTo(results); } $('<span></span>').text(' were removed from the queue.').appendTo(results); // if this request failed so the error if (nfCommon.isDefinedAndNotNull(dropRequest.failureReason)) { $('<br/><br/><span></span>').text(dropRequest.failureReason).appendTo(results); } // display the results nfDialog.showOkDialog({ headerText: 'Empty Queue', dialogContent: results }); }).always(function () { $('#drop-request-status-dialog').modal('hide'); }); } else { // nothing was removed nfDialog.showOkDialog({ headerText: 'Empty Queue', dialogContent: 'No FlowFiles were removed.' }); // close the dialog $('#drop-request-status-dialog').modal('hide'); } }; // process the drop request var processDropRequest = function (delay) { // update the percent complete updateProgress(dropRequest.percentCompleted); // update the status of the drop request $('#drop-request-status-message').text(dropRequest.state); // close the dialog if the if (dropRequest.finished === true || cancelled === true) { completeDropRequest(); } else { // wait delay to poll again dropRequestTimer = setTimeout(function () { // clear the drop request timer dropRequestTimer = null; // schedule to poll the status again in nextDelay pollDropRequest(Math.min(MAX_DELAY, delay * 2)); }, delay * 1000); } }; // schedule for the next poll iteration var pollDropRequest = function (nextDelay) { $.ajax({ type: 'GET', url: dropRequest.uri, dataType: 'json' }).done(function (response) { dropRequest = response.dropRequest; processDropRequest(nextDelay); }).fail(function (xhr, status, error) { if (xhr.status === 403) { nfErrorHandler.handleAjaxError(xhr, status, error); } else { completeDropRequest() } }); }; // issue the request to delete the flow files $.ajax({ type: 'POST', url: '../nifi-api/flowfile-queues/' + encodeURIComponent(connection.id) + '/drop-requests', dataType: 'json', contentType: 'application/json' }).done(function (response) { // initialize the progress bar value updateProgress(0); // show the progress dialog $('#drop-request-status-dialog').modal('show'); // process the drop request dropRequest = response.dropRequest; processDropRequest(1); }).fail(function (xhr, status, error) { if (xhr.status === 403) { nfErrorHandler.handleAjaxError(xhr, status, error); } else { completeDropRequest() } }); } }); }, /** * Lists the flow files in the specified connection. * * @param {selection} selection */ listQueue: function (selection) { if (selection.size() !== 1 || !nfCanvasUtils.isConnection(selection)) { return; } // get the connection data var connection = selection.datum(); // list the flow files in the specified connection nfQueueListing.listQueue(connection); }, /** * Views the state for the specified processor. * * @param {selection} selection */ viewState: function (selection) { if (selection.size() !== 1 || !nfCanvasUtils.isProcessor(selection)) { return; } // get the processor data var processor = selection.datum(); // view the state for the selected processor nfComponentState.showState(processor, nfCanvasUtils.isConfigurable(selection)); }, /** * Views the state for the specified processor. * * @param {selection} selection */ changeVersion: function (selection) { if (selection.size() !== 1 || !nfCanvasUtils.isProcessor(selection)) { return; } // get the processor data var processor = selection.datum(); // attempt to change the version of the specified component nfComponentVersion.promptForVersionChange(processor); }, /** * Aligns the components in the specified selection vertically along the center of the components. * * @param {array} selection The selection */ alignVertical: function (selection) { var updates = d3.map(); // ensure every component is writable if (nfCanvasUtils.canModify(selection) === false) { nfDialog.showOkDialog({ headerText: 'Component Position', dialogContent: 'Must be authorized to modify every component selected.' }); return; } // determine the extent var minX = null, maxX = null; selection.each(function (d) { if (d.type !== "Connection") { if (minX === null || d.position.x < minX) { minX = d.position.x; } var componentMaxX = d.position.x + d.dimensions.width; if (maxX === null || componentMaxX > maxX) { maxX = componentMaxX; } } }); var center = (minX + maxX) / 2; // align all components left selection.each(function(d) { if (d.type !== "Connection") { var delta = { x: center - (d.position.x + d.dimensions.width / 2), y: 0 }; // if this component is already centered, no need to updated it if (delta.x !== 0) { // consider any connections var connections = nfConnection.getComponentConnections(d.id); $.each(connections, function(_, connection) { var connectionSelection = d3.select('#id-' + connection.id); if (!updates.has(connection.id) && nfCanvasUtils.getConnectionSourceComponentId(connection) === nfCanvasUtils.getConnectionDestinationComponentId(connection)) { // this connection is self looping and hasn't been updated by the delta yet var connectionUpdate = nfDraggable.updateConnectionPosition(nfConnection.get(connection.id), delta); if (connectionUpdate !== null) { updates.set(connection.id, connectionUpdate); } } else if (!updates.has(connection.id) && connectionSelection.classed('selected') && nfCanvasUtils.canModify(connectionSelection)) { // this is a selected connection that hasn't been updated by the delta yet if (nfCanvasUtils.getConnectionSourceComponentId(connection) === d.id || !isSourceSelected(connection, selection)) { // the connection is either outgoing or incoming when the source of the connection is not part of the selection var connectionUpdate = nfDraggable.updateConnectionPosition(nfConnection.get(connection.id), delta); if (connectionUpdate !== null) { updates.set(connection.id, connectionUpdate); } } } }); updates.set(d.id, nfDraggable.updateComponentPosition(d, delta)); } } }); nfDraggable.refreshConnections(updates); }, /** * Aligns the components in the specified selection horizontally along the center of the components. * * @param {array} selection The selection */ alignHorizontal: function (selection) { var updates = d3.map(); // ensure every component is writable if (nfCanvasUtils.canModify(selection) === false) { nfDialog.showOkDialog({ headerText: 'Component Position', dialogContent: 'Must be authorized to modify every component selected.' }); return; } // determine the extent var minY = null, maxY = null; selection.each(function (d) { if (d.type !== "Connection") { if (minY === null || d.position.y < minY) { minY = d.position.y; } var componentMaxY = d.position.y + d.dimensions.height; if (maxY === null || componentMaxY > maxY) { maxY = componentMaxY; } } }); var center = (minY + maxY) / 2; // align all components with top most component selection.each(function(d) { if (d.type !== "Connection") { var delta = { x: 0, y: center - (d.position.y + d.dimensions.height / 2) }; // if this component is already centered, no need to updated it if (delta.y !== 0) { // consider any connections var connections = nfConnection.getComponentConnections(d.id); $.each(connections, function(_, connection) { var connectionSelection = d3.select('#id-' + connection.id); if (!updates.has(connection.id) && nfCanvasUtils.getConnectionSourceComponentId(connection) === nfCanvasUtils.getConnectionDestinationComponentId(connection)) { // this connection is self looping and hasn't been updated by the delta yet var connectionUpdate = nfDraggable.updateConnectionPosition(nfConnection.get(connection.id), delta); if (connectionUpdate !== null) { updates.set(connection.id, connectionUpdate); } } else if (!updates.has(connection.id) && connectionSelection.classed('selected') && nfCanvasUtils.canModify(connectionSelection)) { // this is a selected connection that hasn't been updated by the delta yet if (nfCanvasUtils.getConnectionSourceComponentId(connection) === d.id || !isSourceSelected(connection, selection)) { // the connection is either outgoing or incoming when the source of the connection is not part of the selection var connectionUpdate = nfDraggable.updateConnectionPosition(nfConnection.get(connection.id), delta); if (connectionUpdate !== null) { updates.set(connection.id, connectionUpdate); } } } }); updates.set(d.id, nfDraggable.updateComponentPosition(d, delta)); } } }); nfDraggable.refreshConnections(updates); }, /** * Opens the fill color dialog for the component in the specified selection. * * @param {type} selection The selection */ fillColor: function (selection) { if (nfCanvasUtils.isColorable(selection)) { // we know that the entire selection is processors or labels... this // checks if the first item is a processor... if true, all processors var allProcessors = nfCanvasUtils.isProcessor(selection); var color; if (allProcessors) { color = nfProcessor.defaultFillColor(); } else { color = nfLabel.defaultColor(); } // if there is only one component selected, get its color otherwise use default if (selection.size() === 1) { var selectionData = selection.datum(); // use the specified color if appropriate if (nfCommon.isDefinedAndNotNull(selectionData.component.style['background-color'])) { color = selectionData.component.style['background-color']; } } // set the color $('#fill-color').minicolors('value', color); // update the preview visibility if (allProcessors) { $('#fill-color-processor-preview').show(); $('#fill-color-label-preview').hide(); } else { $('#fill-color-processor-preview').hide(); $('#fill-color-label-preview').show(); } // show the dialog $('#fill-color-dialog').modal('show'); } }, /** * Groups the currently selected components into a new group. */ group: function () { var selection = nfCanvasUtils.getSelection(); // ensure that components have been specified if (selection.empty()) { return; } // determine the origin of the bounding box for the selected components var origin = nfCanvasUtils.getOrigin(selection); var pt = {'x': origin.x, 'y': origin.y}; $.when(nfNgBridge.injector.get('groupComponent').promptForGroupName(pt)).done(function (processGroup) { var group = d3.select('#id-' + processGroup.id); nfCanvasUtils.moveComponents(selection, group); }); }, /** * Moves the currently selected component into the current parent group. */ moveIntoParent: function () { var selection = nfCanvasUtils.getSelection(); // ensure that components have been specified if (selection.empty()) { return; } // move the current selection into the parent group nfCanvasUtils.moveComponentsToParent(selection); }, /** * Uploads a new template. */ uploadTemplate: function () { $('#upload-template-dialog').modal('show'); }, /** * Creates a new template based off the currently selected components. If no components * are selected, a template of the entire canvas is made. */ template: function () { var selection = nfCanvasUtils.getSelection(); // if no components are selected, use the entire graph if (selection.empty()) { selection = d3.selectAll('g.component, g.connection'); } // ensure that components have been specified if (selection.empty()) { nfDialog.showOkDialog({ headerText: 'Create Template', dialogContent: "The current selection is not valid to create a template." }); return; } // remove dangling edges (where only the source or destination is also selected) selection = nfCanvasUtils.trimDanglingEdges(selection); // ensure that components specified are valid if (selection.empty()) { nfDialog.showOkDialog({ headerText: 'Create Template', dialogContent: "The current selection is not valid to create a template." }); return; } // prompt for the template name $('#new-template-dialog').modal('setButtonModel', [{ buttonText: 'Create', color: { base: '#728E9B', hover: '#004849', text: '#ffffff' }, handler: { click: function () { // get the template details var templateName = $('#new-template-name').val(); // ensure the template name is not blank if (nfCommon.isBlank(templateName)) { nfDialog.showOkDialog({ headerText: 'Create Template', dialogContent: "The template name cannot be blank." }); return; } // hide the dialog $('#new-template-dialog').modal('hide'); // get the description var templateDescription = $('#new-template-description').val(); // create a snippet var parentGroupId = nfCanvasUtils.getGroupId(); var snippet = nfSnippet.marshal(selection, parentGroupId); // create the snippet nfSnippet.create(snippet).done(function (response) { var createSnippetEntity = { 'name': templateName, 'description': templateDescription, 'snippetId': response.snippet.id }; // create the template $.ajax({ type: 'POST', url: config.urls.api + '/process-groups/' + encodeURIComponent(nfCanvasUtils.getGroupId()) + '/templates', data: JSON.stringify(createSnippetEntity), dataType: 'json', contentType: 'application/json' }).done(function () { // show the confirmation dialog nfDialog.showOkDialog({ headerText: 'Create Template', dialogContent: "Template '" + nfCommon.escapeHtml(templateName) + "' was successfully created." }); }).always(function () { // clear the template dialog fields $('#new-template-name').val(''); $('#new-template-description').val(''); }).fail(nfErrorHandler.handleAjaxError); }).fail(nfErrorHandler.handleAjaxError); } } }, { buttonText: 'Cancel', color: { base: '#E3E8EB', hover: '#C7D2D7', text: '#004849' }, handler: { click: function () { // clear the template dialog fields $('#new-template-name').val(''); $('#new-template-description').val(''); $('#new-template-dialog').modal('hide'); } } }]).modal('show'); // auto focus on the template name $('#new-template-name').focus(); }, /** * Copies the component in the specified selection. * * @param {selection} selection The selection containing the component to be copied */ copy: function (selection) { if (selection.empty()) { return; } // determine the origin of the bounding box of the selection var origin = nfCanvasUtils.getOrigin(selection); // copy the snippet details var parentGroupId = nfCanvasUtils.getGroupId(); nfClipboard.copy({ snippet: nfSnippet.marshal(selection, parentGroupId), origin: origin }); }, /** * Pastes the currently copied selection. * * @param {selection} selection The selection containing the component to be copied * @param {obj} evt The mouse event */ paste: function (selection, evt) { if (nfCommon.isDefinedAndNotNull(evt)) { // get the current scale and translation var scale = nfCanvasUtils.scaleCanvasView(); var translate = nfCanvasUtils.translateCanvasView(); var mouseX = evt.pageX; var mouseY = evt.pageY - nfCanvasUtils.getCanvasOffset(); // adjust the x and y coordinates accordingly var x = (mouseX / scale) - (translate[0] / scale); var y = (mouseY / scale) - (translate[1] / scale); // record the paste origin var pasteLocation = { x: x, y: y }; } // perform the paste nfClipboard.paste().done(function (data) { var copySnippet = $.Deferred(function (deferred) { var reject = function (xhr, status, error) { deferred.reject(xhr.responseText); }; var destinationProcessGroupId = nfCanvasUtils.getGroupId(); // create a snippet from the details nfSnippet.create(data['snippet']).done(function (createResponse) { // determine the origin of the bounding box of the copy var origin = pasteLocation; var snippetOrigin = data['origin']; // determine the appropriate origin if (!nfCommon.isDefinedAndNotNull(origin)) { snippetOrigin.x += 25; snippetOrigin.y += 25; origin = snippetOrigin; } // copy the snippet to the new location nfSnippet.copy(createResponse.snippet.id, origin, destinationProcessGroupId).done(function (copyResponse) { var snippetFlow = copyResponse.flow; // update the graph accordingly nfGraph.add(snippetFlow, { 'selectAll': true }); // update component visibility nfGraph.updateVisibility(); // refresh the birdseye/toolbar nfBirdseye.refresh(); }).fail(function () { // an error occured while performing the copy operation, reload the // graph in case it was a partial success nfCanvasUtils.reload().done(function () { // update component visibility nfGraph.updateVisibility(); // refresh the birdseye/toolbar nfBirdseye.refresh(); }); }).fail(reject); }).fail(reject); }).promise(); // show the appropriate message is the copy fails copySnippet.fail(function (responseText) { // look for a message var message = 'An error occurred while attempting to copy and paste.'; if ($.trim(responseText) !== '') { message = responseText; } nfDialog.showOkDialog({ headerText: 'Paste Error', dialogContent: nfCommon.escapeHtml(message) }); }); }); }, /** * Moves the connection in the specified selection to the front. * * @param {selection} selection */ toFront: function (selection) { if (selection.size() !== 1 || !nfCanvasUtils.isConnection(selection)) { return; } // get the connection data var connection = selection.datum(); // determine the current max zIndex var maxZIndex = -1; $.each(nfConnection.get(), function (_, otherConnection) { if (connection.id !== otherConnection.id && otherConnection.zIndex > maxZIndex) { maxZIndex = otherConnection.zIndex; } }); // ensure the edge wasn't already in front if (maxZIndex >= 0) { // use one higher var zIndex = maxZIndex + 1; // build the connection entity var connectionEntity = { 'revision': nfClient.getRevision(connection), 'component': { 'id': connection.id, 'zIndex': zIndex } }; // update the edge in question $.ajax({ type: 'PUT', url: connection.uri, data: JSON.stringify(connectionEntity), dataType: 'json', contentType: 'application/json' }).done(function (response) { nfConnection.set(response); }); } } }; return nfActions; }));
{ "content_hash": "afcb504f9e112e2c176beda0b493b63d", "timestamp": "", "source": "github", "line_count": 1744, "max_line_length": 622, "avg_line_length": 43.446100917431195, "alnum_prop": 0.4729312392767586, "repo_name": "PuspenduBanerjee/nifi", "id": "7050df0aa374e4b8baff85b12edf000827f60419", "size": "76571", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-ui/src/main/webapp/js/nf/canvas/nf-actions.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "12553" }, { "name": "CSS", "bytes": "218479" }, { "name": "Clojure", "bytes": "3993" }, { "name": "GAP", "bytes": "20139" }, { "name": "Groovy", "bytes": "864048" }, { "name": "HTML", "bytes": "198481" }, { "name": "Java", "bytes": "22871394" }, { "name": "JavaScript", "bytes": "2531891" }, { "name": "Lua", "bytes": "983" }, { "name": "Python", "bytes": "17954" }, { "name": "Ruby", "bytes": "8028" }, { "name": "Shell", "bytes": "28541" }, { "name": "XSLT", "bytes": "5681" } ], "symlink_target": "" }
/** PURE_IMPORTS_START .._Subscriber PURE_IMPORTS_END */ var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; import { Subscriber } from '../Subscriber'; /** * Emits only the first value emitted by the source Observable that meets some * condition. * * <span class="informal">Finds the first value that passes some test and emits * that.</span> * * <img src="./img/find.png" width="100%"> * * `find` searches for the first item in the source Observable that matches the * specified condition embodied by the `predicate`, and returns the first * occurrence in the source. Unlike {@link first}, the `predicate` is required * in `find`, and does not emit an error if a valid value is not found. * * @example <caption>Find and emit the first click that happens on a DIV element</caption> * var clicks = Rx.Observable.fromEvent(document, 'click'); * var result = clicks.find(ev => ev.target.tagName === 'DIV'); * result.subscribe(x => console.log(x)); * * @see {@link filter} * @see {@link first} * @see {@link findIndex} * @see {@link take} * * @param {function(value: T, index: number, source: Observable<T>): boolean} predicate * A function called with each item to test for condition matching. * @param {any} [thisArg] An optional argument to determine the value of `this` * in the `predicate` function. * @return {Observable<T>} An Observable of the first item that matches the * condition. * @method find * @owner Observable */ export function find(predicate, thisArg) { if (typeof predicate !== 'function') { throw new TypeError('predicate is not a function'); } return function (source) { return source.lift(new FindValueOperator(predicate, source, false, thisArg)); }; } export var FindValueOperator = /*@__PURE__*/ (/*@__PURE__*/ function () { function FindValueOperator(predicate, source, yieldIndex, thisArg) { this.predicate = predicate; this.source = source; this.yieldIndex = yieldIndex; this.thisArg = thisArg; } FindValueOperator.prototype.call = function (observer, source) { return source.subscribe(new FindValueSubscriber(observer, this.predicate, this.source, this.yieldIndex, this.thisArg)); }; return FindValueOperator; }()); /** * We need this JSDoc comment for affecting ESDoc. * @ignore * @extends {Ignored} */ export var FindValueSubscriber = /*@__PURE__*/ (/*@__PURE__*/ function (_super) { __extends(FindValueSubscriber, _super); function FindValueSubscriber(destination, predicate, source, yieldIndex, thisArg) { _super.call(this, destination); this.predicate = predicate; this.source = source; this.yieldIndex = yieldIndex; this.thisArg = thisArg; this.index = 0; } FindValueSubscriber.prototype.notifyComplete = function (value) { var destination = this.destination; destination.next(value); destination.complete(); }; FindValueSubscriber.prototype._next = function (value) { var _a = this, predicate = _a.predicate, thisArg = _a.thisArg; var index = this.index++; try { var result = predicate.call(thisArg || this, value, index, this.source); if (result) { this.notifyComplete(this.yieldIndex ? index : value); } } catch (err) { this.destination.error(err); } }; FindValueSubscriber.prototype._complete = function () { this.notifyComplete(this.yieldIndex ? -1 : undefined); }; return FindValueSubscriber; }(Subscriber)); //# sourceMappingURL=find.js.map
{ "content_hash": "060b713ff622fdde5318829a1b970691", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 127, "avg_line_length": 38.94949494949495, "alnum_prop": 0.64548755186722, "repo_name": "Jeck99/At-T", "id": "e25f388432e19150c9bb91f146c80e27c4b31e56", "size": "3856", "binary": false, "copies": "19", "ref": "refs/heads/master", "path": "node_modules/@angular-devkit/schematics/node_modules/rxjs/_esm5/operators/find.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "338242" }, { "name": "HTML", "bytes": "62564" }, { "name": "JavaScript", "bytes": "1996" }, { "name": "TypeScript", "bytes": "73601" } ], "symlink_target": "" }
NDock [![Build Status](https://travis-ci.org/kerryjiang/NDock.svg?branch=master)](https://travis-ci.org/kerryjiang/NDock) ===== **NDock** is a server application container, which can be used for your back end services' hosting and management. **Features**: * Automatic service hosting * Multiple application isolation * App Garden * Watch dog * Automatic recycle management
{ "content_hash": "b0b7dd03d4ace9a12de8b6a26d8a4a2f", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 122, "avg_line_length": 31.5, "alnum_prop": 0.753968253968254, "repo_name": "huoxudong125/NDock", "id": "8c382ef920b532b3ebc62bd36d1950db911d32f6", "size": "378", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "35" }, { "name": "C#", "bytes": "170505" }, { "name": "Shell", "bytes": "42" } ], "symlink_target": "" }
package org.apache.flink.table.planner.plan.optimize import org.apache.flink.annotation.Experimental import org.apache.flink.configuration.{ConfigOption, ReadableConfig} import org.apache.flink.configuration.ConfigOptions.key import org.apache.flink.table.planner.plan.`trait`.MiniBatchInterval import org.apache.flink.table.planner.plan.nodes.calcite.LegacySink import org.apache.flink.table.planner.plan.reuse.SubplanReuser.{SubplanReuseContext, SubplanReuseShuttle} import org.apache.flink.table.planner.plan.rules.logical.WindowPropertiesRules import org.apache.flink.table.planner.plan.utils.{DefaultRelShuttle, ExpandTableScanShuttle} import org.apache.flink.util.Preconditions import com.google.common.collect.Sets import org.apache.calcite.rel._ import org.apache.calcite.rel.core.{Aggregate, Project, Snapshot, TableFunctionScan, Union} import org.apache.calcite.rex.RexNode import java.lang.{Boolean => JBoolean} import java.util import scala.collection.JavaConversions._ import scala.collection.mutable /** * A [[RelNodeBlock]] is a sub-tree in the [[RelNode]] DAG, and represents common sub-graph in * [[CommonSubGraphBasedOptimizer]]. All [[RelNode]]s in each block have only one [[LegacySink]] * output. * * The algorithm works as follows: * 1. If there is only one tree, the whole tree is in one block. (the next steps is needless.) 2. * reuse common sub-plan in different RelNode tree, generate a RelNode DAG, 3. traverse each * tree from root to leaf, and mark the sink RelNode of each RelNode 4. traverse each tree from * root to leaf again, if meet a RelNode which has multiple sink RelNode, the RelNode is the * output node of a new block (or named break-point). There are several special cases that a * RelNode can not be a break-point. (1). UnionAll is not a break-point when * [[RelNodeBlockPlanBuilder.TABLE_OPTIMIZER_UNIONALL_AS_BREAKPOINT_ENABLED]] is false (2). * [[TableFunctionScan]], [[Snapshot]] or window aggregate ([[Aggregate]] on a [[Project]] with * window attribute) are not a break-point because their physical RelNodes are a composite * RelNode, each of them cannot be optimized individually. e.g. FlinkLogicalTableFunctionScan * and FlinkLogicalCorrelate will be combined into a BatchExecCorrelate or a * StreamExecCorrelate. * * For example: (Table API) * * {{{- val sourceTable = tEnv.scan("test_table").select('a, 'b, 'c) val leftTable = * sourceTable.filter('a > 0).select('a as 'a1, 'b as 'b1) val rightTable = * sourceTable.filter('c.isNotNull).select('b as 'b2, 'c as 'c2) val joinTable = * leftTable.join(rightTable, 'a1 === 'b2) joinTable.where('a1 >= 70).select('a1, * 'b1).writeToSink(sink1) joinTable.where('a1 < 70 ).select('a1, 'c2).writeToSink(sink2) }}} * * the RelNode DAG is: * * {{{- Sink(sink1) Sink(sink2) \| | Project(a1,b1) Project(a1,c2) \| | Filter(a1>=70) Filter(a1<70) * \ / Join(a1=b2) / \ Project(a1,b1) Project(b2,c2) \| | Filter(a>0) Filter(c is not null) \ / * Project(a,b,c) \| TableScan }}} * * This [[RelNode]] DAG will be decomposed into three [[RelNodeBlock]]s, the break-point is the * [[RelNode]](`Join(a1=b2)`) which data outputs to multiple [[LegacySink]]s. <p>Notes: Although * `Project(a,b,c)` has two parents (outputs), they eventually merged at `Join(a1=b2)`. So * `Project(a,b,c)` is not a break-point. <p>the first [[RelNodeBlock]] includes TableScan, * Project(a,b,c), Filter(a>0), Filter(c is not null), Project(a1,b1), Project(b2,c2) and * Join(a1=b2) <p>the second one includes Filter(a1>=70), Project(a1,b1) and Sink(sink1) <p>the * third one includes Filter(a1<70), Project(a1,c2) and Sink(sink2) <p>And the first * [[RelNodeBlock]] is the child of another two. * * The [[RelNodeBlock]] plan is: {{{- RelNodeBlock2 RelNodeBlock3 \ / RelNodeBlock1}}} * * The optimizing order is from child block to parent. The optimized result (RelNode) will be * wrapped as an IntermediateRelTable first, and then be converted to a new TableScan which is the * new output node of current block and is also the input of its parent blocks. * * @param outputNode * A RelNode of the output in the block, which could be a [[LegacySink]] or other RelNode which * data outputs to multiple [[LegacySink]]s. */ class RelNodeBlock(val outputNode: RelNode) { // child (or input) blocks private val childBlocks = mutable.LinkedHashSet[RelNodeBlock]() // After this block has been optimized, the result will be converted to a new TableScan as // new output node private var newOutputNode: Option[RelNode] = None private var outputTableName: Option[String] = None private var optimizedPlan: Option[RelNode] = None // whether any parent block requires UPDATE_BEFORE messages private var updateBeforeRequired: Boolean = false private var miniBatchInterval: MiniBatchInterval = MiniBatchInterval.NONE def addChild(block: RelNodeBlock): Unit = childBlocks += block def children: Seq[RelNodeBlock] = childBlocks.toSeq def setNewOutputNode(newNode: RelNode): Unit = newOutputNode = Option(newNode) def getNewOutputNode: Option[RelNode] = newOutputNode def setOutputTableName(name: String): Unit = outputTableName = Option(name) def getOutputTableName: String = outputTableName.orNull def setOptimizedPlan(rel: RelNode): Unit = this.optimizedPlan = Option(rel) def getOptimizedPlan: RelNode = optimizedPlan.orNull def setUpdateBeforeRequired(requireUpdateBefore: Boolean): Unit = { // set the child block whether need to produce update before messages for updates, // a child block may have multiple parents (outputs), if one of the parents require // update before message, then this child block has to produce update before for updates. if (requireUpdateBefore) { this.updateBeforeRequired = true } } /** Returns true if any parent block requires UPDATE_BEFORE messages for updates. */ def isUpdateBeforeRequired: Boolean = updateBeforeRequired def setMiniBatchInterval(miniBatchInterval: MiniBatchInterval): Unit = { this.miniBatchInterval = miniBatchInterval } def getMiniBatchInterval: MiniBatchInterval = miniBatchInterval def getChildBlock(node: RelNode): Option[RelNodeBlock] = { val find = children.filter(_.outputNode.equals(node)) if (find.isEmpty) { None } else { Preconditions.checkArgument(find.size == 1) Some(find.head) } } /** * Get new plan of this block. The child blocks (inputs) will be replace with new RelNodes (the * optimized result of child block). * * @return * New plan of this block */ def getPlan: RelNode = { val shuttle = new RelNodeBlockShuttle outputNode.accept(shuttle) } private class RelNodeBlockShuttle extends DefaultRelShuttle { override def visit(rel: RelNode): RelNode = { val block = getChildBlock(rel) block match { case Some(b) => b.getNewOutputNode.get case _ => super.visit(rel) } } } } /** Holds information to build [[RelNodeBlock]]. */ class RelNodeWrapper(relNode: RelNode) { // parent nodes of `relNode` private val parentNodes = Sets.newIdentityHashSet[RelNode]() // output nodes of some blocks that data of `relNode` outputs to private val blockOutputNodes = Sets.newIdentityHashSet[RelNode]() // stores visited parent nodes when builds RelNodeBlock private val visitedParentNodes = Sets.newIdentityHashSet[RelNode]() def addParentNode(parent: Option[RelNode]): Unit = { parent match { case Some(p) => parentNodes.add(p) case None => // Ignore } } def addVisitedParentNode(parent: Option[RelNode]): Unit = { parent match { case Some(p) => require(parentNodes.contains(p)) visitedParentNodes.add(p) case None => // Ignore } } def addBlockOutputNode(blockOutputNode: RelNode): Unit = blockOutputNodes.add(blockOutputNode) /** Returns true if all parent nodes had been visited, else false */ def allParentNodesVisited: Boolean = parentNodes.size() == visitedParentNodes.size() /** Returns true if number of `blockOutputNodes` is greater than 1, else false */ def hasMultipleBlockOutputNodes: Boolean = blockOutputNodes.size() > 1 /** Returns the output node of the block that the `relNode` belongs to */ def getBlockOutputNode: RelNode = { if (hasMultipleBlockOutputNodes) { // If has multiple block output nodes, the `relNode` is a break-point. // So the `relNode` is the output node of the block that the `relNode` belongs to relNode } else { // the `relNode` is not a break-point require(blockOutputNodes.size == 1) blockOutputNodes.head } } } /** Builds [[RelNodeBlock]] plan */ class RelNodeBlockPlanBuilder private (tableConfig: ReadableConfig) { private val node2Wrapper = new util.IdentityHashMap[RelNode, RelNodeWrapper]() private val node2Block = new util.IdentityHashMap[RelNode, RelNodeBlock]() private val isUnionAllAsBreakPointEnabled = tableConfig .get(RelNodeBlockPlanBuilder.TABLE_OPTIMIZER_UNIONALL_AS_BREAKPOINT_ENABLED) /** * Decompose the [[RelNode]] plan into many [[RelNodeBlock]]s, and rebuild [[RelNodeBlock]] plan. * * @param sinks * RelNode DAG to decompose * @return * Sink-RelNodeBlocks, each Sink-RelNodeBlock is a tree. */ def buildRelNodeBlockPlan(sinks: Seq[RelNode]): Seq[RelNodeBlock] = { sinks.foreach(buildRelNodeWrappers(_, None)) buildBlockOutputNodes(sinks) sinks.map(buildBlockPlan) } private def buildRelNodeWrappers(node: RelNode, parent: Option[RelNode]): Unit = { node2Wrapper.getOrElseUpdate(node, new RelNodeWrapper(node)).addParentNode(parent) node.getInputs.foreach(child => buildRelNodeWrappers(child, Some(node))) } private def buildBlockPlan(node: RelNode): RelNodeBlock = { val currentBlock = new RelNodeBlock(node) buildBlock(node, currentBlock, createNewBlockWhenMeetValidBreakPoint = false) currentBlock } private def buildBlock( node: RelNode, currentBlock: RelNodeBlock, createNewBlockWhenMeetValidBreakPoint: Boolean): Unit = { val hasDiffBlockOutputNodes = node2Wrapper(node).hasMultipleBlockOutputNodes val validBreakPoint = isValidBreakPoint(node) if (validBreakPoint && (createNewBlockWhenMeetValidBreakPoint || hasDiffBlockOutputNodes)) { val childBlock = node2Block.getOrElseUpdate(node, new RelNodeBlock(node)) currentBlock.addChild(childBlock) node.getInputs.foreach { child => buildBlock(child, childBlock, createNewBlockWhenMeetValidBreakPoint = false) } } else { val newCreateNewBlockWhenMeetValidBreakPoint = createNewBlockWhenMeetValidBreakPoint || hasDiffBlockOutputNodes && !validBreakPoint node.getInputs.foreach { child => buildBlock(child, currentBlock, newCreateNewBlockWhenMeetValidBreakPoint) } } } /** * TableFunctionScan/Snapshot/Window Aggregate cannot be optimized individually, so * TableFunctionScan/Snapshot/Window Aggregate is not a valid break-point even though it has * multiple parents. */ private def isValidBreakPoint(node: RelNode): Boolean = node match { case _: TableFunctionScan | _: Snapshot => false case union: Union if union.all => isUnionAllAsBreakPointEnabled case project: Project => project.getProjects.forall(p => !hasWindowGroup(p)) case agg: Aggregate => agg.getInput match { case project: Project => agg.getGroupSet.forall { group => val p = project.getProjects.get(group) !hasWindowGroup(p) } case _ => true } case _ => true } private def hasWindowGroup(rexNode: RexNode): Boolean = { WindowPropertiesRules.hasGroupAuxiliaries(rexNode) || WindowPropertiesRules.hasGroupFunction(rexNode) } private def buildBlockOutputNodes(sinks: Seq[RelNode]): Unit = { // init sink block output node sinks.foreach(sink => node2Wrapper.get(sink).addBlockOutputNode(sink)) val unvisitedNodeQueue: util.Deque[RelNode] = new util.ArrayDeque[RelNode]() unvisitedNodeQueue.addAll(sinks) while (unvisitedNodeQueue.nonEmpty) { val node = unvisitedNodeQueue.removeFirst() val wrapper = node2Wrapper.get(node) require(wrapper != null) val blockOutputNode = wrapper.getBlockOutputNode buildBlockOutputNodes(None, node, blockOutputNode, unvisitedNodeQueue) } } private def buildBlockOutputNodes( parent: Option[RelNode], node: RelNode, curBlockOutputNode: RelNode, unvisitedNodeQueue: util.Deque[RelNode]): Unit = { val wrapper = node2Wrapper.get(node) require(wrapper != null) wrapper.addBlockOutputNode(curBlockOutputNode) wrapper.addVisitedParentNode(parent) // the node can be visited only when its all parent nodes have been visited if (wrapper.allParentNodesVisited) { val newBlockOutputNode = if (wrapper.hasMultipleBlockOutputNodes) { // if the node has different output node, the node is the output node of current block. node } else { curBlockOutputNode } node.getInputs.foreach { input => buildBlockOutputNodes(Some(node), input, newBlockOutputNode, unvisitedNodeQueue) } unvisitedNodeQueue.remove(node) } else { // visit later unvisitedNodeQueue.addLast(node) } } } object RelNodeBlockPlanBuilder { // It is a experimental config, will may be removed later. @Experimental val TABLE_OPTIMIZER_UNIONALL_AS_BREAKPOINT_ENABLED: ConfigOption[JBoolean] = key("table.optimizer.union-all-as-breakpoint-enabled") .booleanType() .defaultValue(JBoolean.valueOf(true)) .withDescription( "When true, the optimizer will breakup the graph at union-all node " + "when it's a breakpoint. When false, the optimizer will skip the union-all node " + "even it's a breakpoint, and will try find the breakpoint in its inputs.") // It is a experimental config, will may be removed later. @Experimental val TABLE_OPTIMIZER_REUSE_OPTIMIZE_BLOCK_WITH_DIGEST_ENABLED: ConfigOption[JBoolean] = key("table.optimizer.reuse-optimize-block-with-digest-enabled") .booleanType() .defaultValue(JBoolean.valueOf(false)) .withDescription( "When true, the optimizer will try to find out duplicated sub-plan by " + "digest to build optimize block(a.k.a. common sub-graph). " + "Each optimize block will be optimized independently.") /** * Decompose the [[RelNode]] trees into [[RelNodeBlock]] trees. First, convert LogicalNode trees * to RelNode trees. Second, reuse same sub-plan in different trees. Third, decompose the RelNode * dag to [[RelNodeBlock]] trees. * * @param sinkNodes * SinkNodes belongs to a LogicalNode plan. * @return * Sink-RelNodeBlocks, each Sink-RelNodeBlock is a tree. */ def buildRelNodeBlockPlan( sinkNodes: Seq[RelNode], tableConfig: ReadableConfig): Seq[RelNodeBlock] = { require(sinkNodes.nonEmpty) // expand QueryOperationCatalogViewTable in TableScan val shuttle = new ExpandTableScanShuttle val convertedRelNodes = sinkNodes.map(_.accept(shuttle)) if (convertedRelNodes.size == 1) { Seq(new RelNodeBlock(convertedRelNodes.head)) } else { // merge multiple RelNode trees to RelNode dag val relNodeDag = reuseRelNodes(convertedRelNodes, tableConfig) val builder = new RelNodeBlockPlanBuilder(tableConfig) builder.buildRelNodeBlockPlan(relNodeDag) } } /** * Reuse common sub-plan in different RelNode tree, generate a RelNode dag * * @param relNodes * RelNode trees * @return * RelNode dag which reuse common subPlan in each tree */ private def reuseRelNodes(relNodes: Seq[RelNode], tableConfig: ReadableConfig): Seq[RelNode] = { val findOpBlockWithDigest = tableConfig .get(RelNodeBlockPlanBuilder.TABLE_OPTIMIZER_REUSE_OPTIMIZE_BLOCK_WITH_DIGEST_ENABLED) if (!findOpBlockWithDigest) { return relNodes } // reuse sub-plan with same digest in input RelNode trees. val context = new SubplanReuseContext(true, relNodes: _*) val reuseShuttle = new SubplanReuseShuttle(context) relNodes.map(_.accept(reuseShuttle)) } }
{ "content_hash": "4937b2b8a4f667c93f3b9d5ca153a76a", "timestamp": "", "source": "github", "line_count": 411, "max_line_length": 105, "avg_line_length": 39.97323600973236, "alnum_prop": 0.7134944305800718, "repo_name": "godfreyhe/flink", "id": "7cabc65d150bb3d6c9b67499e421f54b6927c4cb", "size": "17234", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/optimize/RelNodeBlock.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "20596" }, { "name": "Batchfile", "bytes": "1863" }, { "name": "C", "bytes": "847" }, { "name": "Cython", "bytes": "132975" }, { "name": "Dockerfile", "bytes": "5579" }, { "name": "FreeMarker", "bytes": "93941" }, { "name": "GAP", "bytes": "139536" }, { "name": "HTML", "bytes": "155679" }, { "name": "HiveQL", "bytes": "123152" }, { "name": "Java", "bytes": "93613871" }, { "name": "JavaScript", "bytes": "7038" }, { "name": "Less", "bytes": "68979" }, { "name": "Makefile", "bytes": "5134" }, { "name": "Python", "bytes": "2812324" }, { "name": "Scala", "bytes": "10688614" }, { "name": "Shell", "bytes": "519375" }, { "name": "TypeScript", "bytes": "326237" }, { "name": "q", "bytes": "9630" } ], "symlink_target": "" }
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js"></script> <script src="/script/list.min.js"></script> <script src="/script/script.js"></script> <!-- end scripts --> {% include system/ga.html %} </body> </html>
{ "content_hash": "15f33c5664a29e35789fef84c4fded3a", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 78, "avg_line_length": 33, "alnum_prop": 0.6623376623376623, "repo_name": "studiomohawk/Seven", "id": "ab4903cfeeebc9b232441d2061b8d49661f21194", "size": "231", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_includes/system/sys_footer.html", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "2219" }, { "name": "Ruby", "bytes": "1866" } ], "symlink_target": "" }
<?php /** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ namespace Twilio\Rest\Sync\V1\Service; use Twilio\Deserialize; use Twilio\Exceptions\TwilioException; use Twilio\InstanceResource; use Twilio\Options; use Twilio\Values; use Twilio\Version; /** * PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. * * @property string sid * @property string uniqueName * @property string accountSid * @property string serviceSid * @property string url * @property array links * @property string revision * @property \DateTime dateExpires * @property \DateTime dateCreated * @property \DateTime dateUpdated * @property string createdBy */ class SyncListInstance extends InstanceResource { protected $_syncListItems = null; protected $_syncListPermissions = null; /** * Initialize the SyncListInstance * * @param \Twilio\Version $version Version that contains the resource * @param mixed[] $payload The response payload * @param string $serviceSid The unique SID identifier of the Service Instance * that hosts this List object. * @param string $sid The sid * @return \Twilio\Rest\Sync\V1\Service\SyncListInstance */ public function __construct(Version $version, array $payload, $serviceSid, $sid = null) { parent::__construct($version); // Marshaled Properties $this->properties = array( 'sid' => Values::array_get($payload, 'sid'), 'uniqueName' => Values::array_get($payload, 'unique_name'), 'accountSid' => Values::array_get($payload, 'account_sid'), 'serviceSid' => Values::array_get($payload, 'service_sid'), 'url' => Values::array_get($payload, 'url'), 'links' => Values::array_get($payload, 'links'), 'revision' => Values::array_get($payload, 'revision'), 'dateExpires' => Deserialize::dateTime(Values::array_get($payload, 'date_expires')), 'dateCreated' => Deserialize::dateTime(Values::array_get($payload, 'date_created')), 'dateUpdated' => Deserialize::dateTime(Values::array_get($payload, 'date_updated')), 'createdBy' => Values::array_get($payload, 'created_by'), ); $this->solution = array('serviceSid' => $serviceSid, 'sid' => $sid ?: $this->properties['sid'], ); } /** * Generate an instance context for the instance, the context is capable of * performing various actions. All instance actions are proxied to the context * * @return \Twilio\Rest\Sync\V1\Service\SyncListContext Context for this * SyncListInstance */ protected function proxy() { if (!$this->context) { $this->context = new SyncListContext( $this->version, $this->solution['serviceSid'], $this->solution['sid'] ); } return $this->context; } /** * Fetch a SyncListInstance * * @return SyncListInstance Fetched SyncListInstance */ public function fetch() { return $this->proxy()->fetch(); } /** * Deletes the SyncListInstance * * @return boolean True if delete succeeds, false otherwise */ public function delete() { return $this->proxy()->delete(); } /** * Update the SyncListInstance * * @param array|Options $options Optional Arguments * @return SyncListInstance Updated SyncListInstance */ public function update($options = array()) { return $this->proxy()->update($options); } /** * Access the syncListItems * * @return \Twilio\Rest\Sync\V1\Service\SyncList\SyncListItemList */ protected function getSyncListItems() { return $this->proxy()->syncListItems; } /** * Access the syncListPermissions * * @return \Twilio\Rest\Sync\V1\Service\SyncList\SyncListPermissionList */ protected function getSyncListPermissions() { return $this->proxy()->syncListPermissions; } /** * Magic getter to access properties * * @param string $name Property to access * @return mixed The requested property * @throws TwilioException For unknown properties */ public function __get($name) { if (array_key_exists($name, $this->properties)) { return $this->properties[$name]; } if (property_exists($this, '_' . $name)) { $method = 'get' . ucfirst($name); return $this->$method(); } throw new TwilioException('Unknown property: ' . $name); } /** * Provide a friendly representation * * @return string Machine friendly representation */ public function __toString() { $context = array(); foreach ($this->solution as $key => $value) { $context[] = "$key=$value"; } return '[Twilio.Sync.V1.SyncListInstance ' . implode(' ', $context) . ']'; } }
{ "content_hash": "a75cfd12d7af5d283edf973eb03d7e47", "timestamp": "", "source": "github", "line_count": 166, "max_line_length": 106, "avg_line_length": 31.301204819277107, "alnum_prop": 0.5912240184757506, "repo_name": "besongsamuel/eapp", "id": "b8ab536defa28037ffdc3734f934345501f21685", "size": "5196", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/twilio/sdk/Twilio/Rest/Sync/V1/Service/SyncListInstance.php", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "8037" }, { "name": "CSS", "bytes": "583143" }, { "name": "HTML", "bytes": "12205288" }, { "name": "Hack", "bytes": "99403" }, { "name": "JavaScript", "bytes": "1549084" }, { "name": "PHP", "bytes": "5845610" }, { "name": "Shell", "bytes": "788" }, { "name": "TSQL", "bytes": "1892" } ], "symlink_target": "" }
<Record> <Term>Coffin-Siris Syndrome</Term> <SemanticType>Disease or Syndrome</SemanticType> <ParentTerm>Syndrome</ParentTerm> <ClassificationPath>Findings_and_Disorders_Kind/Disease, Disorder or Finding/Disease or Disorder/Syndrome/Coffin-Siris Syndrome</ClassificationPath> <BroaderTerm>Syndrome</BroaderTerm> <BroaderTerm>Disease or Disorder</BroaderTerm> <BroaderTerm>Coffin-Siris Syndrome</BroaderTerm> <BroaderTerm>Disease, Disorder or Finding</BroaderTerm> <BroaderTerm>Findings_and_Disorders_Kind</BroaderTerm> <Synonym>Coffin-Siris Syndrome</Synonym> <Source>NCI Thesaurus</Source> </Record>
{ "content_hash": "93c035a4903a1ccc272189d9d2cf1b93", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 148, "avg_line_length": 47.23076923076923, "alnum_prop": 0.8061889250814332, "repo_name": "detnavillus/modular-informatic-designs", "id": "45883a7ccf3765f7b218aa99e943419bbb74193d", "size": "614", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pipeline/src/test/resources/thesaurus/diseaseorsyndrome/coffin-sirissyndrome.xml", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2069134" } ], "symlink_target": "" }
namespace exegesis { namespace x86 { // An implementation of a parser for the binary encoding of x86-64 instructions. // Note that this class does not perform full disassembly, it only parses the // instruction data to a structured form that is easy to manage and inspect. // // Note that the parser is not thread safe and one parser may not be used from // multiple threads at the same time. class InstructionParser { public: // Initializes the instruction parser with the given instruction set // information. The instruction_db object must remain valid for the whole // lifetime of the instruction parser. explicit InstructionParser(const X86Architecture* architecture); // Parses a single instruction from 'encoded_instruction'. This method updates // 'encoded_instruction' so that when an instruction is parsed correctly, it // will begin with the first byte of the following instruction. When the // method returns failure, the state of 'encoded_instruction' is valid but // undefined. absl::StatusOr<DecodedInstruction> ConsumeBinaryEncoding( absl::Span<const uint8_t>* encoded_instruction); // Parses a single instruction from 'encoded_instruction'. Ignores all bytes // following the first instruction. absl::StatusOr<DecodedInstruction> ParseBinaryEncoding( absl::Span<const uint8_t> encoded_instruction) { return ConsumeBinaryEncoding(&encoded_instruction); } private: // Resets the state of the parser. void Reset(); // Parses the prefixes of the instruction. Expects that 'encoded_instruction' // starts with the first byte of the instruction. It removes the prefixes from // the span as they are parsed. On success, the span is updated so that it // starts with the first non-prefix byte of the instruction. When the method // fails, the state of the span is undefined. absl::Status ConsumePrefixes(absl::Span<const uint8_t>* encoded_instruction); // Parses the REX prefix of the instruction. absl::Status ParseRexPrefix(uint8_t prefix_byte); // When the first byte of 'encoded_instruction' is a segment override prefix, // parses the prefix, removes the byte from the span, and returns true. // Otherwise, does nothing and returns false. bool ConsumeSegmentOverridePrefixIfNeeded( absl::Span<const uint8_t>* encoded_instruction); // When the first byte of 'encoded_instruction' is an address size override // prefix, parses the prefix, removes the byte from the span, and returns // true. Otherwise, does nothing and returns false. bool ConsumeAddressSizeOverridePrefixIfNeeded( absl::Span<const uint8_t>* encoded_instruction); // Parses the VEX (resp. EVEX) prefix of the instruction. Expects that // 'encoded_instruction' starts with the first byte of the (E)VEX prefix. It // removes the (E)VEX prefix from the span as it is parsed. On success, the // span is updated so that it starts with the first non-prefix byte of the // instruction. When the method fails, the state of the span is undefined. absl::Status ConsumeVexPrefix(absl::Span<const uint8_t>* encoded_instruction); absl::Status ConsumeEvexPrefix( absl::Span<const uint8_t>* encoded_instruction); // Parses the opcode of the instruction. Expects that 'encoded_instruction' // starts with the first byte of the opcode and it removes the opcode from the // span as it is parsed. On success, the span is updated so that it starts // with the first byte of the instruction following the opcode. When the // method fails, the state of the span is undefined. absl::Status ConsumeOpcode(absl::Span<const uint8_t>* encoded_instruction); // Gets the encoding specification for the given opcode, also handling the // case where three least significant bits of the instruction are used to // encode an operand. In such case it looks for the opcode with these bits set // to zero. check_modrm decides whether to match modrm byte of the // specification with the decoded instruction we have. const EncodingSpecification* GetEncodingSpecification(uint32_t opcode_value, bool check_modrm); // Parses the contents of the ModR/M and SIB bytes if they are used by the // instruction. Assumes that the opcode of the instruction was already parsed // and that 'encoded_instruction' starts with the first byte after the opcode. // On success, the span is updated so that it starts with the first byte of // the instruction following the ModR/M and SIB bytes and any potential // displacement values. When the method fails, the state of the span is // undefined. absl::Status ConsumeModRmAndSIBIfNeeded( absl::Span<const uint8_t>* encoded_instruction); // Parses the immediate value attached to the instruction if there is one. // Assumes that all parts of the instruction preceding the immediate value are // already parsed and that 'encoded_instruction' starts with the first byte // after the immediate value. On success, the span is updated so that it // starts with the first byte following the immediate value parsed by this // method. When the method fails, the state of the span is undefined. absl::Status ConsumeImmediateValuesIfNeeded( absl::Span<const uint8_t>* encoded_instruction); // Parses the code offset attached to the instruction if there is one. Assumes // that all parts of the instruction preceding the code offset are already // parsed and that 'encoded_instruction' starts with the first byte after the // immediate value. On success, the span is updated so that it starts with // the first byte following the code offset parsed by this method. When the // method fails, the state of the span is undefined. absl::Status ConsumeCodeOffsetIfNeeded( absl::Span<const uint8_t>* encoded_instruction); // Parses the value of the VEX suffix attached to the instruction if there is // one. Assumes that all parts of the instruction preceding the code offset // are already parsed and that 'encoded_instruction' starts with the first // byte after the immediate value. On success, the span is updated so that it // starts with the first byte following the VEX suffix parsed by this method. // When the method fails, the state of the span is undefined. absl::Status ConsumeVexSuffixIfNeeded( absl::Span<const uint8_t>* encoded_instruction); // Methods for updating the prefixes from the four legacy prefix groups (see // http://wiki.osdev.org/X86-64_Instruction_Encoding#Legacy_Prefixes for the // description of the groups). // // All of these methods can be called at most once during the parsing of the // instruction. Multiple calls mean that the encoded instruction had more than // one prefix from the prefix group corresponding to the method. This is not // an error per se, but it leads to undefined behavior of the CPU and we want // to reject instructions like that. absl::Status AddLockOrRepPrefix(LegacyEncoding::LockOrRepPrefix prefix); void AddSegmentOverridePrefix(LegacyEncoding::SegmentOverridePrefix prefix); absl::Status AddOperandSizeOverridePrefix(); void AddAddressSizeOverridePrefix(); // The architecture information used by the parser. The architecture is used // to determine what parts of an instruction are present for a given // combination of opcode and prefixes. const X86Architecture* const architecture_; // The encoding specification of the current instruction. The specification is // retrieved when the parser finishes parsing the prefixes and the opcode of // the instruction - before that, the pointer is set to nullptr. // The encoding specification object is owned by 'instruction_db_'; it remains // valid as long as 'instruction_db_' is valid and it must not be deleted // explicitly. const EncodingSpecification* specification_; // The encoded form of the current instruction processed by the parser. absl::Span<const uint8_t> encoded_instruction_; // The current instruction processed by the parser. DecodedInstruction instruction_; }; } // namespace x86 } // namespace exegesis #endif // EXEGESIS_X86_INSTRUCTION_PARSER_H_
{ "content_hash": "3bbd752025a554e20076786ab926abc1", "timestamp": "", "source": "github", "line_count": 155, "max_line_length": 80, "avg_line_length": 52.87741935483871, "alnum_prop": 0.7491459248413861, "repo_name": "google/EXEgesis", "id": "3b9f7f5cf3b77fd1cc9b345a9e5f9fd72adb7116", "size": "9943", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "exegesis/x86/instruction_parser.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "2263919" }, { "name": "Makefile", "bytes": "2433" }, { "name": "Starlark", "bytes": "108849" } ], "symlink_target": "" }
package com.navercorp.pinpoint.rpc.client; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Taejin Koo */ public class ConnectFuture { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private static final AtomicReferenceFieldUpdater<ConnectFuture, Result> FIELD_UPDATER = AtomicReferenceFieldUpdater.newUpdater(ConnectFuture.class, Result.class, "result"); private final CountDownLatch latch; private volatile Result result; public enum Result { SUCCESS, FAIL } public ConnectFuture() { this.latch = new CountDownLatch(1); } public Result getResult() { return this.result; } void setResult(Result connectResult) { final Result result = this.result; if (result == null) { if (FIELD_UPDATER.compareAndSet(this, null, connectResult)) { latch.countDown(); } } } public void await() throws InterruptedException { latch.await(); } public boolean await(long timeout, TimeUnit timeUnit) throws InterruptedException { return latch.await(timeout, timeUnit); } public void awaitUninterruptibly() { while (getResult() == null) { try { await(); return; } catch (InterruptedException e) { logger.debug(e.getMessage(), e); Thread.currentThread().interrupt(); } } } }
{ "content_hash": "94d1254b564ea3d9d5ee207dcb5d0d11", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 176, "avg_line_length": 26.49230769230769, "alnum_prop": 0.6085946573751452, "repo_name": "suraj-raturi/pinpoint", "id": "0105ded3cbc23423b2922f8fa94cd5213bbe7d6c", "size": "2330", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "rpc/src/main/java/com/navercorp/pinpoint/rpc/client/ConnectFuture.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "22853" }, { "name": "CSS", "bytes": "133944" }, { "name": "CoffeeScript", "bytes": "10124" }, { "name": "Groovy", "bytes": "1423" }, { "name": "HTML", "bytes": "473809" }, { "name": "Java", "bytes": "8699243" }, { "name": "JavaScript", "bytes": "2277035" }, { "name": "Makefile", "bytes": "5246" }, { "name": "PLSQL", "bytes": "4156" }, { "name": "Python", "bytes": "3523" }, { "name": "Ruby", "bytes": "943" }, { "name": "Shell", "bytes": "30663" }, { "name": "Thrift", "bytes": "7543" } ], "symlink_target": "" }
import * as vscode from 'vscode'; import { ElixirSenseClient } from './elixirSenseClient'; export function checkTokenCancellation(token: vscode.CancellationToken, result: any) { if (token.isCancellationRequested) { throw new Error('The request was cancelled'); } return result; } export function checkElixirSenseClientInitialized(elixirSenseClient: ElixirSenseClient) { if (!elixirSenseClient) { throw new Error('Elixirsense client not ready'); } return elixirSenseClient; }
{ "content_hash": "e6396efcea90c5cadf3ca6f47f912821", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 89, "avg_line_length": 31.0625, "alnum_prop": 0.7625754527162978, "repo_name": "fr1zle/vscode-elixir", "id": "907923d00e1dc2efb0b1dfc15760e35dae62950c", "size": "497", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/elixirSenseValidations.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Elixir", "bytes": "99666" }, { "name": "Makefile", "bytes": "934" }, { "name": "TypeScript", "bytes": "59788" } ], "symlink_target": "" }
<?php /** * \ElggFileCache * Store cached data in a file store. * * @package Elgg.Core * @subpackage Caches */ class ElggFileCache extends \ElggCache { /** * Set the Elgg cache. * * @param string $cache_path The cache path. * @param int $max_age Maximum age in seconds, 0 if no limit. * @param int $max_size Maximum size of cache in seconds, 0 if no limit. * * @throws ConfigurationException */ public function __construct($cache_path, $max_age = 0, $max_size = 0) { $this->setVariable("cache_path", $cache_path); $this->setVariable("max_age", $max_age); $this->setVariable("max_size", $max_size); if ($cache_path == "") { throw new \ConfigurationException("Cache path set to nothing!"); } } // @codingStandardsIgnoreStart /** * Create and return a handle to a file. * * @deprecated 1.8 Use \ElggFileCache::createFile() * * @param string $filename Filename to save as * @param string $rw Write mode * * @return mixed */ protected function create_file($filename, $rw = "rb") { elgg_deprecated_notice('\ElggFileCache::create_file() is deprecated by ::createFile()', 1.8); return $this->createFile($filename, $rw); } // @codingStandardsIgnoreEnd /** * Create and return a handle to a file. * * @param string $filename Filename to save as * @param string $rw Write mode * * @return mixed */ protected function createFile($filename, $rw = "rb") { // Create a filename matrix $matrix = ""; $depth = strlen($filename); if ($depth > 5) { $depth = 5; } // Create full path $path = $this->getVariable("cache_path") . $matrix; if (!is_dir($path)) { mkdir($path, 0700, true); } // Open the file if ((!file_exists($path . $filename)) && ($rw == "rb")) { return false; } return fopen($path . $filename, $rw); } // @codingStandardsIgnoreStart /** * Create a sanitised filename for the file. * * @deprecated 1.8 Use \ElggFileCache::sanitizeFilename() * * @param string $filename The filename * * @return string */ protected function sanitise_filename($filename) { // @todo : Writeme return $filename; } // @codingStandardsIgnoreEnd /** * Create a sanitised filename for the file. * * @param string $filename The filename * * @return string */ protected function sanitizeFilename($filename) { // @todo : Writeme return $filename; } /** * Save a key * * @param string $key Name * @param string $data Value * * @return boolean */ public function save($key, $data) { $f = $this->createFile($this->sanitizeFilename($key), "wb"); if ($f) { $result = fwrite($f, $data); fclose($f); return $result; } return false; } /** * Load a key * * @param string $key Name * @param int $offset Offset * @param int $limit Limit * * @return string */ public function load($key, $offset = 0, $limit = null) { $f = $this->createFile($this->sanitizeFilename($key)); if ($f) { if (!$limit) { $limit = -1; } $data = stream_get_contents($f, $limit, $offset); fclose($f); return $data; } return false; } /** * Invalidate a given key. * * @param string $key Name * * @return bool */ public function delete($key) { $dir = $this->getVariable("cache_path"); if (file_exists($dir . $key)) { return unlink($dir . $key); } return true; } /** * Delete all files in the directory of this file cache * * @return void */ public function clear() { $dir = $this->getVariable("cache_path"); $exclude = array(".", ".."); $files = scandir($dir); if (!$files) { return; } foreach ($files as $f) { if (!in_array($f, $exclude)) { unlink($dir . $f); } } } /** * Preform cleanup and invalidates cache upon object destruction * * @throws IOException */ public function __destruct() { // @todo Check size and age, clean up accordingly $size = 0; $dir = $this->getVariable("cache_path"); // Short circuit if both size and age are unlimited if (($this->getVariable("max_age") == 0) && ($this->getVariable("max_size") == 0)) { return; } $exclude = array(".", ".."); $files = scandir($dir); if (!$files) { throw new \IOException($dir . " is not a directory."); } // Perform cleanup foreach ($files as $f) { if (!in_array($f, $exclude)) { $stat = stat($dir . $f); // Add size $size .= $stat['size']; // Is this older than my maximum date? if (($this->getVariable("max_age") > 0) && (time() - $stat['mtime'] > $this->getVariable("max_age"))) { unlink($dir . $f); } // @todo Size } } } }
{ "content_hash": "d3ab2a392500fee1da526cd5d86eb806", "timestamp": "", "source": "github", "line_count": 230, "max_line_length": 107, "avg_line_length": 20.308695652173913, "alnum_prop": 0.590237636480411, "repo_name": "miniguez/novadores", "id": "3c6eb43a7e0b9c87dc2a4b8041ae63e158f2d93d", "size": "4671", "binary": false, "copies": "13", "ref": "refs/heads/master", "path": "elgg/engine/classes/ElggFileCache.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "5021" }, { "name": "Batchfile", "bytes": "6697" }, { "name": "CSS", "bytes": "9308" }, { "name": "HTML", "bytes": "29934" }, { "name": "JavaScript", "bytes": "123742" }, { "name": "Makefile", "bytes": "6738" }, { "name": "PHP", "bytes": "5638516" }, { "name": "Python", "bytes": "8408" }, { "name": "Shell", "bytes": "1127" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <android.support.v7.widget.CardView android:layout_width="match_parent" android:layout_height="128dp" android:layout_marginLeft="@dimen/view_xlarge_margin" android:layout_marginRight="@dimen/view_xlarge_margin" android:layout_marginTop="@dimen/view_xlarge_margin"> <LinearLayout android:id="@+id/layout_title" android:layout_width="match_parent" android:layout_height="match_parent" android:background="?selectableItemBackground" android:gravity="center_vertical" android:orientation="vertical"> <TextView android:id="@+id/tv_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:minHeight="@dimen/activity_medium_margin" android:text="@string/app_title" android:textSize="@dimen/title_large_size" /> <TextView android:id="@+id/tv_author" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginRight="@dimen/activity_large_margin" android:gravity="right|end" android:text="@string/app_author" android:textSize="@dimen/text_large_size" /> </LinearLayout> </android.support.v7.widget.CardView> <android.support.v7.widget.RecyclerView android:id="@+id/rv_main" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
{ "content_hash": "96e77c6cfecbb3461222114952b0dbfb", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 73, "avg_line_length": 36.51923076923077, "alnum_prop": 0.6076882569773565, "repo_name": "ericyl/EricylUtils", "id": "11e9826b8f1e01e1fd9c395e8e843109959bf4a2", "size": "1899", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "example/src/main/res/layout/fragment_main.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "469389" } ], "symlink_target": "" }
<?php namespace Fuel\Core; class Cache_Storage_File extends \Cache_Storage_Driver { /** * @const string Tag used for opening & closing cache properties */ const PROPS_TAG = 'Fuel_Cache_Properties'; /** * @var string File caching basepath */ protected static $path = ''; /** * @var array driver specific configuration */ protected $config = array(); public function __construct($identifier, $config) { parent::__construct($identifier, $config); $this->config = isset($config['file']) ? $config['file'] : array(); // check for an expiration override $this->expiration = $this->_validate_config('expiration', isset($this->config['expiration']) ? $this->config['expiration'] : $this->expiration); // determine the file cache path static::$path = !empty($this->config['path']) ? $this->config['path'] : \Config::get('cache_dir', APPPATH.'cache'.DS); if ( ! is_dir(static::$path) || ! is_writable(static::$path)) { throw new \FuelException('Cache directory does not exist or is not writable.'); } } /** * Translates a given identifier to a valid path * * @param string * @return string */ protected function identifier_to_path($identifier) { // replace dots with dashes $identifier = str_replace('.', DS, $identifier); return $identifier; } /** * Prepend the cache properties * * @return string */ protected function prep_contents() { $properties = array( 'created' => $this->created, 'expiration' => $this->expiration, 'dependencies' => $this->dependencies, 'content_handler' => $this->content_handler ); $properties = '{{'.self::PROPS_TAG.'}}'.json_encode($properties).'{{/'.self::PROPS_TAG.'}}'; return $properties.$this->contents; } /** * Remove the prepended cache properties and save them in class properties * * @param string * @throws UnexpectedValueException */ protected function unprep_contents($payload) { $properties_end = strpos($payload, '{{/'.self::PROPS_TAG.'}}'); if ($properties_end === false) { throw new \UnexpectedValueException('Cache has bad formatting'); } $this->contents = substr($payload, $properties_end + strlen('{{/'.self::PROPS_TAG.'}}')); $props = substr(substr($payload, 0, $properties_end), strlen('{{'.self::PROPS_TAG.'}}')); $props = json_decode($props, true); if ($props === null) { throw new \UnexpectedValueException('Cache properties retrieval failed'); } $this->created = $props['created']; $this->expiration = is_null($props['expiration']) ? null : (int) ($props['expiration'] - time()); $this->dependencies = $props['dependencies']; $this->content_handler = $props['content_handler']; } /** * Check if other caches or files have been changed since cache creation * * @param array * @return bool */ public function check_dependencies(array $dependencies) { foreach($dependencies as $dep) { if (file_exists($file = static::$path.str_replace('.', DS, $dep).'.cache')) { $filemtime = filemtime($file); if ($filemtime === false || $filemtime > $this->created) { return false; } } elseif (file_exists($dep)) { $filemtime = filemtime($file); if ($filemtime === false || $filemtime > $this->created) { return false; } } else { return false; } } return true; } /** * Delete Cache */ public function delete() { if (file_exists($file = static::$path.$this->identifier_to_path($this->identifier).'.cache')) { unlink($file); $this->reset(); } } // --------------------------------------------------------------------- /** * Purge all caches * * @param limit purge to subsection * @return bool */ public function delete_all($section) { $path = rtrim(static::$path, '\\/').DS; $section = static::identifier_to_path($section); $files = \File::read_dir($path.$section, -1, array('\.cache$' => 'file')); $delete = function($path, $files) use(&$delete, &$section) { $path = rtrim($path, '\\/').DS; foreach ($files as $dir => $file) { if (is_numeric($dir)) { if ( ! $result = \File::delete($path.$file)) { return $result; } } else { if ( ! $result = ($delete($path.$dir, $file) and rmdir($path.$dir))) { return $result; } } } $section !== '' and rmdir($path); return true; }; return $delete($path.$section, $files); } /** * Save a cache, this does the generic pre-processing * * @return bool success */ protected function _set() { $payload = $this->prep_contents(); $id_path = $this->identifier_to_path($this->identifier); // create directory if necessary $subdirs = explode(DS, $id_path); if (count($subdirs) > 1) { array_pop($subdirs); $test_path = static::$path.implode(DS, $subdirs); // check if specified subdir exists if ( ! @is_dir($test_path)) { // create non existing dir if ( ! @mkdir($test_path, 0755, true)) { return false; } } } // write the cache $file = static::$path.$id_path.'.cache'; $handle = fopen($file, 'c'); if ( ! $handle) { return false; } // wait for a lock while ( ! flock($handle, LOCK_EX)); // truncate the file ftruncate($handle, 0); // write the session data fwrite($handle, $payload); //release the lock flock($handle, LOCK_UN); // close the file fclose($handle); return true; } /** * Load a cache, this does the generic post-processing * * @return bool success */ protected function _get() { $id_path = $this->identifier_to_path( $this->identifier ); $file = static::$path.$id_path.'.cache'; if ( ! file_exists($file)) { return false; } $handle = fopen($file, 'r'); if ( ! $handle) { return false; } // wait for a lock while( ! flock($handle, LOCK_SH)); // read the session data $payload = fread($handle, filesize($file)); //release the lock flock($handle, LOCK_UN); // close the file fclose($handle); try { $this->unprep_contents($payload); } catch (\UnexpectedValueException $e) { return false; } return true; } /** * validate a driver config value * * @param string name of the config variable to validate * @param mixed value * @return mixed */ private function _validate_config($name, $value) { switch ($name) { case 'cache_id': if (empty($value) or ! is_string($value)) { $value = 'fuel'; } break; case 'expiration': if (empty($value) or ! is_numeric($value)) { $value = null; } break; } return $value; } }
{ "content_hash": "f93c6fda68cc3d3d9f3a4fad9620ffce", "timestamp": "", "source": "github", "line_count": 324, "max_line_length": 105, "avg_line_length": 20.700617283950617, "alnum_prop": 0.585656776502162, "repo_name": "seem-sky/FrameworkBenchmarks", "id": "f7f11a372404e9f5cf1c47c8342e0441e8ed22a3", "size": "6934", "binary": false, "copies": "12", "ref": "refs/heads/master", "path": "php-fuel/fuel/core/classes/cache/storage/file.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "838" }, { "name": "ApacheConf", "bytes": "20460" }, { "name": "Batchfile", "bytes": "5149" }, { "name": "C", "bytes": "252520" }, { "name": "C#", "bytes": "128140" }, { "name": "C++", "bytes": "182779" }, { "name": "CSS", "bytes": "234858" }, { "name": "Clojure", "bytes": "18787" }, { "name": "DIGITAL Command Language", "bytes": "34" }, { "name": "Dart", "bytes": "28519" }, { "name": "Elixir", "bytes": "1912" }, { "name": "Erlang", "bytes": "8219" }, { "name": "Go", "bytes": "26375" }, { "name": "Groff", "bytes": "57" }, { "name": "Groovy", "bytes": "18121" }, { "name": "HTML", "bytes": "76218" }, { "name": "Handlebars", "bytes": "242" }, { "name": "Haskell", "bytes": "8929" }, { "name": "Java", "bytes": "261012" }, { "name": "JavaScript", "bytes": "390160" }, { "name": "Lua", "bytes": "6991" }, { "name": "Makefile", "bytes": "2915" }, { "name": "MoonScript", "bytes": "2189" }, { "name": "Nginx", "bytes": "100578" }, { "name": "Nimrod", "bytes": "31172" }, { "name": "PHP", "bytes": "17337660" }, { "name": "Perl", "bytes": "5303" }, { "name": "PowerShell", "bytes": "34846" }, { "name": "Python", "bytes": "337598" }, { "name": "QMake", "bytes": "2056" }, { "name": "Racket", "bytes": "1375" }, { "name": "Ruby", "bytes": "37524" }, { "name": "Scala", "bytes": "58608" }, { "name": "Shell", "bytes": "79156" }, { "name": "Smarty", "bytes": "7730" }, { "name": "Volt", "bytes": "677" } ], "symlink_target": "" }
#include "webrtc/p2p/base/basicpacketsocketfactory.h" #include "webrtc/p2p/base/asyncstuntcpsocket.h" #include "webrtc/p2p/base/stun.h" #include "webrtc/base/asynctcpsocket.h" #include "webrtc/base/asyncudpsocket.h" #include "webrtc/base/logging.h" #include "webrtc/base/nethelpers.h" #include "webrtc/base/physicalsocketserver.h" #include "webrtc/base/scoped_ptr.h" #include "webrtc/base/socketadapters.h" #include "webrtc/base/ssladapter.h" #include "webrtc/base/thread.h" namespace rtc { BasicPacketSocketFactory::BasicPacketSocketFactory() : thread_(Thread::Current()), socket_factory_(NULL) { } BasicPacketSocketFactory::BasicPacketSocketFactory(Thread* thread) : thread_(thread), socket_factory_(NULL) { } BasicPacketSocketFactory::BasicPacketSocketFactory( SocketFactory* socket_factory) : thread_(NULL), socket_factory_(socket_factory) { } BasicPacketSocketFactory::~BasicPacketSocketFactory() { } AsyncPacketSocket* BasicPacketSocketFactory::CreateUdpSocket( const SocketAddress& address, uint16_t min_port, uint16_t max_port) { // UDP sockets are simple. rtc::AsyncSocket* socket = socket_factory()->CreateAsyncSocket( address.family(), SOCK_DGRAM); if (!socket) { return NULL; } if (BindSocket(socket, address, min_port, max_port) < 0) { LOG(LS_ERROR) << "UDP bind failed with error " << socket->GetError(); delete socket; return NULL; } return new rtc::AsyncUDPSocket(socket); } AsyncPacketSocket* BasicPacketSocketFactory::CreateServerTcpSocket( const SocketAddress& local_address, uint16_t min_port, uint16_t max_port, int opts) { // Fail if TLS is required. if (opts & PacketSocketFactory::OPT_TLS) { LOG(LS_ERROR) << "TLS support currently is not available."; return NULL; } rtc::AsyncSocket* socket = socket_factory()->CreateAsyncSocket(local_address.family(), SOCK_STREAM); if (!socket) { return NULL; } if (BindSocket(socket, local_address, min_port, max_port) < 0) { LOG(LS_ERROR) << "TCP bind failed with error " << socket->GetError(); delete socket; return NULL; } // If using SSLTCP, wrap the TCP socket in a pseudo-SSL socket. if (opts & PacketSocketFactory::OPT_SSLTCP) { ASSERT(!(opts & PacketSocketFactory::OPT_TLS)); socket = new rtc::AsyncSSLSocket(socket); } // Set TCP_NODELAY (via OPT_NODELAY) for improved performance. // See http://go/gtalktcpnodelayexperiment socket->SetOption(rtc::Socket::OPT_NODELAY, 1); if (opts & PacketSocketFactory::OPT_STUN) return new cricket::AsyncStunTCPSocket(socket, true); return new rtc::AsyncTCPSocket(socket, true); } AsyncPacketSocket* BasicPacketSocketFactory::CreateClientTcpSocket( const SocketAddress& local_address, const SocketAddress& remote_address, const ProxyInfo& proxy_info, const std::string& user_agent, int opts) { rtc::AsyncSocket* socket = socket_factory()->CreateAsyncSocket(local_address.family(), SOCK_STREAM); if (!socket) { return NULL; } if (BindSocket(socket, local_address, 0, 0) < 0) { LOG(LS_ERROR) << "TCP bind failed with error " << socket->GetError(); delete socket; return NULL; } // If using a proxy, wrap the socket in a proxy socket. if (proxy_info.type == rtc::PROXY_SOCKS5) { socket = new rtc::AsyncSocksProxySocket( socket, proxy_info.address, proxy_info.username, proxy_info.password); } else if (proxy_info.type == rtc::PROXY_HTTPS) { socket = new rtc::AsyncHttpsProxySocket( socket, user_agent, proxy_info.address, proxy_info.username, proxy_info.password); } // If using TLS, wrap the socket in an SSL adapter. if (opts & PacketSocketFactory::OPT_TLS) { ASSERT(!(opts & PacketSocketFactory::OPT_SSLTCP)); rtc::SSLAdapter* ssl_adapter = rtc::SSLAdapter::Create(socket); if (!ssl_adapter) { return NULL; } socket = ssl_adapter; if (ssl_adapter->StartSSL(remote_address.hostname().c_str(), false) != 0) { delete ssl_adapter; return NULL; } // If using SSLTCP, wrap the TCP socket in a pseudo-SSL socket. } else if (opts & PacketSocketFactory::OPT_SSLTCP) { ASSERT(!(opts & PacketSocketFactory::OPT_TLS)); socket = new rtc::AsyncSSLSocket(socket); } if (socket->Connect(remote_address) < 0) { LOG(LS_ERROR) << "TCP connect failed with error " << socket->GetError(); delete socket; return NULL; } // Finally, wrap that socket in a TCP or STUN TCP packet socket. AsyncPacketSocket* tcp_socket; if (opts & PacketSocketFactory::OPT_STUN) { tcp_socket = new cricket::AsyncStunTCPSocket(socket, false); } else { tcp_socket = new rtc::AsyncTCPSocket(socket, false); } // Set TCP_NODELAY (via OPT_NODELAY) for improved performance. // See http://go/gtalktcpnodelayexperiment tcp_socket->SetOption(rtc::Socket::OPT_NODELAY, 1); return tcp_socket; } AsyncResolverInterface* BasicPacketSocketFactory::CreateAsyncResolver() { return new rtc::AsyncResolver(); } int BasicPacketSocketFactory::BindSocket(AsyncSocket* socket, const SocketAddress& local_address, uint16_t min_port, uint16_t max_port) { int ret = -1; if (min_port == 0 && max_port == 0) { // If there's no port range, let the OS pick a port for us. ret = socket->Bind(local_address); } else { // Otherwise, try to find a port in the provided range. for (int port = min_port; ret < 0 && port <= max_port; ++port) { ret = socket->Bind(rtc::SocketAddress(local_address.ipaddr(), port)); } } return ret; } SocketFactory* BasicPacketSocketFactory::socket_factory() { if (thread_) { ASSERT(thread_ == Thread::Current()); return thread_->socketserver(); } else { return socket_factory_; } } } // namespace rtc
{ "content_hash": "f99ae59536748e67ef6679ce8429b21f", "timestamp": "", "source": "github", "line_count": 201, "max_line_length": 79, "avg_line_length": 30.383084577114428, "alnum_prop": 0.6522023906991976, "repo_name": "aleonliao/webrtc-trunk", "id": "697518da9d0508cfcec888306b133514307726c7", "size": "6515", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "p2p/base/basicpacketsocketfactory.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "22469" }, { "name": "C", "bytes": "4035520" }, { "name": "C++", "bytes": "18391697" }, { "name": "Java", "bytes": "126618" }, { "name": "Matlab", "bytes": "42078" }, { "name": "Objective-C", "bytes": "38458" }, { "name": "Objective-C++", "bytes": "284884" }, { "name": "Protocol Buffer", "bytes": "11675" }, { "name": "Python", "bytes": "199412" }, { "name": "Shell", "bytes": "77553" } ], "symlink_target": "" }
int main(int argc, char *argv[]) { const auto command_line_args = clblast::RetrieveCommandLineArguments(argc, argv); switch(clblast::GetPrecision(command_line_args, clblast::Precision::kSingle)) { case clblast::Precision::kHalf: clblast::RunClient<clblast::TestXgemmBatched<clblast::half>, clblast::half, clblast::half>(argc, argv); break; case clblast::Precision::kSingle: clblast::RunClient<clblast::TestXgemmBatched<float>, float, float>(argc, argv); break; case clblast::Precision::kDouble: clblast::RunClient<clblast::TestXgemmBatched<double>, double, double>(argc, argv); break; case clblast::Precision::kComplexSingle: clblast::RunClient<clblast::TestXgemmBatched<clblast::float2>, clblast::float2, clblast::float2>(argc, argv); break; case clblast::Precision::kComplexDouble: clblast::RunClient<clblast::TestXgemmBatched<clblast::double2>, clblast::double2, clblast::double2>(argc, argv); break; } return 0; } // =================================================================================================
{ "content_hash": "96f24385342f5dbad5f586aca62bffb7", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 125, "avg_line_length": 59.888888888888886, "alnum_prop": 0.6614100185528757, "repo_name": "dividiti/CLBlast", "id": "d55a87493c410f00dc820b75bd95f790aa8c743b", "size": "1723", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "test/performance/routines/levelx/xgemmbatched.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "312826" }, { "name": "C++", "bytes": "2490981" }, { "name": "CMake", "bytes": "32239" }, { "name": "Objective-C", "bytes": "120410" }, { "name": "Python", "bytes": "168063" } ], "symlink_target": "" }
<!-- Copyright (c) 2008 lib4j Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. You should have received a copy of The MIT License (MIT) along with this program. If not, see <http://opensource.org/licenses/MIT/>. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org</groupId> <artifactId>lib4j</artifactId> <version>3.2.3-SNAPSHOT</version> </parent> <groupId>org.lib4j</groupId> <artifactId>lib4j-cli</artifactId> <version>2.1.7-SNAPSHOT</version> <name>${project.groupId}:${project.artifactId}</name> <properties> <maven.compiler.source>9</maven.compiler.source> <maven.compiler.target>9</maven.compiler.target> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <build> <plugins> <plugin> <groupId>org.lib4j.maven.plugin</groupId> <artifactId>xjc-maven-plugin</artifactId> <configuration> <destDir>${project.build.directory}/generated-sources/jaxb</destDir> <schemas> <schema>src/main/resources/cli.xsd</schema> </schemas> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>commons-cli</groupId> <artifactId>commons-cli</artifactId> <version>1.2</version> <!-- New versions available: https://mvnrepository.com/artifact/commons-cli/commons-cli --> </dependency> <dependency> <groupId>org.lib4j</groupId> <artifactId>lib4j-logging</artifactId> </dependency> <dependency> <groupId>org.lib4j.xml</groupId> <artifactId>xml-jaxb</artifactId> </dependency> <dependency> <groupId>org.lib4j</groupId> <artifactId>lib4j-test</artifactId> <scope>test</scope> </dependency> </dependencies> </project>
{ "content_hash": "47edd406c815a95e10c160745eadebe2", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 120, "avg_line_length": 36.44285714285714, "alnum_prop": 0.6860054880439044, "repo_name": "SevaSafris/java", "id": "31972e4dcae42332046c1d5c0abc888042c1a8d1", "size": "2551", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib4j/cli/pom.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "6387651" }, { "name": "Shell", "bytes": "251" }, { "name": "XSLT", "bytes": "26041" } ], "symlink_target": "" }
package org.zstack.sdk; public class DeleteImageResult { }
{ "content_hash": "e1481fc86b053766d0fef08ac1580437", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 32, "avg_line_length": 9, "alnum_prop": 0.746031746031746, "repo_name": "camilesing/zstack", "id": "6c290f09351c92f14107bce78c7ffd950a592349", "size": "63", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "sdk/src/main/java/org/zstack/sdk/DeleteImageResult.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "59340" }, { "name": "Batchfile", "bytes": "1132" }, { "name": "Groovy", "bytes": "3831914" }, { "name": "Java", "bytes": "17687564" }, { "name": "Python", "bytes": "1055353" }, { "name": "SQLPL", "bytes": "12754" }, { "name": "Shell", "bytes": "159234" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <script src="../../../js-test-resources/js-test.js"></script> <script> function runTest() { description('Tests that loading a same-origin frame with a URL that contains an anchor fragment does scroll this frame.'); description('This tests that the framesniffing defenses are not overzealous.'); // Check scroll position in a timeout to make sure that the anchor has been scrolled to. setTimeout(function() { shouldBeTrue('document.scrollingElement.scrollTop > 0'); shouldBeTrue('document.scrollingElement.scrollLeft > 0'); finishJSTest(); }, 1); } var jsTestIsAsync = true; </script> </head> <body> <!-- large same-origin grandchild frame --> <iframe height="8000" width="8000" src="http://127.0.0.1:8000/navigation/resources/grandchild-with-anchor.html#anchor1" name="grandchild" onload="runTest()"> </iframe> </body> </html>
{ "content_hash": "17548b32d81de4396116c5b655cfc158", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 157, "avg_line_length": 39.041666666666664, "alnum_prop": 0.6734258271077909, "repo_name": "chromium/chromium", "id": "ed2a49c0e661804a4dd8e506c5cd6de95a23a4af", "size": "937", "binary": false, "copies": "9", "ref": "refs/heads/main", "path": "third_party/blink/web_tests/http/tests/navigation/resources/frame-with-anchor-same-origin.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
var setColor = require('ansi-color').set; var util = require('util'); var PassThrough = require('stream').PassThrough; var Console = require('console').Console; function makePassThrough (strm) { var passthrough = new PassThrough(); passthrough.pipe(strm); return passthrough; } function DavLog (options) { options = options || {}; this.beSilent = false; this.beQuiet = false; this.isTTY = process.stdin.isTTY; if (options.color === false) { this.isTTY = false; } this.timestamps = options.timestamps; this.name = options.name || 'davlog'; this.pcolor = options.color || 'magenta'; this.stdout = makePassThrough(options.stdout || process.stdout); this.stderr = makePassThrough(options.stderr || process.stderr); var thisConsole = new Console(this.stdout, this.stderr); this.logFn = thisConsole.log; this.errFn = thisConsole.error; this.COLORS = { info: 'white', log: 'cyan', warn: 'yellow', error: 'red', err: 'red' }; this.STRINGS = { info: 'info', log: 'log', warn: 'warn', error: 'error', err: 'err' }; } ['logFn', 'errFn'].forEach(function(name){ var hiddenName = '_' + name; Object.defineProperty(DavLog.prototype, name, { get: function () { return this[hiddenName]; }, set: function (fn) { this[hiddenName] = fn; this.reset(); } }); }); function prefixWithTimestamps () { return new Date().toISOString() + ' ' + this.color(this.name, this.pcolor); } function prefixNoTimestamps () { return this.color(this.name, this.pcolor); } DavLog.prototype.quiet = function quiet () { this.beQuiet = true; this.reset(); }; DavLog.prototype.silent = function silent () { this.beSilent = true; this.beQuiet = true; this.reset(); }; function noop() {} function noopPass (str) { return str; } function color (str, code) { if (!this.isTTY) { return str; } return setColor(str, code); } function makeLogFunction(type, logFn) { return function aLogFunction() { logFn.apply(this, this.setup(type, arguments)); }; } DavLog.prototype.reset = function reset () { this.info = this.beQuiet ? noop : makeLogFunction('info', this.logFn).bind(this); this.log = this.beQuiet ? noop : makeLogFunction('log', this.logFn).bind(this); this.warn = this.beQuiet ? noop : makeLogFunction('warn', this.logFn).bind(this); this.err = this.beSilent ? noop : makeLogFunction('err', this.errFn).bind(this); this.error = this.beSilent ? process.exit.bind(process, 1) : function errorOut() { makeLogFunction('error', this.errFn).apply(this, arguments); process.exit(1); }.bind(this); this.prefix = this.timestamps ? prefixWithTimestamps : prefixNoTimestamps; this.color = this.isTTY ? color : noopPass; }; DavLog.prototype.setup = function setup (type, args) { return [ this.prefix(), this.color('[' + this.STRINGS[type] + ']', this.COLORS[type]), util.format.apply(null, args) ]; }; DavLog.prototype.init = function init (options) { return new DavLog(options); }; module.exports = new DavLog();
{ "content_hash": "43c80f91485d92f82ae1f1d670176552", "timestamp": "", "source": "github", "line_count": 124, "max_line_length": 86, "avg_line_length": 26.451612903225808, "alnum_prop": 0.6152439024390244, "repo_name": "davglass/davlog", "id": "6ebdf93c522969b9014ea286b80fcfc880408c12", "size": "3440", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/index.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "JavaScript", "bytes": "13673" } ], "symlink_target": "" }
package resource import ( "bytes" "errors" "io" "io/ioutil" "net/http" "reflect" "strings" "testing" "github.com/GoogleCloudPlatform/kubernetes/pkg/api" "github.com/GoogleCloudPlatform/kubernetes/pkg/api/testapi" "github.com/GoogleCloudPlatform/kubernetes/pkg/client" "github.com/GoogleCloudPlatform/kubernetes/pkg/labels" "github.com/GoogleCloudPlatform/kubernetes/pkg/runtime" ) func objBody(obj runtime.Object) io.ReadCloser { return ioutil.NopCloser(bytes.NewReader([]byte(runtime.EncodeOrDie(testapi.Codec(), obj)))) } // splitPath returns the segments for a URL path. func splitPath(path string) []string { path = strings.Trim(path, "/") if path == "" { return []string{} } return strings.Split(path, "/") } func TestHelperDelete(t *testing.T) { tests := []struct { Err bool Req func(*http.Request) bool Resp *http.Response HttpErr error }{ { HttpErr: errors.New("failure"), Err: true, }, { Resp: &http.Response{ StatusCode: http.StatusNotFound, Body: objBody(&api.Status{Status: api.StatusFailure}), }, Err: true, }, { Resp: &http.Response{ StatusCode: http.StatusOK, Body: objBody(&api.Status{Status: api.StatusSuccess}), }, Req: func(req *http.Request) bool { if req.Method != "DELETE" { t.Errorf("unexpected method: %#v", req) return false } parts := splitPath(req.URL.Path) if len(parts) < 3 { t.Errorf("expected URL path to have 3 parts: %s", req.URL.Path) return false } if parts[1] != "bar" { t.Errorf("url doesn't contain namespace: %#v", req) return false } if parts[2] != "foo" { t.Errorf("url doesn't contain name: %#v", req) return false } return true }, }, } for _, test := range tests { client := &client.FakeRESTClient{ Codec: testapi.Codec(), Resp: test.Resp, Err: test.HttpErr, } modifier := &Helper{ RESTClient: client, NamespaceScoped: true, } err := modifier.Delete("bar", "foo") if (err != nil) != test.Err { t.Errorf("unexpected error: %t %v", test.Err, err) } if err != nil { continue } if test.Req != nil && !test.Req(client.Req) { t.Errorf("unexpected request: %#v", client.Req) } } } func TestHelperCreate(t *testing.T) { expectPost := func(req *http.Request) bool { if req.Method != "POST" { t.Errorf("unexpected method: %#v", req) return false } parts := splitPath(req.URL.Path) if parts[1] != "bar" { t.Errorf("url doesn't contain namespace: %#v", req) return false } return true } tests := []struct { Resp *http.Response RespFunc client.HTTPClientFunc HttpErr error Modify bool Object runtime.Object ExpectObject runtime.Object Err bool Req func(*http.Request) bool }{ { HttpErr: errors.New("failure"), Err: true, }, { Resp: &http.Response{ StatusCode: http.StatusNotFound, Body: objBody(&api.Status{Status: api.StatusFailure}), }, Err: true, }, { Resp: &http.Response{ StatusCode: http.StatusOK, Body: objBody(&api.Status{Status: api.StatusSuccess}), }, Object: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}, ExpectObject: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}, Req: expectPost, }, { Modify: false, Object: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "10"}}, ExpectObject: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "10"}}, Resp: &http.Response{StatusCode: http.StatusOK, Body: objBody(&api.Status{Status: api.StatusSuccess})}, Req: expectPost, }, { Modify: true, Object: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "10"}}, ExpectObject: &api.Pod{ ObjectMeta: api.ObjectMeta{Name: "foo"}, Spec: api.PodSpec{ RestartPolicy: api.RestartPolicyAlways, DNSPolicy: api.DNSClusterFirst, }, }, Resp: &http.Response{StatusCode: http.StatusOK, Body: objBody(&api.Status{Status: api.StatusSuccess})}, Req: expectPost, }, } for i, test := range tests { client := &client.FakeRESTClient{ Codec: testapi.Codec(), Resp: test.Resp, Err: test.HttpErr, } if test.RespFunc != nil { client.Client = test.RespFunc } modifier := &Helper{ RESTClient: client, Codec: testapi.Codec(), Versioner: testapi.MetadataAccessor(), NamespaceScoped: true, } data := []byte{} if test.Object != nil { data = []byte(runtime.EncodeOrDie(testapi.Codec(), test.Object)) } _, err := modifier.Create("bar", test.Modify, data) if (err != nil) != test.Err { t.Errorf("%d: unexpected error: %t %v", i, test.Err, err) } if err != nil { continue } if test.Req != nil && !test.Req(client.Req) { t.Errorf("%d: unexpected request: %#v", i, client.Req) } body, err := ioutil.ReadAll(client.Req.Body) if err != nil { t.Fatalf("%d: unexpected error: %#v", i, err) } t.Logf("got body: %s", string(body)) expect := []byte{} if test.ExpectObject != nil { expect = []byte(runtime.EncodeOrDie(testapi.Codec(), test.ExpectObject)) } if !reflect.DeepEqual(expect, body) { t.Errorf("%d: unexpected body: %s", i, string(body)) } } } func TestHelperGet(t *testing.T) { tests := []struct { Err bool Req func(*http.Request) bool Resp *http.Response HttpErr error }{ { HttpErr: errors.New("failure"), Err: true, }, { Resp: &http.Response{ StatusCode: http.StatusNotFound, Body: objBody(&api.Status{Status: api.StatusFailure}), }, Err: true, }, { Resp: &http.Response{ StatusCode: http.StatusOK, Body: objBody(&api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}), }, Req: func(req *http.Request) bool { if req.Method != "GET" { t.Errorf("unexpected method: %#v", req) return false } parts := splitPath(req.URL.Path) if parts[1] != "bar" { t.Errorf("url doesn't contain namespace: %#v", req) return false } if parts[2] != "foo" { t.Errorf("url doesn't contain name: %#v", req) return false } return true }, }, } for _, test := range tests { client := &client.FakeRESTClient{ Codec: testapi.Codec(), Resp: test.Resp, Err: test.HttpErr, } modifier := &Helper{ RESTClient: client, NamespaceScoped: true, } obj, err := modifier.Get("bar", "foo") if (err != nil) != test.Err { t.Errorf("unexpected error: %t %v", test.Err, err) } if err != nil { continue } if obj.(*api.Pod).Name != "foo" { t.Errorf("unexpected object: %#v", obj) } if test.Req != nil && !test.Req(client.Req) { t.Errorf("unexpected request: %#v", client.Req) } } } func TestHelperList(t *testing.T) { tests := []struct { Err bool Req func(*http.Request) bool Resp *http.Response HttpErr error }{ { HttpErr: errors.New("failure"), Err: true, }, { Resp: &http.Response{ StatusCode: http.StatusNotFound, Body: objBody(&api.Status{Status: api.StatusFailure}), }, Err: true, }, { Resp: &http.Response{ StatusCode: http.StatusOK, Body: objBody(&api.PodList{ Items: []api.Pod{{ ObjectMeta: api.ObjectMeta{Name: "foo"}, }, }, }), }, Req: func(req *http.Request) bool { if req.Method != "GET" { t.Errorf("unexpected method: %#v", req) return false } if req.URL.Path != "/namespaces/bar" { t.Errorf("url doesn't contain name: %#v", req.URL) return false } if req.URL.Query().Get("labels") != labels.SelectorFromSet(labels.Set{"foo": "baz"}).String() { t.Errorf("url doesn't contain query parameters: %#v", req.URL) return false } return true }, }, } for _, test := range tests { client := &client.FakeRESTClient{ Codec: testapi.Codec(), Resp: test.Resp, Err: test.HttpErr, } modifier := &Helper{ RESTClient: client, NamespaceScoped: true, } obj, err := modifier.List("bar", testapi.Version(), labels.SelectorFromSet(labels.Set{"foo": "baz"})) if (err != nil) != test.Err { t.Errorf("unexpected error: %t %v", test.Err, err) } if err != nil { continue } if obj.(*api.PodList).Items[0].Name != "foo" { t.Errorf("unexpected object: %#v", obj) } if test.Req != nil && !test.Req(client.Req) { t.Errorf("unexpected request: %#v", client.Req) } } } func TestHelperUpdate(t *testing.T) { expectPut := func(req *http.Request) bool { if req.Method != "PUT" { t.Errorf("unexpected method: %#v", req) return false } parts := splitPath(req.URL.Path) if parts[1] != "bar" { t.Errorf("url doesn't contain namespace: %#v", req.URL) return false } if parts[2] != "foo" { t.Errorf("url doesn't contain name: %#v", req) return false } return true } tests := []struct { Resp *http.Response RespFunc client.HTTPClientFunc HttpErr error Overwrite bool Object runtime.Object ExpectObject runtime.Object Err bool Req func(*http.Request) bool }{ { HttpErr: errors.New("failure"), Err: true, }, { Object: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}, Resp: &http.Response{ StatusCode: http.StatusNotFound, Body: objBody(&api.Status{Status: api.StatusFailure}), }, Err: true, }, { Object: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}, ExpectObject: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}, Resp: &http.Response{ StatusCode: http.StatusOK, Body: objBody(&api.Status{Status: api.StatusSuccess}), }, Req: expectPut, }, { Object: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}, ExpectObject: &api.Pod{ ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "10"}, Spec: api.PodSpec{ RestartPolicy: api.RestartPolicyAlways, DNSPolicy: api.DNSClusterFirst, }, }, Overwrite: true, RespFunc: func(req *http.Request) (*http.Response, error) { if req.Method == "PUT" { return &http.Response{StatusCode: http.StatusOK, Body: objBody(&api.Status{Status: api.StatusSuccess})}, nil } return &http.Response{StatusCode: http.StatusOK, Body: objBody(&api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "10"}})}, nil }, Req: expectPut, }, { Object: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "10"}}, ExpectObject: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "10"}}, Resp: &http.Response{StatusCode: http.StatusOK, Body: objBody(&api.Status{Status: api.StatusSuccess})}, Req: expectPut, }, } for i, test := range tests { client := &client.FakeRESTClient{ Codec: testapi.Codec(), Resp: test.Resp, Err: test.HttpErr, } if test.RespFunc != nil { client.Client = test.RespFunc } modifier := &Helper{ RESTClient: client, Codec: testapi.Codec(), Versioner: testapi.MetadataAccessor(), NamespaceScoped: true, } data := []byte{} if test.Object != nil { data = []byte(runtime.EncodeOrDie(testapi.Codec(), test.Object)) } _, err := modifier.Update("bar", "foo", test.Overwrite, data) if (err != nil) != test.Err { t.Errorf("%d: unexpected error: %t %v", i, test.Err, err) } if err != nil { continue } if test.Req != nil && !test.Req(client.Req) { t.Errorf("%d: unexpected request: %#v", i, client.Req) } body, err := ioutil.ReadAll(client.Req.Body) if err != nil { t.Fatalf("%d: unexpected error: %#v", i, err) } t.Logf("got body: %s", string(body)) expect := []byte{} if test.ExpectObject != nil { expect = []byte(runtime.EncodeOrDie(testapi.Codec(), test.ExpectObject)) } if !reflect.DeepEqual(expect, body) { t.Errorf("%d: unexpected body: %s", i, string(body)) } } }
{ "content_hash": "b08c4c6b50e4eb9039a2496bdb6c46c1", "timestamp": "", "source": "github", "line_count": 469, "max_line_length": 146, "avg_line_length": 25.571428571428573, "alnum_prop": 0.606937380138414, "repo_name": "sdodson/origin", "id": "a56b31b8774313b9e8c4864b0435f9aef775f0e5", "size": "12571", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Godeps/_workspace/src/github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/resource/helper_test.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "44938" }, { "name": "Go", "bytes": "10015658" }, { "name": "HTML", "bytes": "70349" }, { "name": "JavaScript", "bytes": "198824" }, { "name": "Makefile", "bytes": "2748" }, { "name": "Python", "bytes": "3979" }, { "name": "Ruby", "bytes": "236" }, { "name": "Shell", "bytes": "97004" } ], "symlink_target": "" }
package com.zinibu.employee; import java.util.*; public class Employee { public static final int X = 10; public Employee(String n, double s, int year, int month, int day) { name = n; salary = s; GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day); System.out.println("Hey"); System.out.println("Now"); hireDay = calendar.getTime(); } public void raiseSalary(double byPercent) { double raise = salary * byPercent / 100; salary += raise; } public String getName() { return name; } public Date getHireDay() { return (Date) hireDay.clone(); } public double getSalary() { return salary; } /** * @return String salutation and name */ public String sayHi() { return "super dear " + name; } public static String sayCompanyName() { return "Acme Company"; } private final String name; // we set final because name won't change after the object is created. private String nickName; /** * Get the nickName * * @return the nickName */ public String getNickName() { return nickName; } /** * Set the nickName * * @param nickName the nickName to set */ public void setNickName(String nickName) { this.nickName = nickName; } private Date hireDay; private double salary; public static final int ID = 123; // static constant, so there's only this one for the class, instead of one per instance public static void main(String[] args) { Employee e = new Employee("Mike", 102.47, 2010, 2, 1); System.out.println("Hey from Employee class main " + e.getName() + ", you were hired on " + e.getHireDay() + " and your salary is now " + e.getSalary()); } }
{ "content_hash": "773c8b7cd8ef650c2c7a7689728b9c2d", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 161, "avg_line_length": 23.68354430379747, "alnum_prop": 0.5938001068947087, "repo_name": "alexisbellido/Java-and-Eclipse", "id": "dfae97fa1aed6d6c8ad4a6c66a4b804dec4da26f", "size": "1871", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/zinibu/employee/Employee.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "1391" }, { "name": "Java", "bytes": "11604" } ], "symlink_target": "" }
layout: event title: "McCabe, Halsted, WTFPS – Software Metriken zum Mitnehmen" date: 2014-06-04 19:15:00 tags: events speakers: - tgetrost location: hs-karlsruhe-m202 --- McCabe, Halsted, Cyclomatic Complexity, WTFPS? Nie gehört? Schon mal gehört, aber was ist das eigentlich? Was sagen mir die Werte in meinem Code Quality Dashboard? (Code-) Metriken machen verschiedene (Qualitäts-) Aspekte der Softwareentwicklung vergleich- und messbar. Sie unterstützen die Identifizierung von Schwachstellen und helfen nötige „Refactorings“ in Projekten zu platzieren. Der Vortrag gibt eine kompakte Einführung in die Welt der Code Metriken und ihrer Verwendung. Er verfolgt drei Ziele: Als erstes wird anhand eines Beispiels veranschaulicht, welchen Sachverhalt wir mit der Metrik quantifizieren. Als zweites beantworten wir die Frage wie die Metrik berechnet wird und welche Arten der Visualisierung zur Verfügung stehen. Abschließend werden mögliche Reaktionen und Konflikte zwischen Metrik und den Programmierzielen erörtert.
{ "content_hash": "fd8da537ede79839eafe44e7d4f4b447", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 342, "avg_line_length": 73.28571428571429, "alnum_prop": 0.8167641325536062, "repo_name": "fhopf/jugka-site", "id": "5f8b29713ae471b91be999e279b7f7131ea8f6fc", "size": "1046", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/events/2014-06-04-software-metriken-zum-mitnehmen.markdown", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "20082" }, { "name": "HTML", "bytes": "11441" }, { "name": "JavaScript", "bytes": "367" }, { "name": "Ruby", "bytes": "6009" } ], "symlink_target": "" }
package org.uberfire.java.nio.fs.jgit.util.commands; public class PathUtil { public static String normalize(final String path) { if (path.equals("/")) { return ""; } final boolean startsWith = path.startsWith("/"); final boolean endsWith = path.endsWith("/"); if (startsWith && endsWith) { return path.substring(1, path.length() - 1); } if (startsWith) { return path.substring(1); } if (endsWith) { return path.substring(0, path.length() - 1); } return path; } }
{ "content_hash": "97e6d07a0503b8e9582bc11d5d868e6f", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 56, "avg_line_length": 24.321428571428573, "alnum_prop": 0.47577092511013214, "repo_name": "karreiro/uberfire", "id": "27233e5369e0dd2181967ebd1bf5c8f0a286245c", "size": "1302", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "uberfire-nio2-backport/uberfire-nio2-impls/uberfire-nio2-jgit/src/main/java/org/uberfire/java/nio/fs/jgit/util/commands/PathUtil.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "80257" }, { "name": "FreeMarker", "bytes": "46611" }, { "name": "HTML", "bytes": "106890" }, { "name": "Java", "bytes": "15858867" }, { "name": "JavaScript", "bytes": "86367" }, { "name": "Shell", "bytes": "5994" } ], "symlink_target": "" }
package 练习26 object Runner extends App { val item01 = Item("Item01") val item02 = Item("Item02") val item03 = Item("Item03") val item04 = Item("Item04") val item05 = Item("Item05") val item06 = Item("Item06") val item07 = Item("Item07") case class Number2P1(tail1: Number2, override val head: Item) extends Number2P { override def tail: Number2 = { val zero = new Number2O2 val num = Number2P1(Number2P1(Number2P1(Number2P1(Number2P1(zero, item01), item02), item03), item04), item05) number0.tail1 = num number0 = zero tail1 } } case class Number2O11(override var tail1: Number2) extends Number2O1 { override def tail: Number2 = { val zero = Number2O11(null) number0.tail1 = zero number0 = zero tail1 } } var number0: Number3 = null var number1: Number2 = null def reset: Unit = { number0 = Number2O11(null) number1 = Number2P1(Number2P1(Number2P1(Number2P1(number0, item01), item02), item03), item04) } val number2 = Number1P(Number1P(Number1P(Number1O, item01), item02), item03) val number3 = Number1P(Number1P(Number1P(Number1P(Number1P(Number1P(Number1O, item01), item02), item03), item04), item05), item06) reset println(ResultP(number2.method1(number1), item01).length) // 5 ^ 3 = 125 reset println(ResultP(number3.method1(number1), item01).length) // 5 ^ 6 = 15625 }
{ "content_hash": "9124eba4260c1ab6bbfc07dd25ad38c1", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 132, "avg_line_length": 29.851063829787233, "alnum_prop": 0.6749821810406272, "repo_name": "djx314/ubw", "id": "003a29d00eacc75199e50d5cf935eae8384e4b92", "size": "1407", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "a28-练习/src/main/scala/练习26/Runner.scala", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Scala", "bytes": "1020964" } ], "symlink_target": "" }
namespace { const char* const kDidChangeView = "DidChangeView"; const char* const kHandleInputEvent = "DidHandleInputEvent"; const char* const kDidChangeFocus = "DidChangeFocus"; const char* const kHaveFocus = "HaveFocus"; const char* const kDontHaveFocus = "DontHaveFocus"; // Convert a given modifier to a descriptive string. Note that the actual // declared type of modifier in each of the event classes is uint32_t, but it is // expected to be interpreted as a bitfield of 'or'ed PP_InputEvent_Modifier // values. std::string ModifierToString(uint32_t modifier) { std::string s; if (modifier & PP_INPUTEVENT_MODIFIER_SHIFTKEY) { s += "shift "; } if (modifier & PP_INPUTEVENT_MODIFIER_CONTROLKEY) { s += "ctrl "; } if (modifier & PP_INPUTEVENT_MODIFIER_ALTKEY) { s += "alt "; } if (modifier & PP_INPUTEVENT_MODIFIER_METAKEY) { s += "meta "; } if (modifier & PP_INPUTEVENT_MODIFIER_ISKEYPAD) { s += "keypad "; } if (modifier & PP_INPUTEVENT_MODIFIER_ISAUTOREPEAT) { s += "autorepeat "; } if (modifier & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN) { s += "left-button-down "; } if (modifier & PP_INPUTEVENT_MODIFIER_MIDDLEBUTTONDOWN) { s += "middle-button-down "; } if (modifier & PP_INPUTEVENT_MODIFIER_RIGHTBUTTONDOWN) { s += "right-button-down "; } if (modifier & PP_INPUTEVENT_MODIFIER_CAPSLOCKKEY) { s += "caps-lock "; } if (modifier & PP_INPUTEVENT_MODIFIER_NUMLOCKKEY) { s += "num-lock "; } return s; } std::string MouseButtonToString(PP_InputEvent_MouseButton button) { switch (button) { case PP_INPUTEVENT_MOUSEBUTTON_NONE: return "None"; case PP_INPUTEVENT_MOUSEBUTTON_LEFT: return "Left"; case PP_INPUTEVENT_MOUSEBUTTON_MIDDLE: return "Middle"; case PP_INPUTEVENT_MOUSEBUTTON_RIGHT: return "Right"; default: std::ostringstream stream; stream << "Unrecognized (" << static_cast<int32_t>(button) << ")"; return stream.str(); } } } // namespace class EventInstance : public pp::Instance { public: explicit EventInstance(PP_Instance instance) : pp::Instance(instance) { RequestInputEvents(PP_INPUTEVENT_CLASS_MOUSE | PP_INPUTEVENT_CLASS_WHEEL | PP_INPUTEVENT_CLASS_TOUCH); RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD); } virtual ~EventInstance() {} /// Clicking outside of the instance's bounding box /// will create a DidChangeFocus event (the NaCl instance is /// out of focus). Clicking back inside the instance's /// bounding box will create another DidChangeFocus event /// (the NaCl instance is back in focus). The default is /// that the instance is out of focus. void DidChangeFocus(bool focus) { PostMessage(pp::Var(kDidChangeFocus)); if (focus == true) { PostMessage(pp::Var(kHaveFocus)); } else { PostMessage(pp::Var(kDontHaveFocus)); } } /// Scrolling the mouse wheel causes a DidChangeView event. void DidChangeView(const pp::View& view) { PostMessage(pp::Var(kDidChangeView)); } void GotKeyEvent(const pp::KeyboardInputEvent& key_event, const std::string& kind) { std::ostringstream stream; stream << pp_instance() << ":" << " Key event:" << kind << " modifier:" << ModifierToString(key_event.GetModifiers()) << " key_code:" << key_event.GetKeyCode() << " time:" << key_event.GetTimeStamp() << " text:" << key_event.GetCharacterText().DebugString() << "\n"; PostMessage(stream.str()); } void GotMouseEvent(const pp::MouseInputEvent& mouse_event, const std::string& kind) { std::ostringstream stream; stream << pp_instance() << ":" << " Mouse event:" << kind << " modifier:" << ModifierToString(mouse_event.GetModifiers()) << " button:" << MouseButtonToString(mouse_event.GetButton()) << " x:" << mouse_event.GetPosition().x() << " y:" << mouse_event.GetPosition().y() << " click_count:" << mouse_event.GetClickCount() << " time:" << mouse_event.GetTimeStamp() << "\n"; PostMessage(stream.str()); } void GotWheelEvent(const pp::WheelInputEvent& wheel_event) { std::ostringstream stream; stream << pp_instance() << ": Wheel event." << " modifier:" << ModifierToString(wheel_event.GetModifiers()) << " deltax:" << wheel_event.GetDelta().x() << " deltay:" << wheel_event.GetDelta().y() << " wheel_ticks_x:" << wheel_event.GetTicks().x() << " wheel_ticks_y:"<< wheel_event.GetTicks().y() << " scroll_by_page: " << (wheel_event.GetScrollByPage() ? "true" : "false") << "\n"; PostMessage(stream.str()); } void GotTouchEvent(const pp::TouchInputEvent& touch_event, const std::string& kind) { std::ostringstream stream; stream << pp_instance() << ":" << " Touch event:" << kind << " modifier:" << ModifierToString(touch_event.GetModifiers()); uint32_t touch_count = touch_event.GetTouchCount(PP_TOUCHLIST_TYPE_CHANGEDTOUCHES); for (uint32_t i = 0; i < touch_count; ++i) { pp::TouchPoint point = touch_event.GetTouchByIndex(PP_TOUCHLIST_TYPE_CHANGEDTOUCHES, i); stream << " x[" << point.id() << "]:" << point.position().x(); stream << " y[" << point.id() << "]:" << point.position().y(); stream << " radius_x[" << point.id() << "]:" << point.radii().x(); stream << " radius_y[" << point.id() << "]:" << point.radii().y(); stream << " angle[" << point.id() << "]:" << point.rotation_angle(); stream << " pressure[" << point.id() << "]:" << point.pressure(); } PostMessage(stream.str()); } // Handle an incoming input event by switching on type and dispatching // to the appropriate subtype handler. // // HandleInputEvent operates on the main Pepper thread. In large // real-world applications, you'll want to create a separate thread // that puts events in a queue and handles them independant of the main // thread so as not to slow down the browser. There is an additional // version of this example in the examples directory that demonstrates // this best practice. virtual bool HandleInputEvent(const pp::InputEvent& event) { PostMessage(pp::Var(kHandleInputEvent)); switch (event.GetType()) { case PP_INPUTEVENT_TYPE_UNDEFINED: break; case PP_INPUTEVENT_TYPE_MOUSEDOWN: GotMouseEvent(pp::MouseInputEvent(event), "Down"); break; case PP_INPUTEVENT_TYPE_MOUSEUP: GotMouseEvent(pp::MouseInputEvent(event), "Up"); break; case PP_INPUTEVENT_TYPE_MOUSEMOVE: GotMouseEvent(pp::MouseInputEvent(event), "Move"); break; case PP_INPUTEVENT_TYPE_MOUSEENTER: GotMouseEvent(pp::MouseInputEvent(event), "Enter"); break; case PP_INPUTEVENT_TYPE_MOUSELEAVE: GotMouseEvent(pp::MouseInputEvent(event), "Leave"); break; case PP_INPUTEVENT_TYPE_WHEEL: GotWheelEvent(pp::WheelInputEvent(event)); break; case PP_INPUTEVENT_TYPE_RAWKEYDOWN: GotKeyEvent(pp::KeyboardInputEvent(event), "RawKeyDown"); break; case PP_INPUTEVENT_TYPE_KEYDOWN: GotKeyEvent(pp::KeyboardInputEvent(event), "Down"); break; case PP_INPUTEVENT_TYPE_KEYUP: GotKeyEvent(pp::KeyboardInputEvent(event), "Up"); break; case PP_INPUTEVENT_TYPE_CHAR: GotKeyEvent(pp::KeyboardInputEvent(event), "Character"); break; case PP_INPUTEVENT_TYPE_CONTEXTMENU: GotKeyEvent(pp::KeyboardInputEvent(event), "Context"); break; // Note that if we receive an IME event we just send a message back // to the browser to indicate we have received it. case PP_INPUTEVENT_TYPE_IME_COMPOSITION_START: PostMessage(pp::Var("PP_INPUTEVENT_TYPE_IME_COMPOSITION_START")); break; case PP_INPUTEVENT_TYPE_IME_COMPOSITION_UPDATE: PostMessage(pp::Var("PP_INPUTEVENT_TYPE_IME_COMPOSITION_UPDATE")); break; case PP_INPUTEVENT_TYPE_IME_COMPOSITION_END: PostMessage(pp::Var("PP_INPUTEVENT_TYPE_IME_COMPOSITION_END")); break; case PP_INPUTEVENT_TYPE_IME_TEXT: PostMessage(pp::Var("PP_INPUTEVENT_TYPE_IME_COMPOSITION_TEXT")); break; case PP_INPUTEVENT_TYPE_TOUCHSTART: GotTouchEvent(pp::TouchInputEvent(event), "Start"); break; case PP_INPUTEVENT_TYPE_TOUCHMOVE: GotTouchEvent(pp::TouchInputEvent(event), "Move"); break; case PP_INPUTEVENT_TYPE_TOUCHEND: GotTouchEvent(pp::TouchInputEvent(event), "End"); break; case PP_INPUTEVENT_TYPE_TOUCHCANCEL: GotTouchEvent(pp::TouchInputEvent(event), "Cancel"); break; default: assert(false); return false; } return true; } }; // The EventModule provides an implementation of pp::Module that creates // EventInstance objects when invoked. This is part of the glue code that makes // our example accessible to ppapi. class EventModule : public pp::Module { public: EventModule() : pp::Module() {} virtual ~EventModule() {} virtual pp::Instance* CreateInstance(PP_Instance instance) { return new EventInstance(instance); } }; // Implement the required pp::CreateModule function that creates our specific // kind of Module (in this case, EventModule). This is part of the glue code // that makes our example accessible to ppapi. namespace pp { Module* CreateModule() { return new EventModule(); } }
{ "content_hash": "60e0b532dcbe51df9a38dc2d6071db8b", "timestamp": "", "source": "github", "line_count": 265, "max_line_length": 80, "avg_line_length": 36.74339622641509, "alnum_prop": 0.6307897709766869, "repo_name": "leighpauls/k2cro4", "id": "a84822bab9c7ad289b55a482ae3d80d5e93b561e", "size": "10173", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "native_client_sdk/src/examples/input_events/input_events.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "3062" }, { "name": "AppleScript", "bytes": "25392" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "68131038" }, { "name": "C", "bytes": "242794338" }, { "name": "C#", "bytes": "11024" }, { "name": "C++", "bytes": "353525184" }, { "name": "Common Lisp", "bytes": "3721" }, { "name": "D", "bytes": "1931" }, { "name": "Emacs Lisp", "bytes": "1639" }, { "name": "F#", "bytes": "4992" }, { "name": "FORTRAN", "bytes": "10404" }, { "name": "Java", "bytes": "3845159" }, { "name": "JavaScript", "bytes": "39146656" }, { "name": "Lua", "bytes": "13768" }, { "name": "Matlab", "bytes": "22373" }, { "name": "Objective-C", "bytes": "21887598" }, { "name": "PHP", "bytes": "2344144" }, { "name": "Perl", "bytes": "49033099" }, { "name": "Prolog", "bytes": "2926122" }, { "name": "Python", "bytes": "39863959" }, { "name": "R", "bytes": "262" }, { "name": "Racket", "bytes": "359" }, { "name": "Ruby", "bytes": "304063" }, { "name": "Scheme", "bytes": "14853" }, { "name": "Shell", "bytes": "9195117" }, { "name": "Tcl", "bytes": "1919771" }, { "name": "Verilog", "bytes": "3092" }, { "name": "Visual Basic", "bytes": "1430" }, { "name": "eC", "bytes": "5079" } ], "symlink_target": "" }
// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __ESP_GATTC_API_H__ #define __ESP_GATTC_API_H__ #include "esp_bt_defs.h" #include "esp_gatt_defs.h" #include "esp_err.h" #ifdef __cplusplus extern "C" { #endif /// GATT Client callback function events typedef enum { ESP_GATTC_REG_EVT = 0, /*!< When GATT client is registered, the event comes */ ESP_GATTC_UNREG_EVT = 1, /*!< When GATT client is unregistered, the event comes */ ESP_GATTC_OPEN_EVT = 2, /*!< When GATT connection is set up, the event comes */ ESP_GATTC_READ_CHAR_EVT = 3, /*!< When GATT characteristic is read, the event comes */ ESP_GATTC_WRITE_CHAR_EVT = 4, /*!< When GATT characteristic write operation completes, the event comes */ ESP_GATTC_CLOSE_EVT = 5, /*!< When GATT connection is closed, the event comes */ ESP_GATTC_SEARCH_CMPL_EVT = 6, /*!< When GATT service discovery is completed, the event comes */ ESP_GATTC_SEARCH_RES_EVT = 7, /*!< When GATT service discovery result is got, the event comes */ ESP_GATTC_READ_DESCR_EVT = 8, /*!< When GATT characteristic descriptor read completes, the event comes */ ESP_GATTC_WRITE_DESCR_EVT = 9, /*!< When GATT characteristic descriptor write completes, the event comes */ ESP_GATTC_NOTIFY_EVT = 10, /*!< When GATT notification or indication arrives, the event comes */ ESP_GATTC_PREP_WRITE_EVT = 11, /*!< When GATT prepare-write operation completes, the event comes */ ESP_GATTC_EXEC_EVT = 12, /*!< When write execution completes, the event comes */ ESP_GATTC_ACL_EVT = 13, /*!< When ACL connection is up, the event comes */ ESP_GATTC_CANCEL_OPEN_EVT = 14, /*!< When GATT client ongoing connection is cancelled, the event comes */ ESP_GATTC_SRVC_CHG_EVT = 15, /*!< When "service changed" occurs, the event comes */ ESP_GATTC_ENC_CMPL_CB_EVT = 17, /*!< When encryption procedure completes, the event comes */ ESP_GATTC_CFG_MTU_EVT = 18, /*!< When configuration of MTU completes, the event comes */ ESP_GATTC_ADV_DATA_EVT = 19, /*!< When advertising of data, the event comes */ ESP_GATTC_MULT_ADV_ENB_EVT = 20, /*!< When multi-advertising is enabled, the event comes */ ESP_GATTC_MULT_ADV_UPD_EVT = 21, /*!< When multi-advertising parameters are updated, the event comes */ ESP_GATTC_MULT_ADV_DATA_EVT = 22, /*!< When multi-advertising data arrives, the event comes */ ESP_GATTC_MULT_ADV_DIS_EVT = 23, /*!< When multi-advertising is disabled, the event comes */ ESP_GATTC_CONGEST_EVT = 24, /*!< When GATT connection congestion comes, the event comes */ ESP_GATTC_BTH_SCAN_ENB_EVT = 25, /*!< When batch scan is enabled, the event comes */ ESP_GATTC_BTH_SCAN_CFG_EVT = 26, /*!< When batch scan storage is configured, the event comes */ ESP_GATTC_BTH_SCAN_RD_EVT = 27, /*!< When Batch scan read event is reported, the event comes */ ESP_GATTC_BTH_SCAN_THR_EVT = 28, /*!< When Batch scan threshold is set, the event comes */ ESP_GATTC_BTH_SCAN_PARAM_EVT = 29, /*!< When Batch scan parameters are set, the event comes */ ESP_GATTC_BTH_SCAN_DIS_EVT = 30, /*!< When Batch scan is disabled, the event comes */ ESP_GATTC_SCAN_FLT_CFG_EVT = 31, /*!< When Scan filter configuration completes, the event comes */ ESP_GATTC_SCAN_FLT_PARAM_EVT = 32, /*!< When Scan filter parameters are set, the event comes */ ESP_GATTC_SCAN_FLT_STATUS_EVT = 33, /*!< When Scan filter status is reported, the event comes */ ESP_GATTC_ADV_VSC_EVT = 34, /*!< When advertising vendor spec content event is reported, the event comes */ ESP_GATTC_GET_CHAR_EVT = 35, /*!< When characteristic is got from GATT server, the event comes */ ESP_GATTC_GET_DESCR_EVT = 36, /*!< When characteristic descriptor is got from GATT server, the event comes */ ESP_GATTC_GET_INCL_SRVC_EVT = 37, /*!< When included service is got from GATT server, the event comes */ ESP_GATTC_REG_FOR_NOTIFY_EVT = 38, /*!< When register for notification of a service completes, the event comes */ ESP_GATTC_UNREG_FOR_NOTIFY_EVT = 39, /*!< When unregister for notification of a service completes, the event comes */ } esp_gattc_cb_event_t; /// Maximum Transmission Unit used in GATT #define ESP_GATT_DEF_BLE_MTU_SIZE 23 /// Maximum Transmission Unit allowed in GATT #define ESP_GATT_MAX_MTU_SIZE 517 /** * @brief Gatt client callback parameters union */ typedef union { /** * @brief ESP_GATTC_REG_EVT */ struct gattc_reg_evt_param { esp_gatt_status_t status; /*!< Operation status */ uint16_t app_id; /*!< Application id which input in register API */ } reg; /*!< Gatt client callback param of ESP_GATTC_REG_EVT */ /** * @brief ESP_GATTC_OPEN_EVT */ struct gattc_open_evt_param { esp_gatt_status_t status; /*!< Operation status */ uint16_t conn_id; /*!< Connection id */ esp_bd_addr_t remote_bda; /*!< Remote bluetooth device address */ uint16_t mtu; /*!< MTU size */ } open; /*!< Gatt client callback param of ESP_GATTC_OPEN_EVT */ /** * @brief ESP_GATTC_CLOSE_EVT */ struct gattc_close_evt_param { esp_gatt_status_t status; /*!< Operation status */ uint16_t conn_id; /*!< Connection id */ esp_bd_addr_t remote_bda; /*!< Remote bluetooth device address */ esp_gatt_conn_reason_t reason; /*!< The reason of gatt connection close */ } close; /*!< Gatt client callback param of ESP_GATTC_CLOSE_EVT */ /** * @brief ESP_GATTC_CFG_MTU_EVT */ struct gattc_cfg_mtu_evt_param { esp_gatt_status_t status; /*!< Operation status */ uint16_t conn_id; /*!< Connection id */ uint16_t mtu; /*!< MTU size */ } cfg_mtu; /*!< Gatt client callback param of ESP_GATTC_CFG_MTU_EVT */ /** * @brief ESP_GATTC_SEARCH_CMPL_EVT */ struct gattc_search_cmpl_evt_param { esp_gatt_status_t status; /*!< Operation status */ uint16_t conn_id; /*!< Connection id */ } search_cmpl; /*!< Gatt client callback param of ESP_GATTC_SEARCH_CMPL_EVT */ /** * @brief ESP_GATTC_SEARCH_RES_EVT */ struct gattc_search_res_evt_param { uint16_t conn_id; /*!< Connection id */ esp_gatt_srvc_id_t srvc_id; /*!< Service id, include service uuid and other information */ } search_res; /*!< Gatt client callback param of ESP_GATTC_SEARCH_RES_EVT */ /** * @brief ESP_GATTC_READ_CHAR_EVT, ESP_GATTC_READ_DESCR_EVT */ struct gattc_read_char_evt_param { esp_gatt_status_t status; /*!< Operation status */ uint16_t conn_id; /*!< Connection id */ esp_gatt_srvc_id_t srvc_id; /*!< Service id, include service uuid and other information */ esp_gatt_id_t char_id; /*!< Characteristic id, include characteristic uuid and other information */ esp_gatt_id_t descr_id; /*!< Descriptor id, include descriptor uuid and other information */ uint8_t *value; /*!< Characteristic value */ uint16_t value_type; /*!< Characteristic value type */ uint16_t value_len; /*!< Characteristic value length */ } read; /*!< Gatt client callback param of ESP_GATTC_READ_CHAR_EVT */ /** * @brief ESP_GATTC_WRITE_CHAR_EVT, ESP_GATTC_PREP_WRITE_EVT, ESP_GATTC_WRITE_DESCR_EVT */ struct gattc_write_evt_param { esp_gatt_status_t status; /*!< Operation status */ uint16_t conn_id; /*!< Connection id */ esp_gatt_srvc_id_t srvc_id; /*!< Service id, include service uuid and other information */ esp_gatt_id_t char_id; /*!< Characteristic id, include characteristic uuid and other information */ esp_gatt_id_t descr_id; /*!< Descriptor id, include descriptor uuid and other information */ } write; /*!< Gatt client callback param of ESP_GATTC_WRITE_DESCR_EVT */ /** * @brief ESP_GATTC_EXEC_EVT */ struct gattc_exec_cmpl_evt_param { esp_gatt_status_t status; /*!< Operation status */ uint16_t conn_id; /*!< Connection id */ } exec_cmpl; /*!< Gatt client callback param of ESP_GATTC_EXEC_EVT */ /** * @brief ESP_GATTC_NOTIFY_EVT */ struct gattc_notify_evt_param { uint16_t conn_id; /*!< Connection id */ esp_bd_addr_t remote_bda; /*!< Remote bluetooth device address */ esp_gatt_srvc_id_t srvc_id; /*!< Service id, include service uuid and other information */ esp_gatt_id_t char_id; /*!< Characteristic id, include characteristic uuid and other information */ esp_gatt_id_t descr_id; /*!< Descriptor id, include descriptor uuid and other information */ uint16_t value_len; /*!< Notify attribute value */ uint8_t *value; /*!< Notify attribute value */ bool is_notify; /*!< True means notify, false means indicate */ } notify; /*!< Gatt client callback param of ESP_GATTC_NOTIFY_EVT */ /** * @brief ESP_GATTC_SRVC_CHG_EVT */ struct gattc_srvc_chg_evt_param { esp_bd_addr_t remote_bda; /*!< Remote bluetooth device address */ } srvc_chg; /*!< Gatt client callback param of ESP_GATTC_SRVC_CHG_EVT */ /** * @brief ESP_GATTC_CONGEST_EVT */ struct gattc_congest_evt_param { uint16_t conn_id; /*!< Connection id */ bool congested; /*!< Congested or not */ } congest; /*!< Gatt client callback param of ESP_GATTC_CONGEST_EVT */ /** * @brief ESP_GATTC_GET_CHAR_EVT */ struct gattc_get_char_evt_param { esp_gatt_status_t status; /*!< Operation status */ uint16_t conn_id; /*!< Connection id */ esp_gatt_srvc_id_t srvc_id; /*!< Service id, include service uuid and other information */ esp_gatt_id_t char_id; /*!< Characteristic id, include characteristic uuid and other information */ esp_gatt_char_prop_t char_prop; /*!< Characteristic property */ } get_char; /*!< Gatt client callback param of ESP_GATTC_GET_CHAR_EVT */ /** * @brief ESP_GATTC_GET_DESCR_EVT */ struct gattc_get_descr_evt_param { esp_gatt_status_t status; /*!< Operation status */ uint16_t conn_id; /*!< Connection id */ esp_gatt_srvc_id_t srvc_id; /*!< Service id, include service uuid and other information */ esp_gatt_id_t char_id; /*!< Characteristic id, include characteristic uuid and other information */ esp_gatt_id_t descr_id; /*!< Descriptor id, include descriptor uuid and other information */ } get_descr; /*!< Gatt client callback param of ESP_GATTC_GET_DESCR_EVT */ /** * @brief ESP_GATTC_GET_INCL_SRVC_EVT */ struct gattc_get_incl_srvc_evt_param { esp_gatt_status_t status; /*!< Operation status */ uint16_t conn_id; /*!< Connection id */ esp_gatt_srvc_id_t srvc_id; /*!< Service id, include service uuid and other information */ esp_gatt_srvc_id_t incl_srvc_id;/*!< Included service id, include service uuid and other information */ } get_incl_srvc; /*!< Gatt client callback param of ESP_GATTC_GET_INCL_SRVC_EVT */ /** * @brief ESP_GATTC_REG_FOR_NOTIFY_EVT */ struct gattc_reg_for_notify_evt_param { esp_gatt_status_t status; /*!< Operation status */ esp_gatt_srvc_id_t srvc_id; /*!< Service id, include service uuid and other information */ esp_gatt_id_t char_id; /*!< Characteristic id, include characteristic uuid and other information */ } reg_for_notify; /*!< Gatt client callback param of ESP_GATTC_REG_FOR_NOTIFY_EVT */ /** * @brief ESP_GATTC_UNREG_FOR_NOTIFY_EVT */ struct gattc_unreg_for_notify_evt_param { esp_gatt_status_t status; /*!< Operation status */ esp_gatt_srvc_id_t srvc_id; /*!< Service id, include service uuid and other information */ esp_gatt_id_t char_id; /*!< Characteristic id, include characteristic uuid and other information */ } unreg_for_notify; /*!< Gatt client callback param of ESP_GATTC_UNREG_FOR_NOTIFY_EVT */ } esp_ble_gattc_cb_param_t; /*!< GATT client callback parameter union type */ /** * @brief GATT Client callback function type * @param event : Event type * @param gatts_if : GATT client access interface, normally * different gattc_if correspond to different profile * @param param : Point to callback parameter, currently is union type */ typedef void (* esp_gattc_cb_t)(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param); /** * @brief This function is called to register application callbacks * with GATTC module. * * @param[in] callback : pointer to the application callback function. * * @return * - ESP_OK: success * - other: failed * */ esp_err_t esp_ble_gattc_register_callback(esp_gattc_cb_t callback); /** * @brief This function is called to register application callbacks * with GATTC module. * * @param[in] app_id : Application Identify (UUID), for different application * * @return * - ESP_OK: success * - other: failed * */ esp_err_t esp_ble_gattc_app_register(uint16_t app_id); /** * @brief This function is called to unregister an application * from GATTC module. * * @param[in] gattc_if: Gatt client access interface. * * @return * - ESP_OK: success * - other: failed * */ esp_err_t esp_ble_gattc_app_unregister(esp_gatt_if_t gattc_if); /** * @brief Open a direct connection or add a background auto connection * * @param[in] gattc_if: Gatt client access interface. * @param[in] remote_bda: remote device bluetooth device address. * @param[in] is_direct: direct connection or background auto connection * * @return * - ESP_OK: success * - other: failed * */ esp_err_t esp_ble_gattc_open(esp_gatt_if_t gattc_if, esp_bd_addr_t remote_bda, bool is_direct); /** * @brief Close a connection to a GATT server. * * @param[in] gattc_if: Gatt client access interface. * @param[in] conn_id: connection ID to be closed. * * @return * - ESP_OK: success * - other: failed * */ esp_err_t esp_ble_gattc_close (esp_gatt_if_t gattc_if, uint16_t conn_id); /** * @brief Configure the MTU size in the GATT channel. This can be done * only once per connection. * * @param[in] gattc_if: Gatt client access interface. * @param[in] conn_id: connection ID. * @param[in] mtu: desired MTU size to use. * * @return * - ESP_OK: success * - other: failed * */ esp_err_t esp_ble_gattc_config_mtu (esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t mtu); /** * @brief This function is called to request a GATT service discovery * on a GATT server. This function report service search result * by a callback event, and followed by a service search complete * event. * * @param[in] gattc_if: Gatt client access interface. * @param[in] conn_id: connection ID. * @param[in] filter_uuid: a UUID of the service application is interested in. * If Null, discover for all services. * * @return * - ESP_OK: success * - other: failed * */ esp_err_t esp_ble_gattc_search_service(esp_gatt_if_t gattc_if, uint16_t conn_id, esp_bt_uuid_t *filter_uuid); /** * @brief This function is called to find the first characteristic of the * service on the given server. * * @param[in] gattc_if: Gatt client access interface. * @param[in] conn_id: connection ID which identify the server. * @param[in] srvc_id: service ID * @param[in] start_char_id: the start characteristic ID * @return * - ESP_OK: success * - other: failed * */ esp_err_t esp_ble_gattc_get_characteristic(esp_gatt_if_t gattc_if, uint16_t conn_id, esp_gatt_srvc_id_t *srvc_id, esp_gatt_id_t *start_char_id); /** * @brief This function is called to find the descriptor of the * service on the given server. * * @param[in] gattc_if: Gatt client access interface. * @param[in] conn_id: connection ID which identify the server. * @param[in] srvc_id: the service ID of which the characteristic is belonged to. * @param[in] char_id: Characteristic ID, if NULL find the first available * characteristic. * @param[in] start_descr_id: the start descriptor id * * @return * - ESP_OK: success * - other: failed * */ esp_err_t esp_ble_gattc_get_descriptor(esp_gatt_if_t gattc_if, uint16_t conn_id, esp_gatt_srvc_id_t *srvc_id, esp_gatt_id_t *char_id, esp_gatt_id_t *start_descr_id); /** * @brief This function is called to find the first characteristic of the * service on the given server. * * @param[in] gattc_if: Gatt client access interface. * @param[in] conn_id: connection ID which identify the server. * @param[in] srvc_id: the service ID of which the characteristic is belonged to. * @param[in] start_incl_srvc_id: the start include service id * * @return * - ESP_OK: success * - other: failed * */ esp_err_t esp_ble_gattc_get_included_service(esp_gatt_if_t gattc_if, uint16_t conn_id, esp_gatt_srvc_id_t *srvc_id, esp_gatt_srvc_id_t *start_incl_srvc_id); /** * @brief This function is called to read a service's characteristics of * the given characteristic ID * * @param[in] gattc_if: Gatt client access interface. * @param[in] conn_id : connection ID. * @param[in] srvc_id : service ID. * @param[in] char_id : characteristic ID to read. * @param[in] auth_req : authenticate request type * * @return * - ESP_OK: success * - other: failed * */ esp_err_t esp_ble_gattc_read_char (esp_gatt_if_t gattc_if, uint16_t conn_id, esp_gatt_srvc_id_t *srvc_id, esp_gatt_id_t *char_id, esp_gatt_auth_req_t auth_req); /** * @brief This function is called to read a characteristics descriptor. * * @param[in] gattc_if: Gatt client access interface. * @param[in] conn_id : connection ID. * @param[in] srvc_id : service ID. * @param[in] char_id : characteristic ID to read. * @param[in] descr_id : characteristic descriptor ID to read. * @param[in] auth_req : authenticate request type * * @return * - ESP_OK: success * - other: failed * */ esp_err_t esp_ble_gattc_read_char_descr (esp_gatt_if_t gattc_if, uint16_t conn_id, esp_gatt_srvc_id_t *srvc_id, esp_gatt_id_t *char_id, esp_gatt_id_t *descr_id, esp_gatt_auth_req_t auth_req); /** * @brief This function is called to write characteristic value. * * @param[in] gattc_if: Gatt client access interface. * @param[in] conn_id : connection ID. * @param[in] srvc_id : service ID. * @param[in] char_id : characteristic ID to write. * @param[in] value_len: length of the value to be written. * @param[in] value : the value to be written. * @param[in] write_type : the type of attribute write operation. * @param[in] auth_req : authentication request. * * @return * - ESP_OK: success * - other: failed * */ esp_err_t esp_ble_gattc_write_char( esp_gatt_if_t gattc_if, uint16_t conn_id, esp_gatt_srvc_id_t *srvc_id, esp_gatt_id_t *char_id, uint16_t value_len, uint8_t *value, esp_gatt_write_type_t write_type, esp_gatt_auth_req_t auth_req); /** * @brief This function is called to write characteristic descriptor value. * * @param[in] gattc_if: Gatt client access interface. * @param[in] conn_id : connection ID * @param[in] srvc_id : service ID. * @param[in] char_id : characteristic ID. * @param[in] descr_id : characteristic descriptor ID to write. * @param[in] value_len: length of the value to be written. * @param[in] value : the value to be written. * @param[in] write_type : the type of attribute write operation. * @param[in] auth_req : authentication request. * * @return * - ESP_OK: success * - other: failed * */ esp_err_t esp_ble_gattc_write_char_descr (esp_gatt_if_t gattc_if, uint16_t conn_id, esp_gatt_srvc_id_t *srvc_id, esp_gatt_id_t *char_id, esp_gatt_id_t *descr_id, uint16_t value_len, uint8_t *value, esp_gatt_write_type_t write_type, esp_gatt_auth_req_t auth_req); /** * @brief This function is called to prepare write a characteristic value. * * @param[in] gattc_if: Gatt client access interface. * @param[in] conn_id : connection ID. * @param[in] srvc_id : service ID. * @param[in] char_id : GATT characteristic ID of the service. * @param[in] offset : offset of the write value. * @param[in] value_len: length of the value to be written. * @param[in] value : the value to be written. * @param[in] auth_req : authentication request. * * @return * - ESP_OK: success * - other: failed * */ esp_err_t esp_ble_gattc_prepare_write(esp_gatt_if_t gattc_if, uint16_t conn_id, esp_gatt_srvc_id_t *srvc_id, esp_gatt_id_t *char_id, uint16_t offset, uint16_t value_len, uint8_t *value, esp_gatt_auth_req_t auth_req); /** * @brief This function is called to execute write a prepare write sequence. * * @param[in] gattc_if: Gatt client access interface. * @param[in] conn_id : connection ID. * @param[in] is_execute : execute or cancel. * * @return * - ESP_OK: success * - other: failed * */ esp_err_t esp_ble_gattc_execute_write (esp_gatt_if_t gattc_if, uint16_t conn_id, bool is_execute); /** * @brief This function is called to register for notification of a service. * * @param[in] gattc_if: Gatt client access interface. * @param[in] server_bda : target GATT server. * @param[in] srvc_id : pointer to GATT service ID. * @param[in] char_id : pointer to GATT characteristic ID. * * @return * - ESP_OK: registration succeeds * - other: failed * */ esp_gatt_status_t esp_ble_gattc_register_for_notify (esp_gatt_if_t gattc_if, esp_bd_addr_t server_bda, esp_gatt_srvc_id_t *srvc_id, esp_gatt_id_t *char_id); /** * @brief This function is called to de-register for notification of a service. * * @param[in] gattc_if: Gatt client access interface. * @param[in] server_bda : target GATT server. * @param[in] srvc_id : pointer to GATT service ID. * @param[in] char_id : pointer to GATT characteristic ID. * * @return * - ESP_OK: unregister succeeds * - other: failed * */ esp_gatt_status_t esp_ble_gattc_unregister_for_notify (esp_gatt_if_t gattc_if, esp_bd_addr_t server_bda, esp_gatt_srvc_id_t *srvc_id, esp_gatt_id_t *char_id); #ifdef __cplusplus } #endif #endif /* __ESP_GATTC_API_H__ */
{ "content_hash": "29e15c343e951b356d17a0400a9cd58d", "timestamp": "", "source": "github", "line_count": 607, "max_line_length": 127, "avg_line_length": 43.69686985172982, "alnum_prop": 0.5631503543960187, "repo_name": "dantonets/Pingzee-ESP32", "id": "b52dabbdaca364b03ac3dcb4c691e7dabdf68de2", "size": "26524", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "components/bt/bluedroid/api/include/esp_gattc_api.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "136041" }, { "name": "Batchfile", "bytes": "1112" }, { "name": "C", "bytes": "21681326" }, { "name": "C++", "bytes": "2966776" }, { "name": "CMake", "bytes": "4504" }, { "name": "Makefile", "bytes": "5513776" }, { "name": "Objective-C", "bytes": "112775" }, { "name": "Python", "bytes": "269839" }, { "name": "Shell", "bytes": "14942" } ], "symlink_target": "" }
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>training</groupId> <artifactId>hadoop-exercises</artifactId> <version>1.0</version> <packaging>jar</packaging> <name>Hadoop Training Exercises</name> <url>http://maven.apache.org</url> <properties> <jar.name>Exercises.jar</jar.name> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <play_area>/home/hadoop/Training/play_area</play_area> <oozie_workflow_dir>${play_area}/oozie/oozie-exercise-workflow</oozie_workflow_dir> <pig_scripts_dir>${play_area}/pig/scripts</pig_scripts_dir> <!-- <local_example_dir>${play_area}/local/</local_example_dir> --> <hadoop_version>2.0.0-cdh4.0.0</hadoop_version> <hbase_version>0.92.1-cdh4.0.0</hbase_version> <pig_version>0.9.2-cdh4.0.0</pig_version> <junit_version>4.8.1</junit_version> <commons_io_version>2.3</commons_io_version> <samples.version>1.0</samples.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit_version}</version> <scope>test</scope> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>${commons_io_version}</version> </dependency> <dependency> <groupId>org.apache.hadoop</groupId> <artifactId>hadoop-common</artifactId> <version>${hadoop_version}</version> </dependency> <dependency> <groupId>org.apache.hadoop</groupId> <artifactId>hadoop-client</artifactId> <version>${hadoop_version}</version> </dependency> <dependency> <groupId>org.apache.hbase</groupId> <artifactId>hbase</artifactId> <version>${hbase_version}</version> </dependency> <dependency> <groupId>org.apache.pig</groupId> <artifactId>pig</artifactId> <version>${pig_version}</version> </dependency> <dependency> <groupId>training</groupId> <artifactId>hadoop-samples</artifactId> <version>${samples.version}</version> </dependency> </dependencies> <repositories> <repository> <id>java.net</id> <url>http://repository.cloudera.com/artifactory/cloudera-repos</url> </repository> </repositories> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.4</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>2.4</version> <executions> <execution> <id>copy</id> <phase>package</phase> <goals> <goal>copy</goal> </goals> <configuration> <artifactItems> <artifactItem> <groupId>${project.groupId}</groupId> <artifactId>${project.artifactId}</artifactId> <version>${project.version}</version> <type>jar</type> <overWrite>true</overWrite> <outputDirectory>${play_area}</outputDirectory> <destFileName>${jar.name}</destFileName> </artifactItem> <artifactItem> <groupId>${project.groupId}</groupId> <artifactId>${project.artifactId}</artifactId> <version>${project.version}</version> <type>jar</type> <overWrite>true</overWrite> <outputDirectory>${oozie_workflow_dir}/lib</outputDirectory> <destFileName>${jar.name}</destFileName> </artifactItem> <artifactItem> <groupId>${project.groupId}</groupId> <artifactId>${project.artifactId}</artifactId> <version>${project.version}</version> <type>jar</type> <overWrite>true</overWrite> <outputDirectory>${pig_scripts_dir}</outputDirectory> <destFileName>${jar.name}</destFileName> </artifactItem> </artifactItems> </configuration> </execution> </executions> </plugin> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>2.5</version> <executions> <execution> <id>copy-resources</id> <phase>package</phase> <goals> <goal>copy-resources</goal> </goals> <configuration> <outputDirectory>${oozie_workflow_dir}</outputDirectory> <resources> <resource> <directory>src/main/resources/oozie/workflows/</directory> </resource> </resources> </configuration> </execution> <execution> <id>copy-pig-scripts</id> <phase>package</phase> <goals> <goal>copy-resources</goal> </goals> <configuration> <outputDirectory>${pig_scripts_dir}</outputDirectory> <resources> <resource> <directory>src/main/resources/pig/</directory> </resource> </resources> </configuration> </execution> <!-- <execution> <id>copy-local-example</id> <phase>package</phase> <goals> <goal>copy-resources</goal> </goals> <configuration> <outputDirectory>${local_example_dir}</outputDirectory> <resources> <resource> <directory>src/main/resources/mr/local</directory> </resource> </resources> </configuration> </execution> --> </executions> </plugin> </plugins> </build> </project>
{ "content_hash": "195531a1facf85dc20e43a3e4355784d", "timestamp": "", "source": "github", "line_count": 203, "max_line_length": 104, "avg_line_length": 28.29064039408867, "alnum_prop": 0.6343374542921818, "repo_name": "gliptak/hadoop-course", "id": "fc1d7cdce725944675e47710935c2415034284f7", "size": "5743", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Exercises/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "5246" }, { "name": "Java", "bytes": "547523" }, { "name": "PigLatin", "bytes": "14723" }, { "name": "Python", "bytes": "1878" }, { "name": "Shell", "bytes": "53003" } ], "symlink_target": "" }
import React from 'react'; import { withRouter, Link } from "react-router-dom"; import { Button, MenuItem, Nav, Navbar, NavItem, NavDropdown, Jumbotron } from 'react-bootstrap'; import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn, } from 'material-ui/Table'; class Header extends React.Component { constructor(props) { super(props); this.state = { selected: [1], } } componentDidMount() { } handleRowSelection(selectedRows) { this.setState({ selected: selectedRows, }); }; render() { // <NavDropdown eventKey={3} title="Gerenciar Corridas" id="basic-nav-dropdown"> // <MenuItem eventKey={3.1}><Link className="drop-down-itens" to="/Passageiros"> // Gerenciar Passageiros</Link></MenuItem> // <MenuItem eventKey={3.1}><Link className="drop-down-itens" to="/Motoristas"> // Gerenciar Motoristas</Link></MenuItem> // <MenuItem eventKey={3.1}><Link className="drop-down-itens" to="/Corridas"> // Gerenciar Corridas</Link></MenuItem> // <img src={require('../Images/caricon.png')} width="40px" height="40px" /> // <Navbar collapseOnSelect={true}> // <Navbar.Header> // <Navbar.Brand> // <Link to="/"> // Início // </Link> // </Navbar.Brand> // </Navbar.Header> // <Nav> // <NavItem eventKey={1}> // <Link className="drop-down-itens" to="/Passageiros"> // Gerenciar Passageiros</Link> // </NavItem> // <NavItem eventKey={1}> // <Link className="drop-down-itens" to="/Motoristas"> // Gerenciar Motoristas</Link> // </NavItem> // <NavItem eventKey={1}> // <Link className="drop-down-itens" to="/Corridas"> // Gerenciar Corridas</Link> // </NavItem> // </Nav> // </Navbar> // </NavDropdown> return ( <div> <nav className="navbar navbar-default"> <div className="container"> <div className="navbar-header"> <Link className="navbar-brand" to="/"> Início </Link> </div> <div className="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul className="nav navbar-nav"> <li> <Link className="drop-down-itens" to="/Passageiros"> Gerenciar Passageiros</Link> </li> <li><Link className="drop-down-itens" to="/Motoristas"> Gerenciar Motoristas </Link> </li> <li> <Link className="drop-down-itens" to="/Corridas"> Gerenciar Corridas </Link> </li> </ul> <ul className="nav navbar-nav navbar-right"> <li><Link className="drop-down-itens" to="/Sobre">Sobre o Autor</Link></li> </ul> </div> </div> </nav> </div> ) } } export default Header;
{ "content_hash": "30381af2504f57bd7be9d832b7b607f5", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 113, "avg_line_length": 36.60747663551402, "alnum_prop": 0.41639009446004593, "repo_name": "pedrobertao/CorridaGeneciadorBertao", "id": "cc66df59f28fc5dcccb8e8c5a6eb8b3d46040d16", "size": "3919", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/ComponentsFixed/Header.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1997" }, { "name": "HTML", "bytes": "752" }, { "name": "JavaScript", "bytes": "3764021" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <geo:GeodesyML gml:id="MAC100AUS" xmlns:gco="http://www.isotc211.org/2005/gco" xmlns:geo="urn:xml-gov-au:icsm:egeodesy:0.5" xmlns:gmd="http://www.isotc211.org/2005/gmd" xmlns:gml="http://www.opengis.net/gml/3.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <geo:siteLog gml:id="mac1_20161221.log"> <geo:formInformation> <geo:FormInformation gml:id="form-information"> <geo:preparedBy>Ted Zhou</geo:preparedBy> <geo:datePrepared>2016-12-21</geo:datePrepared> <geo:reportType>UPDATE</geo:reportType> </geo:FormInformation> </geo:formInformation> <geo:siteIdentification> <geo:SiteIdentification gml:id="site-identification"> <geo:siteName>Macquarie Island</geo:siteName> <geo:fourCharacterID>MAC1</geo:fourCharacterID> <geo:monumentInscription>AUS211</geo:monumentInscription> <geo:iersDOMESNumber>50135M001</geo:iersDOMESNumber> <geo:cdpNumber>NONE</geo:cdpNumber> <geo:monumentDescription codeSpace="urn:ga-gov-au:monument-description-type">PILLAR</geo:monumentDescription> <geo:monumentFoundation>CONCRETE BLOCK</geo:monumentFoundation> <geo:markerDescription></geo:markerDescription> <geo:dateInstalled>1995-06-27T00:00:00Z</geo:dateInstalled> <geo:geologicCharacteristic codeSpace="urn:ga-gov-au:geologic-characteristic-type">CONGLOMERATE</geo:geologicCharacteristic> <geo:bedrockType>SEDIMENTARY</geo:bedrockType> <geo:bedrockCondition>WEATHERED</geo:bedrockCondition> <geo:fractureSpacing></geo:fractureSpacing> <geo:faultZonesNearby codeSpace="urn:ga-gov-au:fault-zones-type"></geo:faultZonesNearby> <geo:notes>ARGN (Australian Regional GPS Network)</geo:notes> </geo:SiteIdentification> </geo:siteIdentification> <geo:siteLocation> <geo:SiteLocation gml:id="site-location"> <geo:city>Macquarie Island</geo:city> <geo:state>Tasmania</geo:state> <geo:countryCodeISO codeList="http://xml.gov.au/icsm/geodesyml/codelists/country-codes-codelist.xml#GeodesyML_CountryCode" codeListValue="Australia" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.5">AUS</geo:countryCodeISO> <geo:tectonicPlate codeSpace="urn:ga-gov-au:plate-type">AUSTRALIAN/PACIFIC</geo:tectonicPlate> <geo:approximatePositionITRF> <geo:cartesianPosition> <gml:Point gml:id="itrf_cartesian" srsName="EPSG:7789"> <gml:pos>-3464038.4875 1334172.7432 -5169224.4229</gml:pos> </gml:Point> </geo:cartesianPosition> <geo:geodeticPosition> <gml:Point gml:id="itrf_geodetic" srsName="EPSG:7912"> <gml:pos>-54.4995 158.9358 -6.69</gml:pos> </gml:Point> </geo:geodeticPosition> </geo:approximatePositionITRF> <geo:notes>The site is situated on the Macquaire Ridge between the Austrlaian and Pacific plates.</geo:notes> </geo:SiteLocation> </geo:siteLocation> <geo:gnssReceiver> <geo:GnssReceiver gml:id="gnss-receiver-1"> <geo:manufacturerSerialNumber>C 125</geo:manufacturerSerialNumber> <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSReceiverTypeCode" codeListValue="AOA ICS-4000Z" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.5">AOA ICS-4000Z</geo:igsModelCode> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GPS</geo:satelliteSystem> <geo:firmwareVersion>3.2.33.1</geo:firmwareVersion> <geo:elevationCutoffSetting>0.0</geo:elevationCutoffSetting> <geo:dateInstalled>1995-06-27T00:00:00Z</geo:dateInstalled> <geo:dateRemoved>1999-08-26T00:00:00Z</geo:dateRemoved> <geo:temperatureStabilization xsi:nil="true"></geo:temperatureStabilization> </geo:GnssReceiver> <geo:dateInserted>1995-06-27T00:00:00Z</geo:dateInserted> </geo:gnssReceiver> <geo:gnssReceiver> <geo:GnssReceiver gml:id="gnss-receiver-2"> <geo:manufacturerSerialNumber>4278</geo:manufacturerSerialNumber> <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSReceiverTypeCode" codeListValue="ASHTECH Z-XII3" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.5">ASHTECH Z-XII3</geo:igsModelCode> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GPS</geo:satelliteSystem> <geo:firmwareVersion>1F60</geo:firmwareVersion> <geo:elevationCutoffSetting>0.0</geo:elevationCutoffSetting> <geo:dateInstalled>1999-08-26T00:00:00Z</geo:dateInstalled> <geo:dateRemoved>1999-12-20T03:30:00Z</geo:dateRemoved> <geo:temperatureStabilization xsi:nil="true"></geo:temperatureStabilization> </geo:GnssReceiver> <geo:dateInserted>1999-08-26T00:00:00Z</geo:dateInserted> </geo:gnssReceiver> <geo:gnssReceiver> <geo:GnssReceiver gml:id="gnss-receiver-3"> <geo:manufacturerSerialNumber>3358</geo:manufacturerSerialNumber> <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSReceiverTypeCode" codeListValue="ASHTECH Z-XII3" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.5">ASHTECH Z-XII3</geo:igsModelCode> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GPS</geo:satelliteSystem> <geo:firmwareVersion>CD00</geo:firmwareVersion> <geo:elevationCutoffSetting>0.0</geo:elevationCutoffSetting> <geo:dateInstalled>1999-12-20T10:30:00Z</geo:dateInstalled> <geo:dateRemoved>2001-01-04T00:00:00Z</geo:dateRemoved> <geo:temperatureStabilization xsi:nil="true"></geo:temperatureStabilization> </geo:GnssReceiver> <geo:dateInserted>1999-12-20T10:30:00Z</geo:dateInserted> </geo:gnssReceiver> <geo:gnssReceiver> <geo:GnssReceiver gml:id="gnss-receiver-4"> <geo:notes>Ashtech Z-X113 s/n 3358 ver CD00</geo:notes> <geo:manufacturerSerialNumber>C133U</geo:manufacturerSerialNumber> <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSReceiverTypeCode" codeListValue="AOA ICS-4000Z ACT" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.5">AOA ICS-4000Z ACT</geo:igsModelCode> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GPS</geo:satelliteSystem> <geo:firmwareVersion>3.3.32.4</geo:firmwareVersion> <geo:elevationCutoffSetting>0.0</geo:elevationCutoffSetting> <geo:dateInstalled>2001-01-04T00:00:00Z</geo:dateInstalled> <geo:dateRemoved>2002-03-13T00:00:00Z</geo:dateRemoved> <geo:temperatureStabilization xsi:nil="true"></geo:temperatureStabilization> </geo:GnssReceiver> <geo:dateInserted>2001-01-04T00:00:00Z</geo:dateInserted> </geo:gnssReceiver> <geo:gnssReceiver> <geo:GnssReceiver gml:id="gnss-receiver-5"> <geo:notes>Ashtech Z-X113 s/n 3358 ver CD00</geo:notes> <geo:manufacturerSerialNumber>C133U</geo:manufacturerSerialNumber> <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSReceiverTypeCode" codeListValue="AOA ICS-4000Z ACT" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.5">AOA ICS-4000Z ACT</geo:igsModelCode> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GPS</geo:satelliteSystem> <geo:firmwareVersion>3.3.32.3</geo:firmwareVersion> <geo:elevationCutoffSetting>0.0</geo:elevationCutoffSetting> <geo:dateInstalled>2002-03-13T00:00:00Z</geo:dateInstalled> <geo:dateRemoved>2005-04-21T23:59:00Z</geo:dateRemoved> <geo:temperatureStabilization xsi:nil="true"></geo:temperatureStabilization> </geo:GnssReceiver> <geo:dateInserted>2002-03-13T00:00:00Z</geo:dateInserted> </geo:gnssReceiver> <geo:gnssReceiver> <geo:GnssReceiver gml:id="gnss-receiver-6"> <geo:manufacturerSerialNumber>3358</geo:manufacturerSerialNumber> <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSReceiverTypeCode" codeListValue="ASHTECH Z-XII3" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.5">ASHTECH Z-XII3</geo:igsModelCode> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GPS</geo:satelliteSystem> <geo:firmwareVersion>CD00</geo:firmwareVersion> <geo:elevationCutoffSetting>0.0</geo:elevationCutoffSetting> <geo:dateInstalled>2005-04-22T00:00:00Z</geo:dateInstalled> <geo:dateRemoved>2006-04-04T23:59:00Z</geo:dateRemoved> <geo:temperatureStabilization xsi:nil="true"></geo:temperatureStabilization> </geo:GnssReceiver> <geo:dateInserted>2005-04-22T00:00:00Z</geo:dateInserted> </geo:gnssReceiver> <geo:gnssReceiver> <geo:GnssReceiver gml:id="gnss-receiver-7"> <geo:manufacturerSerialNumber>24007</geo:manufacturerSerialNumber> <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSReceiverTypeCode" codeListValue="ASHTECH UZ-12" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.5">ASHTECH UZ-12</geo:igsModelCode> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GPS</geo:satelliteSystem> <geo:firmwareVersion>CQ00</geo:firmwareVersion> <geo:elevationCutoffSetting>0.0</geo:elevationCutoffSetting> <geo:dateInstalled>2006-04-05T00:00:00Z</geo:dateInstalled> <geo:dateRemoved>2009-03-19T23:59:00Z</geo:dateRemoved> <geo:temperatureStabilization xsi:nil="true"></geo:temperatureStabilization> </geo:GnssReceiver> <geo:dateInserted>2006-04-05T00:00:00Z</geo:dateInserted> </geo:gnssReceiver> <geo:gnssReceiver> <geo:GnssReceiver gml:id="gnss-receiver-8"> <geo:notes>This receiver was withdrawn due to tracking problems.</geo:notes> <geo:manufacturerSerialNumber>4828K57163</geo:manufacturerSerialNumber> <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSReceiverTypeCode" codeListValue="TRIMBLE NETR5" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.5">TRIMBLE NETR5</geo:igsModelCode> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GPS</geo:satelliteSystem> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GLO</geo:satelliteSystem> <geo:firmwareVersion>3.60</geo:firmwareVersion> <geo:elevationCutoffSetting>0.0</geo:elevationCutoffSetting> <geo:dateInstalled>2009-03-20T00:00:00Z</geo:dateInstalled> <geo:dateRemoved>2009-05-25T00:00:00Z</geo:dateRemoved> <geo:temperatureStabilization xsi:nil="true"></geo:temperatureStabilization> </geo:GnssReceiver> <geo:dateInserted>2009-03-20T00:00:00Z</geo:dateInserted> </geo:gnssReceiver> <geo:gnssReceiver> <geo:GnssReceiver gml:id="gnss-receiver-9"> <geo:manufacturerSerialNumber>UC2200524007</geo:manufacturerSerialNumber> <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSReceiverTypeCode" codeListValue="ASHTECH UZ-12" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.5">ASHTECH UZ-12</geo:igsModelCode> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GPS</geo:satelliteSystem> <geo:firmwareVersion>CQ00</geo:firmwareVersion> <geo:elevationCutoffSetting>0.0</geo:elevationCutoffSetting> <geo:dateInstalled>2009-05-25T00:00:00Z</geo:dateInstalled> <geo:dateRemoved>2011-04-23T23:59:00Z</geo:dateRemoved> <geo:temperatureStabilization xsi:nil="true"></geo:temperatureStabilization> </geo:GnssReceiver> <geo:dateInserted>2009-05-25T00:00:00Z</geo:dateInserted> </geo:gnssReceiver> <geo:gnssReceiver> <geo:GnssReceiver gml:id="gnss-receiver-10"> <geo:manufacturerSerialNumber>495588</geo:manufacturerSerialNumber> <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSReceiverTypeCode" codeListValue="LEICA GRX1200+GNSS" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.5">LEICA GRX1200+GNSS</geo:igsModelCode> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GPS</geo:satelliteSystem> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GLO</geo:satelliteSystem> <geo:firmwareVersion>8.10</geo:firmwareVersion> <geo:elevationCutoffSetting>0.0</geo:elevationCutoffSetting> <geo:dateInstalled>2011-04-24T00:00:00Z</geo:dateInstalled> <geo:dateRemoved>2012-11-07T04:00:00Z</geo:dateRemoved> <geo:temperatureStabilization xsi:nil="true"></geo:temperatureStabilization> </geo:GnssReceiver> <geo:dateInserted>2011-04-24T00:00:00Z</geo:dateInserted> </geo:gnssReceiver> <geo:gnssReceiver> <geo:GnssReceiver gml:id="gnss-receiver-11"> <geo:manufacturerSerialNumber>495588</geo:manufacturerSerialNumber> <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSReceiverTypeCode" codeListValue="LEICA GRX1200+GNSS" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.5">LEICA GRX1200+GNSS</geo:igsModelCode> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GPS</geo:satelliteSystem> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GLO</geo:satelliteSystem> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GAL</geo:satelliteSystem> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">SBAS</geo:satelliteSystem> <geo:firmwareVersion>8.51/6.111</geo:firmwareVersion> <geo:elevationCutoffSetting>0.0</geo:elevationCutoffSetting> <geo:dateInstalled>2012-11-07T04:00:00Z</geo:dateInstalled> <geo:dateRemoved>2015-06-12T00:00:00Z</geo:dateRemoved> <geo:temperatureStabilization xsi:nil="true"></geo:temperatureStabilization> </geo:GnssReceiver> <geo:dateInserted>2012-11-07T04:00:00Z</geo:dateInserted> </geo:gnssReceiver> <geo:gnssReceiver> <geo:GnssReceiver gml:id="gnss-receiver-12"> <geo:manufacturerSerialNumber>495588</geo:manufacturerSerialNumber> <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSReceiverTypeCode" codeListValue="LEICA GRX1200+GNSS" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.5">LEICA GRX1200+GNSS</geo:igsModelCode> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GPS</geo:satelliteSystem> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GLO</geo:satelliteSystem> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GAL</geo:satelliteSystem> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">SBAS</geo:satelliteSystem> <geo:firmwareVersion>9.20/6.404</geo:firmwareVersion> <geo:elevationCutoffSetting>0.0</geo:elevationCutoffSetting> <geo:dateInstalled>2015-06-12T00:00:00Z</geo:dateInstalled> <geo:dateRemoved>2016-11-29T04:00:00Z</geo:dateRemoved> <geo:temperatureStabilization xsi:nil="true"></geo:temperatureStabilization> </geo:GnssReceiver> <geo:dateInserted>2015-06-12T00:00:00Z</geo:dateInserted> </geo:gnssReceiver> <geo:gnssReceiver> <geo:GnssReceiver gml:id="gnss-receiver-13"> <geo:manufacturerSerialNumber>3012260</geo:manufacturerSerialNumber> <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSReceiverTypeCode" codeListValue="SEPT POLARX5" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.5">SEPT POLARX5</geo:igsModelCode> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GPS</geo:satelliteSystem> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GLO</geo:satelliteSystem> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GAL</geo:satelliteSystem> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">BDS</geo:satelliteSystem> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">QZSS</geo:satelliteSystem> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">IRNSS</geo:satelliteSystem> <geo:firmwareVersion>5.0.2</geo:firmwareVersion> <geo:elevationCutoffSetting>0.0</geo:elevationCutoffSetting> <geo:dateInstalled>2016-11-29T04:00:00Z</geo:dateInstalled> <geo:dateRemoved>2016-12-21T00:00:00Z</geo:dateRemoved> <geo:temperatureStabilization xsi:nil="true"></geo:temperatureStabilization> </geo:GnssReceiver> <geo:dateInserted>2016-11-29T04:00:00Z</geo:dateInserted> </geo:gnssReceiver> <geo:gnssReceiver> <geo:GnssReceiver gml:id="gnss-receiver-14"> <geo:notes>Firmware upgrade only</geo:notes> <geo:manufacturerSerialNumber>3012260</geo:manufacturerSerialNumber> <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSReceiverTypeCode" codeListValue="SEPT POLARX5" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.5">SEPT POLARX5</geo:igsModelCode> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GPS</geo:satelliteSystem> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GLO</geo:satelliteSystem> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GAL</geo:satelliteSystem> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">BDS</geo:satelliteSystem> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">QZSS</geo:satelliteSystem> <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">IRNSS</geo:satelliteSystem> <geo:firmwareVersion>5.10</geo:firmwareVersion> <geo:elevationCutoffSetting>0.0</geo:elevationCutoffSetting> <geo:dateInstalled>2016-12-21T00:00:00Z</geo:dateInstalled> <geo:dateRemoved></geo:dateRemoved> <geo:temperatureStabilization xsi:nil="true"></geo:temperatureStabilization> </geo:GnssReceiver> <geo:dateInserted>2016-12-21T00:00:00Z</geo:dateInserted> </geo:gnssReceiver> <geo:gnssAntenna> <geo:GnssAntenna gml:id="gnss-antenna-1"> <geo:notes>Incorrect serial number corrected 2015-10-27</geo:notes> <geo:manufacturerSerialNumber>520</geo:manufacturerSerialNumber> <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSAntennaTypeCode" codeListValue="AOAD/M_T AUST" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.5">AOAD/M_T AUST</geo:igsModelCode> <geo:antennaReferencePoint codeSpace="urn:ga-gov-au:antenna-reference-point-type">BPA</geo:antennaReferencePoint> <geo:marker-arpUpEcc.>0.028</geo:marker-arpUpEcc.> <geo:marker-arpNorthEcc.>0.0</geo:marker-arpNorthEcc.> <geo:marker-arpEastEcc.>0.0</geo:marker-arpEastEcc.> <geo:alignmentFromTrueNorth>0.0</geo:alignmentFromTrueNorth> <geo:antennaRadomeType codeSpace="urn:igs-org:gnss-radome-model-code">AUST</geo:antennaRadomeType> <geo:radomeSerialNumber></geo:radomeSerialNumber> <geo:antennaCableType></geo:antennaCableType> <geo:antennaCableLength xsi:nil="true"></geo:antennaCableLength> <geo:dateInstalled>1996-01-09T00:00:00Z</geo:dateInstalled> <geo:dateRemoved>2016-11-29T04:00:00Z</geo:dateRemoved> </geo:GnssAntenna> <geo:dateInserted>1996-01-09T00:00:00Z</geo:dateInserted> </geo:gnssAntenna> <geo:gnssAntenna> <geo:GnssAntenna gml:id="gnss-antenna-2"> <geo:manufacturerSerialNumber>01514</geo:manufacturerSerialNumber> <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSAntennaTypeCode" codeListValue="JAVRINGANT_DM SCIS" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.5">JAVRINGANT_DM SCIS</geo:igsModelCode> <geo:antennaReferencePoint codeSpace="urn:ga-gov-au:antenna-reference-point-type">BPA</geo:antennaReferencePoint> <geo:marker-arpUpEcc.>0.053</geo:marker-arpUpEcc.> <geo:marker-arpNorthEcc.>0.0</geo:marker-arpNorthEcc.> <geo:marker-arpEastEcc.>0.0</geo:marker-arpEastEcc.> <geo:alignmentFromTrueNorth>0.0</geo:alignmentFromTrueNorth> <geo:antennaRadomeType codeSpace="urn:igs-org:gnss-radome-model-code">SCIS</geo:antennaRadomeType> <geo:radomeSerialNumber></geo:radomeSerialNumber> <geo:antennaCableType></geo:antennaCableType> <geo:antennaCableLength xsi:nil="true"></geo:antennaCableLength> <geo:dateInstalled>2016-11-29T04:00:00Z</geo:dateInstalled> <geo:dateRemoved></geo:dateRemoved> </geo:GnssAntenna> <geo:dateInserted>2016-11-29T04:00:00Z</geo:dateInserted> </geo:gnssAntenna> <geo:frequencyStandard> <geo:FrequencyStandard gml:id="frequency-standard-1"> <geo:standardType codeSpace="urn:ga-gov-au:frequency-standard-type">INTERNAL</geo:standardType> <geo:inputFrequency xsi:nil="true"></geo:inputFrequency> <gml:validTime> <gml:TimePeriod gml:id="frequency-standard-1--time-period-1"> <gml:beginPosition>1995-06-27</gml:beginPosition> <gml:endPosition></gml:endPosition> </gml:TimePeriod> </gml:validTime> <geo:notes></geo:notes> </geo:FrequencyStandard> <geo:dateInserted>1995-06-27</geo:dateInserted> </geo:frequencyStandard> <geo:siteContact gml:id="agency-1"> <gmd:MD_SecurityConstraints> <gmd:classification gco:nilReason="missing"/> </gmd:MD_SecurityConstraints> <gmd:CI_ResponsibleParty> <gmd:individualName> <gco:CharacterString>Ryan Ruddick</gco:CharacterString> </gmd:individualName> <gmd:organisationName> <gco:CharacterString>Geoscience Australia</gco:CharacterString> </gmd:organisationName> <gmd:contactInfo> <gmd:CI_Contact> <gmd:phone> <gmd:CI_Telephone> <gmd:voice> <gco:CharacterString>+61 2 6249 9426</gco:CharacterString> </gmd:voice> <gmd:voice> <gco:CharacterString>+61 2 6249 9111</gco:CharacterString> </gmd:voice> <gmd:facsimile> <gco:CharacterString></gco:CharacterString> </gmd:facsimile> </gmd:CI_Telephone> </gmd:phone> <gmd:address> <gmd:CI_Address> <gmd:deliveryPoint> <gco:CharacterString>GPO Box 378 Canberra ACT 2601 AUSTRALIA</gco:CharacterString> </gmd:deliveryPoint> <gmd:city> <gco:CharacterString>Canberra</gco:CharacterString> </gmd:city> <gmd:postalCode> <gco:CharacterString>2601</gco:CharacterString> </gmd:postalCode> <gmd:country> <gco:CharacterString>Australia</gco:CharacterString> </gmd:country> <gmd:electronicMailAddress> <gco:CharacterString>geodesy@ga.gov.au</gco:CharacterString> </gmd:electronicMailAddress> </gmd:CI_Address> </gmd:address> </gmd:CI_Contact> </gmd:contactInfo> <gmd:role> <gmd:CI_RoleCode codeList="http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#CI_RoleCode" codeListValue="pointOfContact"></gmd:CI_RoleCode> </gmd:role> </gmd:CI_ResponsibleParty> </geo:siteContact> <geo:siteContact gml:id="agency-2"> <gmd:MD_SecurityConstraints> <gmd:classification gco:nilReason="missing"/> </gmd:MD_SecurityConstraints> <gmd:CI_ResponsibleParty> <gmd:individualName> <gco:CharacterString>Nicholas Brown</gco:CharacterString> </gmd:individualName> <gmd:organisationName> <gco:CharacterString>Geoscience Australia</gco:CharacterString> </gmd:organisationName> <gmd:contactInfo> <gmd:CI_Contact> <gmd:phone> <gmd:CI_Telephone> <gmd:voice> <gco:CharacterString>+61 2 6249 9831</gco:CharacterString> </gmd:voice> <gmd:voice> <gco:CharacterString>+61 2 6249 9111</gco:CharacterString> </gmd:voice> <gmd:facsimile> <gco:CharacterString></gco:CharacterString> </gmd:facsimile> </gmd:CI_Telephone> </gmd:phone> <gmd:address> <gmd:CI_Address> <gmd:deliveryPoint> <gco:CharacterString>GPO Box 378 Canberra ACT 2601 AUSTRALIA</gco:CharacterString> </gmd:deliveryPoint> <gmd:city> <gco:CharacterString>Canberra</gco:CharacterString> </gmd:city> <gmd:postalCode> <gco:CharacterString>2601</gco:CharacterString> </gmd:postalCode> <gmd:country> <gco:CharacterString>Australia</gco:CharacterString> </gmd:country> <gmd:electronicMailAddress> <gco:CharacterString>geodesy@ga.gov.au</gco:CharacterString> </gmd:electronicMailAddress> </gmd:CI_Address> </gmd:address> </gmd:CI_Contact> </gmd:contactInfo> <gmd:role> <gmd:CI_RoleCode codeList="http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#CI_RoleCode" codeListValue="pointOfContact"></gmd:CI_RoleCode> </gmd:role> </gmd:CI_ResponsibleParty> </geo:siteContact> <geo:siteMetadataCustodian gml:id="agency-3"> <gmd:MD_SecurityConstraints> <gmd:classification gco:nilReason="missing"/> </gmd:MD_SecurityConstraints> <gmd:CI_ResponsibleParty> <gmd:individualName> <gco:CharacterString>Ryan Ruddick</gco:CharacterString> </gmd:individualName> <gmd:organisationName> <gco:CharacterString>Geoscience Australia</gco:CharacterString> </gmd:organisationName> <gmd:contactInfo> <gmd:CI_Contact> <gmd:phone> <gmd:CI_Telephone> <gmd:voice> <gco:CharacterString>+61 2 6249 9426</gco:CharacterString> </gmd:voice> <gmd:voice> <gco:CharacterString>+61 2 6249 9111</gco:CharacterString> </gmd:voice> <gmd:facsimile> <gco:CharacterString></gco:CharacterString> </gmd:facsimile> </gmd:CI_Telephone> </gmd:phone> <gmd:address> <gmd:CI_Address> <gmd:deliveryPoint> <gco:CharacterString>GPO Box 378 Canberra ACT 2601 AUSTRALIA</gco:CharacterString> </gmd:deliveryPoint> <gmd:city> <gco:CharacterString>Canberra</gco:CharacterString> </gmd:city> <gmd:postalCode> <gco:CharacterString>2601</gco:CharacterString> </gmd:postalCode> <gmd:country> <gco:CharacterString>Australia</gco:CharacterString> </gmd:country> <gmd:electronicMailAddress> <gco:CharacterString>geodesy@ga.gov.au</gco:CharacterString> </gmd:electronicMailAddress> </gmd:CI_Address> </gmd:address> </gmd:CI_Contact> </gmd:contactInfo> <gmd:role> <gmd:CI_RoleCode codeList="http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#CI_RoleCode" codeListValue="pointOfContact"></gmd:CI_RoleCode> </gmd:role> </gmd:CI_ResponsibleParty> </geo:siteMetadataCustodian> <geo:moreInformation> <geo:MoreInformation gml:id="more-information"> <geo:dataCenter>GA</geo:dataCenter> <geo:dataCenter>CDDIS</geo:dataCenter> <geo:urlForMoreInformation>http://www.ga.gov.au</geo:urlForMoreInformation> <geo:siteMap>Y</geo:siteMap> <geo:siteDiagram>Y</geo:siteDiagram> <geo:horizonMask>Y</geo:horizonMask> <geo:monumentDescription>Y</geo:monumentDescription> <geo:sitePictures>Y</geo:sitePictures> <geo:notes></geo:notes> <geo:antennaGraphicsWithDimensions></geo:antennaGraphicsWithDimensions> <geo:insertTextGraphicFromAntenna></geo:insertTextGraphicFromAntenna> <geo:DOI codeSpace="urn:ga-gov-au:self.moreInformation-type">TODO</geo:DOI> </geo:MoreInformation> </geo:moreInformation> </geo:siteLog> </geo:GeodesyML>
{ "content_hash": "d1bae0ec2eff9804da1c4c378921983c", "timestamp": "", "source": "github", "line_count": 479, "max_line_length": 268, "avg_line_length": 69.95824634655533, "alnum_prop": 0.6018203521336914, "repo_name": "GeoscienceAustralia/Geodesy-Web-Services", "id": "74f7fcb92f2cfbac07e511f4c4f67a70560f54d4", "size": "33510", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gws-system-test/src/main/resources/sitelogs/2017-06-29/geodesyml/mac1_20161221.xml", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "11736" }, { "name": "Dockerfile", "bytes": "3160" }, { "name": "Groovy", "bytes": "10989" }, { "name": "HTML", "bytes": "22789" }, { "name": "Haskell", "bytes": "1029" }, { "name": "Java", "bytes": "717432" }, { "name": "Makefile", "bytes": "400" }, { "name": "Nix", "bytes": "1500" }, { "name": "Python", "bytes": "426289" }, { "name": "Scheme", "bytes": "99608" }, { "name": "Shell", "bytes": "85078" }, { "name": "TSQL", "bytes": "327764" } ], "symlink_target": "" }
var passport = require('passport'), LocalStrategy = require('passport-local').Strategy, User = require('mongoose').model('User'); module.exports = function() { passport.use(new LocalStrategy(function(username, password, done) { User.findOne({ username: username, function(err, user) { if (err) return done(err); if (!user) return done(null, false, {message: 'Unknown user'}); if (!user.authenticate(password)) return done(null, false, {message: 'Unknown user'}); return done(null, user); } }); })); };
{ "content_hash": "fa4fe4293d93c8650851a848f695eca3", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 102, "avg_line_length": 37.529411764705884, "alnum_prop": 0.5564263322884012, "repo_name": "AbdullahAlger/macro-fitness-tracker", "id": "9410484ff45f44983b2d2297e994c0f5f62ba399", "size": "638", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/strategies/local.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "20027" }, { "name": "HTML", "bytes": "13722" }, { "name": "JavaScript", "bytes": "14384" } ], "symlink_target": "" }
package fr.imie; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class Serialiser implements ISerialiser { /* (non-Javadoc) * @see org.imie.testTDDTennis.ISerialiser#persist(org.imie.testTDDTennis.Jeux) */ @Override public void persist(Jeu jeu) { ObjectOutputStream oos = null; FileOutputStream fichier; try { fichier = new FileOutputStream("jeux.ser"); oos = new ObjectOutputStream(fichier); oos.writeObject(jeu); oos.flush(); oos.close(); } catch (IOException e) { try { oos.close(); } catch (IOException e1) { throw new RuntimeException(e1); } throw new RuntimeException(e); } } /* (non-Javadoc) * @see org.imie.testTDDTennis.ISerialiser#read() */ @Override public Jeu read() { ObjectInputStream ois = null; FileInputStream fichier; Jeu retour; try { fichier = new FileInputStream("jeux.ser"); ois = new ObjectInputStream(fichier); retour = (Jeu) ois.readObject(); ois.close(); } catch (IOException | ClassNotFoundException e) { try { ois.close(); } catch (IOException e1) { throw new RuntimeException(e1); } throw new RuntimeException(e); } return retour; } }
{ "content_hash": "d3348b88948dd9045d0f3d75a5a53e49", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 80, "avg_line_length": 22.033898305084747, "alnum_prop": 0.686923076923077, "repo_name": "imie-source/CDPN-N-05-SHARE", "id": "51c97bffbf43d089575cdcd3a63d85db03f3b758", "size": "1300", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tests/testTennisRule/TennisRule/src/main/java/fr/imie/Serialiser.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "29826" } ], "symlink_target": "" }
/** * @TODO: add this to OHIF's Viewers */ import { Template } from 'meteor/templating'; import { $ } from 'meteor/jquery'; import { toolManager } from '../../../lib/toolManager'; import { viewportUtils } from '../../../lib/viewportUtils'; Template.textMarkerDialogs.events({ 'change #startFrom'(e) { const config = cornerstoneTools.textMarker.getConfiguration(); config.current = $(e.target).val(); //console.log("Changed starting point to: " + config.current); }, 'change #ascending'(e) { const config = cornerstoneTools.textMarker.getConfiguration(); config.ascending = $(e.target).is(':checked'); const currentIndex = config.markers.indexOf(config.current); config.current = config.markers[currentIndex]; const nextMarker = config.current; $('#startFrom').val(nextMarker).trigger('change'); //console.log("Changed ascending to: " + config.ascending); }, 'click #clearLabels'() { const element = viewportUtils.getActiveViewportElement(); const toolType = 'textMarker'; const toolStateManager = cornerstoneTools.globalImageIdSpecificToolStateManager; const toolState = toolStateManager.toolState; // We might want to make this a convenience function in cornerstoneTools const stack = cornerstoneTools.getToolState(element, 'stack'); if (stack && stack.data.length && stack.data[0].imageIds.length) { const imageIds = stack.data[0].imageIds; // Clear the tool data for each image in the stack imageIds.forEach( imageId => { if(toolState.hasOwnProperty(imageId)) { const toolData = toolState[imageId]; if (toolData.hasOwnProperty(toolType)) { delete toolData[toolType]; } } }); } cornerstone.updateImage(element); }, 'click .closeTextMarkerDialogs'() { const defaultTool = toolManager.getDefaultTool(); toolManager.setActiveTool(defaultTool); document.getElementById('textMarkerOptionsDialog').close(); $('#spine').removeClass('active'); $('#' + defaultTool).addClass('active'); } }); Template.textMarkerDialogs.onRendered(function() { const optionsDialog = $('#textMarkerOptionsDialog'); optionsDialog.draggable(); dialogPolyfill.registerDialog(optionsDialog.get(0)); const relabelDialog = $('#textMarkerRelabelDialog'); relabelDialog.draggable(); dialogPolyfill.registerDialog(relabelDialog.get(0)); $(document).on('click', event => { if (!$(event.target).closest('.select2-wrapper').length) { setTimeout(() => { $('#startFrom, .relabelSelect').select2('close'); }, 200); } }); $(document).on('touchmove', event => { if (!$(event.target).closest('.select2-container').length) { setTimeout(() => { $('#startFrom, .relabelSelect').select2('close'); }, 200); } }); $(() => { FastClick.attach(document.body); const $customSelects = $('#startFrom, .relabelSelect') $customSelects.select2({ /** * Adds needsclick class to all DOM elements in the Select2 results list * so they can be accessible on iOS mobile when FastClick is initiated too. */ templateResult(result, container) { if (!result.id) { return result.text; } container.className += ' needsclick'; return result.text; }, placeholder: 'C1', minimumResultsForSearch: -1, theme: 'viewerDropdown' }); /** * Additional to tweaking the templateResult option in Select2, * add needsclick class to all DOM elements in the Select2 container, * so they can be accessible on iOS mobile when FastClick is initiated too. * * More info about needsclick: * https://github.com/ftlabs/fastclick#ignore-certain-elements-with-needsclick * */ $customSelects.each( (index, el) =>{ $(el).data('select2').$container.find('*').addClass('needsclick'); }); }); });
{ "content_hash": "6f26f14de0c3362bac0e700f143e2d5b", "timestamp": "", "source": "github", "line_count": 124, "max_line_length": 88, "avg_line_length": 35.58064516129032, "alnum_prop": 0.5818223028105167, "repo_name": "NucleusIo/HealthGenesis", "id": "335418881b0f328fe1fa15ab92ae0f94e0cea392", "size": "4412", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "viewerApp/Packages/ohif-viewerbase/client/components/viewer/textMarkerDialogs/textMarkerDialogs.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "168" }, { "name": "CSS", "bytes": "128109" }, { "name": "HTML", "bytes": "151790" }, { "name": "JavaScript", "bytes": "2823176" }, { "name": "Shell", "bytes": "8160" } ], "symlink_target": "" }
IF NOT EXISTS (select * from sys.objects where type = 'p' and name = 'testRowGroupAndDelta' and schema_id = SCHEMA_ID('RowGroups') ) exec ('create procedure [RowGroups].[testRowGroupAndDelta] as select 1'); GO ALTER PROCEDURE [RowGroups].[testRowGroupAndDelta] AS BEGIN DROP TABLE IF EXISTS #ExpectedRowGroups; CREATE TABLE #ExpectedRowGroups( [TableName] nvarchar(256), [Type] varchar(20), [ObjectType] varchar(20) not null, [Location] varchar(15), [Partition] int, [Compression Type] varchar(50), [BulkLoadRGs] int, [Open DeltaStores] int, [Closed DeltaStores] int, [Tombstones] int, [Compressed RowGroups] int, [Total RowGroups] int, [Deleted Rows] Decimal(18,6), [Active Rows] Decimal(18,6), [Total Rows] Decimal(18,6), [Size in GB] Decimal(18,3), [Scans] int, [Updates] int, [LastScan] DateTime ); select top (0) * into #ActualRowGroups from #ExpectedRowGroups; -- CCI -- Insert expected result insert into #ExpectedRowGroups (TableName, Type, ObjectType, Location, Partition, [Compression Type], [BulkLoadRGs], [Open DeltaStores], [Closed DeltaStores], Tombstones, [Compressed RowGroups], [Total RowGroups], [Deleted Rows], [Active Rows], [Total Rows], [Size in GB], [Scans], [Updates], [LastScan]) select '[dbo].[RowGroupAndDeltaCCI]', 'Clustered', 'Table', 'Disk-Based', 1, 'COLUMNSTORE', 0, 1, 0, 0, 1, 2, 0.0 /*Del Rows*/, 0.000002 /*Active Rows*/, 0.000002 /*Total Rows*/, 0.0, 0, 1, NULL; insert into #ActualRowGroups exec dbo.cstore_GetRowGroups @tableName = 'RowGroupAndDelta'; update #ExpectedRowGroups set Scans = NULL, Updates = NULL, LastScan = NULL; update #ActualRowGroups set Scans = NULL, Updates = NULL, LastScan = NULL; exec tSQLt.AssertEqualsTable '#ExpectedRowGroups', '#ActualRowGroups'; END GO
{ "content_hash": "bd8578b3a541ce8983b6e6ae194f5def", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 159, "avg_line_length": 32.32142857142857, "alnum_prop": 0.6988950276243094, "repo_name": "NikoNeugebauer/CISL", "id": "2f10d09ab97055ccfa2067fed7bd7a844ec807ed", "size": "2719", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Tests/SQL-2016/RowGroups_testRowGroupAndDelta.sql", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PLSQL", "bytes": "1019817" }, { "name": "PLpgSQL", "bytes": "1357440" }, { "name": "PowerShell", "bytes": "41457" }, { "name": "SQLPL", "bytes": "277625" } ], "symlink_target": "" }
""" Copyright (c) 2014 Alex Forencich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from myhdl import * import os try: from queue import Queue except ImportError: from Queue import Queue import axis_ep module = 'axis_register_64' srcs = [] srcs.append("../rtl/%s.v" % module) srcs.append("test_%s.v" % module) src = ' '.join(srcs) build_cmd = "iverilog -o test_%s.vvp %s" % (module, src) def dut_axis_register_64(clk, rst, current_test, input_axis_tdata, input_axis_tkeep, input_axis_tvalid, input_axis_tready, input_axis_tlast, input_axis_tuser, output_axis_tdata, output_axis_tkeep, output_axis_tvalid, output_axis_tready, output_axis_tlast, output_axis_tuser): if os.system(build_cmd): raise Exception("Error running build command") return Cosimulation("vvp -m myhdl test_%s.vvp -lxt2" % module, clk=clk, rst=rst, current_test=current_test, input_axis_tdata=input_axis_tdata, input_axis_tkeep=input_axis_tkeep, input_axis_tvalid=input_axis_tvalid, input_axis_tready=input_axis_tready, input_axis_tlast=input_axis_tlast, input_axis_tuser=input_axis_tuser, output_axis_tdata=output_axis_tdata, output_axis_tkeep=output_axis_tkeep, output_axis_tvalid=output_axis_tvalid, output_axis_tready=output_axis_tready, output_axis_tlast=output_axis_tlast, output_axis_tuser=output_axis_tuser) def bench(): # Inputs clk = Signal(bool(0)) rst = Signal(bool(0)) current_test = Signal(intbv(0)[8:]) input_axis_tdata = Signal(intbv(0)[64:]) input_axis_tkeep = Signal(intbv(0)[8:]) input_axis_tvalid = Signal(bool(0)) input_axis_tlast = Signal(bool(0)) input_axis_tuser = Signal(bool(0)) output_axis_tready = Signal(bool(0)) # Outputs input_axis_tready = Signal(bool(0)) output_axis_tdata = Signal(intbv(0)[64:]) output_axis_tkeep = Signal(intbv(0)[8:]) output_axis_tvalid = Signal(bool(0)) output_axis_tlast = Signal(bool(0)) output_axis_tuser = Signal(bool(0)) # sources and sinks source_queue = Queue() source_pause = Signal(bool(0)) sink_queue = Queue() sink_pause = Signal(bool(0)) source = axis_ep.AXIStreamSource(clk, rst, tdata=input_axis_tdata, tkeep=input_axis_tkeep, tvalid=input_axis_tvalid, tready=input_axis_tready, tlast=input_axis_tlast, tuser=input_axis_tuser, fifo=source_queue, pause=source_pause, name='source') sink = axis_ep.AXIStreamSink(clk, rst, tdata=output_axis_tdata, tkeep=output_axis_tkeep, tvalid=output_axis_tvalid, tready=output_axis_tready, tlast=output_axis_tlast, tuser=output_axis_tuser, fifo=sink_queue, pause=sink_pause, name='sink') # DUT dut = dut_axis_register_64(clk, rst, current_test, input_axis_tdata, input_axis_tkeep, input_axis_tvalid, input_axis_tready, input_axis_tlast, input_axis_tuser, output_axis_tdata, output_axis_tkeep, output_axis_tvalid, output_axis_tready, output_axis_tlast, output_axis_tuser) @always(delay(4)) def clkgen(): clk.next = not clk @instance def check(): yield delay(100) yield clk.posedge rst.next = 1 yield clk.posedge rst.next = 0 yield clk.posedge yield delay(100) yield clk.posedge yield clk.posedge yield clk.posedge print("test 1: test packet") current_test.next = 1 test_frame = axis_ep.AXIStreamFrame(b'\xDA\xD1\xD2\xD3\xD4\xD5' + b'\x5A\x51\x52\x53\x54\x55' + b'\x80\x00' + b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10') source_queue.put(test_frame) yield clk.posedge yield output_axis_tlast.posedge yield clk.posedge yield clk.posedge rx_frame = None if not sink_queue.empty(): rx_frame = sink_queue.get() assert rx_frame == test_frame yield delay(100) yield clk.posedge print("test 2: longer packet") current_test.next = 2 test_frame = axis_ep.AXIStreamFrame(b'\xDA\xD1\xD2\xD3\xD4\xD5' + b'\x5A\x51\x52\x53\x54\x55' + b'\x80\x00' + bytearray(range(256))) source_queue.put(test_frame) yield clk.posedge yield output_axis_tlast.posedge yield clk.posedge yield clk.posedge rx_frame = None if not sink_queue.empty(): rx_frame = sink_queue.get() assert rx_frame == test_frame yield clk.posedge print("test 3: test packet with pauses") current_test.next = 3 test_frame = axis_ep.AXIStreamFrame(b'\xDA\xD1\xD2\xD3\xD4\xD5' + b'\x5A\x51\x52\x53\x54\x55' + b'\x80\x00' + bytearray(range(256))) source_queue.put(test_frame) yield clk.posedge yield delay(64) yield clk.posedge source_pause.next = True yield delay(32) yield clk.posedge source_pause.next = False yield delay(64) yield clk.posedge sink_pause.next = True yield delay(32) yield clk.posedge sink_pause.next = False yield output_axis_tlast.posedge yield clk.posedge yield clk.posedge rx_frame = None if not sink_queue.empty(): rx_frame = sink_queue.get() assert rx_frame == test_frame yield delay(100) yield clk.posedge print("test 4: back-to-back packets") current_test.next = 4 test_frame1 = axis_ep.AXIStreamFrame(b'\xDA\xD1\xD2\xD3\xD4\xD5' + b'\x5A\x51\x52\x53\x54\x55' + b'\x80\x00' + b'\x01\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10') test_frame2 = axis_ep.AXIStreamFrame(b'\xDA\xD1\xD2\xD3\xD4\xD5' + b'\x5A\x51\x52\x53\x54\x55' + b'\x80\x00' + b'\x02\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10') source_queue.put(test_frame1) source_queue.put(test_frame2) yield clk.posedge yield output_axis_tlast.posedge yield clk.posedge yield output_axis_tlast.posedge yield clk.posedge yield clk.posedge rx_frame = None if not sink_queue.empty(): rx_frame = sink_queue.get() assert rx_frame == test_frame1 rx_frame = None if not sink_queue.empty(): rx_frame = sink_queue.get() assert rx_frame == test_frame2 yield delay(100) yield clk.posedge print("test 5: alternate pause source") current_test.next = 5 test_frame1 = axis_ep.AXIStreamFrame(b'\xDA\xD1\xD2\xD3\xD4\xD5' + b'\x5A\x51\x52\x53\x54\x55' + b'\x80\x00' + b'\x01\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10') test_frame2 = axis_ep.AXIStreamFrame(b'\xDA\xD1\xD2\xD3\xD4\xD5' + b'\x5A\x51\x52\x53\x54\x55' + b'\x80\x00' + b'\x02\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10') source_queue.put(test_frame1) source_queue.put(test_frame2) yield clk.posedge while input_axis_tvalid or output_axis_tvalid: source_pause.next = True yield clk.posedge yield clk.posedge yield clk.posedge source_pause.next = False yield clk.posedge yield clk.posedge yield clk.posedge rx_frame = None if not sink_queue.empty(): rx_frame = sink_queue.get() assert rx_frame == test_frame1 rx_frame = None if not sink_queue.empty(): rx_frame = sink_queue.get() assert rx_frame == test_frame2 yield delay(100) yield clk.posedge print("test 6: alternate pause sink") current_test.next = 6 test_frame1 = axis_ep.AXIStreamFrame(b'\xDA\xD1\xD2\xD3\xD4\xD5' + b'\x5A\x51\x52\x53\x54\x55' + b'\x80\x00' + b'\x01\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10') test_frame2 = axis_ep.AXIStreamFrame(b'\xDA\xD1\xD2\xD3\xD4\xD5' + b'\x5A\x51\x52\x53\x54\x55' + b'\x80\x00' + b'\x02\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10') source_queue.put(test_frame1) source_queue.put(test_frame2) yield clk.posedge while input_axis_tvalid or output_axis_tvalid: sink_pause.next = True yield clk.posedge yield clk.posedge yield clk.posedge sink_pause.next = False yield clk.posedge yield clk.posedge yield clk.posedge rx_frame = None if not sink_queue.empty(): rx_frame = sink_queue.get() assert rx_frame == test_frame1 rx_frame = None if not sink_queue.empty(): rx_frame = sink_queue.get() assert rx_frame == test_frame2 yield delay(100) yield clk.posedge print("test 7: tuser assert") current_test.next = 7 test_frame = axis_ep.AXIStreamFrame(b'\xDA\xD1\xD2\xD3\xD4\xD5' + b'\x5A\x51\x52\x53\x54\x55' + b'\x80\x00' + b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10') test_frame.user = 1 source_queue.put(test_frame) yield clk.posedge yield output_axis_tlast.posedge yield clk.posedge yield clk.posedge rx_frame = None if not sink_queue.empty(): rx_frame = sink_queue.get() assert rx_frame == test_frame assert rx_frame.user[-1] yield delay(100) raise StopSimulation return dut, source, sink, clkgen, check def test_bench(): os.chdir(os.path.dirname(os.path.abspath(__file__))) sim = Simulation(bench()) sim.run() if __name__ == '__main__': print("Running test...") test_bench()
{ "content_hash": "5d0e91512a98a707abba68dc61d36b61", "timestamp": "", "source": "github", "line_count": 409, "max_line_length": 117, "avg_line_length": 33.02200488997555, "alnum_prop": 0.5009625351695542, "repo_name": "alexforencich/hdg2000", "id": "986201bce01cd657b86d95e81744d1be4f810d17", "size": "13528", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "fpga/lib/axis/tb/test_axis_register_64.py", "mode": "33261", "license": "mit", "language": [ { "name": "Makefile", "bytes": "9054" }, { "name": "Python", "bytes": "934476" }, { "name": "Shell", "bytes": "8661" }, { "name": "Verilog", "bytes": "687285" } ], "symlink_target": "" }
<footer class="post-info"> <span class="label label-default">Date</span> <span class="published"> <i class="fa fa-calendar"></i><time datetime="{{ article.date.isoformat() }}"> {{ article.locale_date }}</time> </span> {% if SHOW_ARTICLE_AUTHOR %} {% if article.author %} <span class="label label-default">By</span> <a href="{{ SITEURL }}/{{ article.author.url }}"><i class="fa fa-user"></i> {{ article.author }}</a> {% endif %} {% endif %} {% if SHOW_ARTICLE_CATEGORY %} <span class="label label-default">Category</span> <a href="{{ SITEURL }}/{{ article.category.url }}">{{ article.category }}</a> {% endif %} {% if PDF_PROCESSOR %} <span class="label label-default"> <a href="{{ SITEURL }}/pdf/{{ article.slug }}.pdf">as PDF</a> </span> {% endif %} {% include 'includes/taglist.html' %} {% import 'includes/translations.html' as translations with context %} {{ translations.translations_for(article) }} </footer><!-- /.post-info -->
{ "content_hash": "2674fa5e2fac9918c7fc743f735ea5f2", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 119, "avg_line_length": 39.925925925925924, "alnum_prop": 0.5593692022263451, "repo_name": "gw0/pelican-bootstrap3", "id": "333d42676bddd52e29753b1f660359bcfbd0eb59", "size": "1078", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "templates/includes/article_info.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "99385" }, { "name": "HTML", "bytes": "45772" }, { "name": "JavaScript", "bytes": "3952" } ], "symlink_target": "" }
""" Command-line and common processing for Docutils front-end tools. Exports the following classes: * `OptionParser`: Standard Docutils command-line processing. * `Option`: Customized version of `optparse.Option`; validation support. * `Values`: Runtime settings; objects are simple structs (``object.attribute``). Supports cumulative list settings (attributes). * `ConfigParser`: Standard Docutils config file processing. Also exports the following functions: * Option callbacks: `store_multiple`, `read_config_file`. * Setting validators: `validate_encoding`, `validate_encoding_error_handler`, `validate_encoding_and_error_handler`, `validate_boolean`, `validate_threshold`, `validate_colon_separated_string_list`, `validate_dependency_file`. * `make_paths_absolute`. * SettingSpec manipulation: `filter_settings_spec`. """ __docformat__ = 'reStructuredText' import os import os.path import sys import warnings import ConfigParser as CP import codecs import optparse from optparse import SUPPRESS_HELP import docutils import docutils.utils import docutils.nodes from docutils.error_reporting import locale_encoding, ErrorOutput, ErrorString def store_multiple(option, opt, value, parser, *args, **kwargs): """ Store multiple values in `parser.values`. (Option callback.) Store `None` for each attribute named in `args`, and store the value for each key (attribute name) in `kwargs`. """ for attribute in args: setattr(parser.values, attribute, None) for key, value in kwargs.items(): setattr(parser.values, key, value) def read_config_file(option, opt, value, parser): """ Read a configuration file during option processing. (Option callback.) """ try: new_settings = parser.get_config_file_settings(value) except ValueError, error: parser.error(error) parser.values.update(new_settings, parser) def validate_encoding(setting, value, option_parser, config_parser=None, config_section=None): try: codecs.lookup(value) except LookupError: raise (LookupError('setting "%s": unknown encoding: "%s"' % (setting, value)), None, sys.exc_info()[2]) return value def validate_encoding_error_handler(setting, value, option_parser, config_parser=None, config_section=None): try: codecs.lookup_error(value) except LookupError: raise (LookupError( 'unknown encoding error handler: "%s" (choices: ' '"strict", "ignore", "replace", "backslashreplace", ' '"xmlcharrefreplace", and possibly others; see documentation for ' 'the Python ``codecs`` module)' % value), None, sys.exc_info()[2]) return value def validate_encoding_and_error_handler( setting, value, option_parser, config_parser=None, config_section=None): """ Side-effect: if an error handler is included in the value, it is inserted into the appropriate place as if it was a separate setting/option. """ if ':' in value: encoding, handler = value.split(':') validate_encoding_error_handler( setting + '_error_handler', handler, option_parser, config_parser, config_section) if config_parser: config_parser.set(config_section, setting + '_error_handler', handler) else: setattr(option_parser.values, setting + '_error_handler', handler) else: encoding = value validate_encoding(setting, encoding, option_parser, config_parser, config_section) return encoding def validate_boolean(setting, value, option_parser, config_parser=None, config_section=None): if isinstance(value, unicode): try: return option_parser.booleans[value.strip().lower()] except KeyError: raise (LookupError('unknown boolean value: "%s"' % value), None, sys.exc_info()[2]) return value def validate_nonnegative_int(setting, value, option_parser, config_parser=None, config_section=None): value = int(value) if value < 0: raise ValueError('negative value; must be positive or zero') return value def validate_threshold(setting, value, option_parser, config_parser=None, config_section=None): try: return int(value) except ValueError: try: return option_parser.thresholds[value.lower()] except (KeyError, AttributeError): raise (LookupError('unknown threshold: %r.' % value), None, sys.exc_info[2]) def validate_colon_separated_string_list( setting, value, option_parser, config_parser=None, config_section=None): if isinstance(value, unicode): value = value.split(':') else: last = value.pop() value.extend(last.split(':')) return value def validate_url_trailing_slash( setting, value, option_parser, config_parser=None, config_section=None): if not value: return './' elif value.endswith('/'): return value else: return value + '/' def validate_dependency_file(setting, value, option_parser, config_parser=None, config_section=None): try: return docutils.utils.DependencyList(value) except IOError: return docutils.utils.DependencyList(None) def validate_strip_class(setting, value, option_parser, config_parser=None, config_section=None): # convert to list: if isinstance(value, unicode): value = [value] class_values = filter(None, [v.strip() for v in value.pop().split(',')]) # validate: for class_value in class_values: normalized = docutils.nodes.make_id(class_value) if class_value != normalized: raise ValueError('invalid class value %r (perhaps %r?)' % (class_value, normalized)) value.extend(class_values) return value def make_paths_absolute(pathdict, keys, base_path=None): """ Interpret filesystem path settings relative to the `base_path` given. Paths are values in `pathdict` whose keys are in `keys`. Get `keys` from `OptionParser.relative_path_settings`. """ if base_path is None: base_path = os.getcwdu() # type(base_path) == unicode # to allow combining non-ASCII cwd with unicode values in `pathdict` for key in keys: if key in pathdict: value = pathdict[key] if isinstance(value, list): value = [make_one_path_absolute(base_path, path) for path in value] elif value: value = make_one_path_absolute(base_path, value) pathdict[key] = value def make_one_path_absolute(base_path, path): return os.path.abspath(os.path.join(base_path, path)) def filter_settings_spec(settings_spec, *exclude, **replace): """Return a copy of `settings_spec` excluding/replacing some settings. `settings_spec` is a tuple of configuration settings with a structure described for docutils.SettingsSpec.settings_spec. Optional positional arguments are names of to-be-excluded settings. Keyword arguments are option specification replacements. (See the html4strict writer for an example.) """ settings = list(settings_spec) # every third item is a sequence of option tuples for i in range(2, len(settings), 3): newopts = [] for opt_spec in settings[i]: # opt_spec is ("<help>", [<option strings>], {<keyword args>}) opt_name = [opt_string[2:].replace('-', '_') for opt_string in opt_spec[1] if opt_string.startswith('--') ][0] if opt_name in exclude: continue if opt_name in replace.keys(): newopts.append(replace[opt_name]) else: newopts.append(opt_spec) settings[i] = tuple(newopts) return tuple(settings) class Values(optparse.Values): """ Updates list attributes by extension rather than by replacement. Works in conjunction with the `OptionParser.lists` instance attribute. """ def __init__(self, *args, **kwargs): optparse.Values.__init__(self, *args, **kwargs) if (not hasattr(self, 'record_dependencies') or self.record_dependencies is None): # Set up dependency list, in case it is needed. self.record_dependencies = docutils.utils.DependencyList() def update(self, other_dict, option_parser): if isinstance(other_dict, Values): other_dict = other_dict.__dict__ other_dict = other_dict.copy() for setting in option_parser.lists.keys(): if (hasattr(self, setting) and setting in other_dict): value = getattr(self, setting) if value: value += other_dict[setting] del other_dict[setting] self._update_loose(other_dict) def copy(self): """Return a shallow copy of `self`.""" return self.__class__(defaults=self.__dict__) class Option(optparse.Option): ATTRS = optparse.Option.ATTRS + ['validator', 'overrides'] def process(self, opt, value, values, parser): """ Call the validator function on applicable settings and evaluate the 'overrides' option. Extends `optparse.Option.process`. """ result = optparse.Option.process(self, opt, value, values, parser) setting = self.dest if setting: if self.validator: value = getattr(values, setting) try: new_value = self.validator(setting, value, parser) except Exception, error: raise (optparse.OptionValueError( 'Error in option "%s":\n %s' % (opt, ErrorString(error))), None, sys.exc_info()[2]) setattr(values, setting, new_value) if self.overrides: setattr(values, self.overrides, None) return result class OptionParser(optparse.OptionParser, docutils.SettingsSpec): """ Parser for command-line and library use. The `settings_spec` specification here and in other Docutils components are merged to build the set of command-line options and runtime settings for this process. Common settings (defined below) and component-specific settings must not conflict. Short options are reserved for common settings, and components are restrict to using long options. """ standard_config_files = [ '/etc/docutils.conf', # system-wide './docutils.conf', # project-specific '~/.docutils'] # user-specific """Docutils configuration files, using ConfigParser syntax. Filenames will be tilde-expanded later. Later files override earlier ones.""" threshold_choices = 'info 1 warning 2 error 3 severe 4 none 5'.split() """Possible inputs for for --report and --halt threshold values.""" thresholds = {'info': 1, 'warning': 2, 'error': 3, 'severe': 4, 'none': 5} """Lookup table for --report and --halt threshold values.""" booleans={'1': 1, 'on': 1, 'yes': 1, 'true': 1, '0': 0, 'off': 0, 'no': 0, 'false': 0, '': 0} """Lookup table for boolean configuration file settings.""" default_error_encoding = getattr(sys.stderr, 'encoding', None) or locale_encoding or 'ascii' default_error_encoding_error_handler = 'backslashreplace' settings_spec = ( 'General Docutils Options', None, (('Specify the document title as metadata.', ['--title'], {}), ('Include a "Generated by Docutils" credit and link.', ['--generator', '-g'], {'action': 'store_true', 'validator': validate_boolean}), ('Do not include a generator credit.', ['--no-generator'], {'action': 'store_false', 'dest': 'generator'}), ('Include the date at the end of the document (UTC).', ['--date', '-d'], {'action': 'store_const', 'const': '%Y-%m-%d', 'dest': 'datestamp'}), ('Include the time & date (UTC).', ['--time', '-t'], {'action': 'store_const', 'const': '%Y-%m-%d %H:%M UTC', 'dest': 'datestamp'}), ('Do not include a datestamp of any kind.', ['--no-datestamp'], {'action': 'store_const', 'const': None, 'dest': 'datestamp'}), ('Include a "View document source" link.', ['--source-link', '-s'], {'action': 'store_true', 'validator': validate_boolean}), ('Use <URL> for a source link; implies --source-link.', ['--source-url'], {'metavar': '<URL>'}), ('Do not include a "View document source" link.', ['--no-source-link'], {'action': 'callback', 'callback': store_multiple, 'callback_args': ('source_link', 'source_url')}), ('Link from section headers to TOC entries. (default)', ['--toc-entry-backlinks'], {'dest': 'toc_backlinks', 'action': 'store_const', 'const': 'entry', 'default': 'entry'}), ('Link from section headers to the top of the TOC.', ['--toc-top-backlinks'], {'dest': 'toc_backlinks', 'action': 'store_const', 'const': 'top'}), ('Disable backlinks to the table of contents.', ['--no-toc-backlinks'], {'dest': 'toc_backlinks', 'action': 'store_false'}), ('Link from footnotes/citations to references. (default)', ['--footnote-backlinks'], {'action': 'store_true', 'default': 1, 'validator': validate_boolean}), ('Disable backlinks from footnotes and citations.', ['--no-footnote-backlinks'], {'dest': 'footnote_backlinks', 'action': 'store_false'}), ('Enable section numbering by Docutils. (default)', ['--section-numbering'], {'action': 'store_true', 'dest': 'sectnum_xform', 'default': 1, 'validator': validate_boolean}), ('Disable section numbering by Docutils.', ['--no-section-numbering'], {'action': 'store_false', 'dest': 'sectnum_xform'}), ('Remove comment elements from the document tree.', ['--strip-comments'], {'action': 'store_true', 'validator': validate_boolean}), ('Leave comment elements in the document tree. (default)', ['--leave-comments'], {'action': 'store_false', 'dest': 'strip_comments'}), ('Remove all elements with classes="<class>" from the document tree. ' 'Warning: potentially dangerous; use with caution. ' '(Multiple-use option.)', ['--strip-elements-with-class'], {'action': 'append', 'dest': 'strip_elements_with_classes', 'metavar': '<class>', 'validator': validate_strip_class}), ('Remove all classes="<class>" attributes from elements in the ' 'document tree. Warning: potentially dangerous; use with caution. ' '(Multiple-use option.)', ['--strip-class'], {'action': 'append', 'dest': 'strip_classes', 'metavar': '<class>', 'validator': validate_strip_class}), ('Report system messages at or higher than <level>: "info" or "1", ' '"warning"/"2" (default), "error"/"3", "severe"/"4", "none"/"5"', ['--report', '-r'], {'choices': threshold_choices, 'default': 2, 'dest': 'report_level', 'metavar': '<level>', 'validator': validate_threshold}), ('Report all system messages. (Same as "--report=1".)', ['--verbose', '-v'], {'action': 'store_const', 'const': 1, 'dest': 'report_level'}), ('Report no system messages. (Same as "--report=5".)', ['--quiet', '-q'], {'action': 'store_const', 'const': 5, 'dest': 'report_level'}), ('Halt execution at system messages at or above <level>. ' 'Levels as in --report. Default: 4 (severe).', ['--halt'], {'choices': threshold_choices, 'dest': 'halt_level', 'default': 4, 'metavar': '<level>', 'validator': validate_threshold}), ('Halt at the slightest problem. Same as "--halt=info".', ['--strict'], {'action': 'store_const', 'const': 1, 'dest': 'halt_level'}), ('Enable a non-zero exit status for non-halting system messages at ' 'or above <level>. Default: 5 (disabled).', ['--exit-status'], {'choices': threshold_choices, 'dest': 'exit_status_level', 'default': 5, 'metavar': '<level>', 'validator': validate_threshold}), ('Enable debug-level system messages and diagnostics.', ['--debug'], {'action': 'store_true', 'validator': validate_boolean}), ('Disable debug output. (default)', ['--no-debug'], {'action': 'store_false', 'dest': 'debug'}), ('Send the output of system messages to <file>.', ['--warnings'], {'dest': 'warning_stream', 'metavar': '<file>'}), ('Enable Python tracebacks when Docutils is halted.', ['--traceback'], {'action': 'store_true', 'default': None, 'validator': validate_boolean}), ('Disable Python tracebacks. (default)', ['--no-traceback'], {'dest': 'traceback', 'action': 'store_false'}), ('Specify the encoding and optionally the ' 'error handler of input text. Default: <locale-dependent>:strict.', ['--input-encoding', '-i'], {'metavar': '<name[:handler]>', 'validator': validate_encoding_and_error_handler}), ('Specify the error handler for undecodable characters. ' 'Choices: "strict" (default), "ignore", and "replace".', ['--input-encoding-error-handler'], {'default': 'strict', 'validator': validate_encoding_error_handler}), ('Specify the text encoding and optionally the error handler for ' 'output. Default: UTF-8:strict.', ['--output-encoding', '-o'], {'metavar': '<name[:handler]>', 'default': 'utf-8', 'validator': validate_encoding_and_error_handler}), ('Specify error handler for unencodable output characters; ' '"strict" (default), "ignore", "replace", ' '"xmlcharrefreplace", "backslashreplace".', ['--output-encoding-error-handler'], {'default': 'strict', 'validator': validate_encoding_error_handler}), ('Specify text encoding and error handler for error output. ' 'Default: %s:%s.' % (default_error_encoding, default_error_encoding_error_handler), ['--error-encoding', '-e'], {'metavar': '<name[:handler]>', 'default': default_error_encoding, 'validator': validate_encoding_and_error_handler}), ('Specify the error handler for unencodable characters in ' 'error output. Default: %s.' % default_error_encoding_error_handler, ['--error-encoding-error-handler'], {'default': default_error_encoding_error_handler, 'validator': validate_encoding_error_handler}), ('Specify the language (as BCP 47 language tag). Default: en.', ['--language', '-l'], {'dest': 'language_code', 'default': 'en', 'metavar': '<name>'}), ('Write output file dependencies to <file>.', ['--record-dependencies'], {'metavar': '<file>', 'validator': validate_dependency_file, 'default': None}), # default set in Values class ('Read configuration settings from <file>, if it exists.', ['--config'], {'metavar': '<file>', 'type': 'string', 'action': 'callback', 'callback': read_config_file}), ("Show this program's version number and exit.", ['--version', '-V'], {'action': 'version'}), ('Show this help message and exit.', ['--help', '-h'], {'action': 'help'}), # Typically not useful for non-programmatical use: (SUPPRESS_HELP, ['--id-prefix'], {'default': ''}), (SUPPRESS_HELP, ['--auto-id-prefix'], {'default': 'id'}), # Hidden options, for development use only: (SUPPRESS_HELP, ['--dump-settings'], {'action': 'store_true'}), (SUPPRESS_HELP, ['--dump-internals'], {'action': 'store_true'}), (SUPPRESS_HELP, ['--dump-transforms'], {'action': 'store_true'}), (SUPPRESS_HELP, ['--dump-pseudo-xml'], {'action': 'store_true'}), (SUPPRESS_HELP, ['--expose-internal-attribute'], {'action': 'append', 'dest': 'expose_internals', 'validator': validate_colon_separated_string_list}), (SUPPRESS_HELP, ['--strict-visitor'], {'action': 'store_true'}), )) """Runtime settings and command-line options common to all Docutils front ends. Setting specs specific to individual Docutils components are also used (see `populate_from_components()`).""" settings_defaults = {'_disable_config': None, '_source': None, '_destination': None, '_config_files': None} """Defaults for settings that don't have command-line option equivalents.""" relative_path_settings = ('warning_stream',) config_section = 'general' version_template = ('%%prog (Docutils %s [%s], Python %s, on %s)' % (docutils.__version__, docutils.__version_details__, sys.version.split()[0], sys.platform)) """Default version message.""" def __init__(self, components=(), defaults=None, read_config_files=None, *args, **kwargs): """ `components` is a list of Docutils components each containing a ``.settings_spec`` attribute. `defaults` is a mapping of setting default overrides. """ self.lists = {} """Set of list-type settings.""" self.config_files = [] """List of paths of applied configuration files.""" optparse.OptionParser.__init__( self, option_class=Option, add_help_option=None, formatter=optparse.TitledHelpFormatter(width=78), *args, **kwargs) if not self.version: self.version = self.version_template # Make an instance copy (it will be modified): self.relative_path_settings = list(self.relative_path_settings) self.components = (self,) + tuple(components) self.populate_from_components(self.components) self.set_defaults_from_dict(defaults or {}) if read_config_files and not self.defaults['_disable_config']: try: config_settings = self.get_standard_config_settings() except ValueError, error: self.error(error) self.set_defaults_from_dict(config_settings.__dict__) def populate_from_components(self, components): """ For each component, first populate from the `SettingsSpec.settings_spec` structure, then from the `SettingsSpec.settings_defaults` dictionary. After all components have been processed, check for and populate from each component's `SettingsSpec.settings_default_overrides` dictionary. """ for component in components: if component is None: continue settings_spec = component.settings_spec self.relative_path_settings.extend( component.relative_path_settings) for i in range(0, len(settings_spec), 3): title, description, option_spec = settings_spec[i:i+3] if title: group = optparse.OptionGroup(self, title, description) self.add_option_group(group) else: group = self # single options for (help_text, option_strings, kwargs) in option_spec: option = group.add_option(help=help_text, *option_strings, **kwargs) if kwargs.get('action') == 'append': self.lists[option.dest] = 1 if component.settings_defaults: self.defaults.update(component.settings_defaults) for component in components: if component and component.settings_default_overrides: self.defaults.update(component.settings_default_overrides) def get_standard_config_files(self): """Return list of config files, from environment or standard.""" try: config_files = os.environ['DOCUTILSCONFIG'].split(os.pathsep) except KeyError: config_files = self.standard_config_files # If 'HOME' is not set, expandvars() requires the 'pwd' module which is # not available under certain environments, for example, within # mod_python. The publisher ends up in here, and we need to publish # from within mod_python. Therefore we need to avoid expanding when we # are in those environments. expand = os.path.expanduser if 'HOME' not in os.environ: try: import pwd except ImportError: expand = lambda x: x return [expand(f) for f in config_files if f.strip()] def get_standard_config_settings(self): settings = Values() for filename in self.get_standard_config_files(): settings.update(self.get_config_file_settings(filename), self) return settings def get_config_file_settings(self, config_file): """Returns a dictionary containing appropriate config file settings.""" parser = ConfigParser() parser.read(config_file, self) self.config_files.extend(parser._files) base_path = os.path.dirname(config_file) applied = {} settings = Values() for component in self.components: if not component: continue for section in (tuple(component.config_section_dependencies or ()) + (component.config_section,)): if section in applied: continue applied[section] = 1 settings.update(parser.get_section(section), self) make_paths_absolute( settings.__dict__, self.relative_path_settings, base_path) return settings.__dict__ def check_values(self, values, args): """Store positional arguments as runtime settings.""" values._source, values._destination = self.check_args(args) make_paths_absolute(values.__dict__, self.relative_path_settings) values._config_files = self.config_files return values def check_args(self, args): source = destination = None if args: source = args.pop(0) if source == '-': # means stdin source = None if args: destination = args.pop(0) if destination == '-': # means stdout destination = None if args: self.error('Maximum 2 arguments allowed.') if source and source == destination: self.error('Do not specify the same file for both source and ' 'destination. It will clobber the source file.') return source, destination def set_defaults_from_dict(self, defaults): self.defaults.update(defaults) def get_default_values(self): """Needed to get custom `Values` instances.""" defaults = Values(self.defaults) defaults._config_files = self.config_files return defaults def get_option_by_dest(self, dest): """ Get an option by its dest. If you're supplying a dest which is shared by several options, it is undefined which option of those is returned. A KeyError is raised if there is no option with the supplied dest. """ for group in self.option_groups + [self]: for option in group.option_list: if option.dest == dest: return option raise KeyError('No option with dest == %r.' % dest) class ConfigParser(CP.RawConfigParser): old_settings = { 'pep_stylesheet': ('pep_html writer', 'stylesheet'), 'pep_stylesheet_path': ('pep_html writer', 'stylesheet_path'), 'pep_template': ('pep_html writer', 'template')} """{old setting: (new section, new setting)} mapping, used by `handle_old_config`, to convert settings from the old [options] section.""" old_warning = """ The "[option]" section is deprecated. Support for old-format configuration files may be removed in a future Docutils release. Please revise your configuration files. See <http://docutils.sf.net/docs/user/config.html>, section "Old-Format Configuration Files". """ not_utf8_error = """\ Unable to read configuration file "%s": content not encoded as UTF-8. Skipping "%s" configuration file. """ def __init__(self, *args, **kwargs): CP.RawConfigParser.__init__(self, *args, **kwargs) self._files = [] """List of paths of configuration files read.""" self._stderr = ErrorOutput() """Wrapper around sys.stderr catching en-/decoding errors""" def read(self, filenames, option_parser): if type(filenames) in (str, unicode): filenames = [filenames] for filename in filenames: try: # Config files must be UTF-8-encoded: fp = codecs.open(filename, 'r', 'utf-8') except IOError: continue try: if sys.version_info < (3,2): CP.RawConfigParser.readfp(self, fp, filename) else: CP.RawConfigParser.read_file(self, fp, filename) except UnicodeDecodeError: self._stderr.write(self.not_utf8_error % (filename, filename)) fp.close() continue fp.close() self._files.append(filename) if self.has_section('options'): self.handle_old_config(filename) self.validate_settings(filename, option_parser) def handle_old_config(self, filename): warnings.warn_explicit(self.old_warning, ConfigDeprecationWarning, filename, 0) options = self.get_section('options') if not self.has_section('general'): self.add_section('general') for key, value in options.items(): if key in self.old_settings: section, setting = self.old_settings[key] if not self.has_section(section): self.add_section(section) else: section = 'general' setting = key if not self.has_option(section, setting): self.set(section, setting, value) self.remove_section('options') def validate_settings(self, filename, option_parser): """ Call the validator function and implement overrides on all applicable settings. """ for section in self.sections(): for setting in self.options(section): try: option = option_parser.get_option_by_dest(setting) except KeyError: continue if option.validator: value = self.get(section, setting) try: new_value = option.validator( setting, value, option_parser, config_parser=self, config_section=section) except Exception, error: raise (ValueError( 'Error in config file "%s", section "[%s]":\n' ' %s\n' ' %s = %s' % (filename, section, ErrorString(error), setting, value)), None, sys.exc_info()[2]) self.set(section, setting, new_value) if option.overrides: self.set(section, option.overrides, None) def optionxform(self, optionstr): """ Transform '-' to '_' so the cmdline form of option names can be used. """ return optionstr.lower().replace('-', '_') def get_section(self, section): """ Return a given section as a dictionary (empty if the section doesn't exist). """ section_dict = {} if self.has_section(section): for option in self.options(section): section_dict[option] = self.get(section, option) return section_dict class ConfigDeprecationWarning(DeprecationWarning): """Warning for deprecated configuration file features."""
{ "content_hash": "86b4bcc80c744da5959f1270d533e20d", "timestamp": "", "source": "github", "line_count": 784, "max_line_length": 80, "avg_line_length": 43.26020408163265, "alnum_prop": 0.5713527538624837, "repo_name": "ddd332/presto", "id": "83f5fde594647739f22da18ac205dba4666b0b6c", "size": "34078", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "presto-docs/target/sphinx/docutils/frontend.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1449" }, { "name": "CSS", "bytes": "130017" }, { "name": "GAP", "bytes": "41169" }, { "name": "Java", "bytes": "6836515" }, { "name": "JavaScript", "bytes": "135954" }, { "name": "Python", "bytes": "8056702" }, { "name": "TeX", "bytes": "55016" } ], "symlink_target": "" }
package com.oak.finance.app.monitor; import java.util.Set; public interface MarketDataMonitorsController { void startStocksAnalysis(Set<String> symbolList, Set<String> interestingSymbols); void loadHistoricalQuotes(); }
{ "content_hash": "4af51dc016a2fd7eae46f43fcbda73b4", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 82, "avg_line_length": 22.6, "alnum_prop": 0.8097345132743363, "repo_name": "charcode/StockScreener", "id": "7c6eadaccff0c247e86ed20758e6f57feb5e9fc0", "size": "226", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/oak/finance/app/monitor/MarketDataMonitorsController.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "242968" } ], "symlink_target": "" }
&& __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ >= 40000) \ || (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) \ && __IPHONE_OS_VERSION_MIN_REQUIRED >= 40000) # define ANKI_OS ANKI_OS_IOS # else # define ANKI_OS ANKI_OS_MACOS # endif #elif defined(__ANDROID__) # define ANKI_OS ANKI_OS_ANDROID #else # define ANKI_OS ANKI_OS_LINUX #endif // POSIX system or not #if ANKI_OS == ANKI_OS_LINUX || ANKI_OS == ANKI_OS_ANDROID \ || ANKI_OS == ANKI_OS_MACOS || ANKI_OS == ANKI_OS_IOS # define ANKI_POSIX 1 #else # define ANKI_POSIX 0 #endif // CPU architecture #define ANKI_CPU_ARCH_INTEL 1 #define ANKI_CPU_ARCH_ARM 2 #if defined(__GNUC__) # if defined(__arm__) # define ANKI_CPU_ARCH ANKI_CPU_ARCH_ARM # define ANKI_CPU_ARCH_STR "ANKI_CPU_ARCH_ARM" # elif defined(__i386__) || defined(__amd64__) # define ANKI_CPU_ARCH ANKI_CPU_ARCH_INTEL # define ANKI_CPU_ARCH_STR "ANKI_CPU_ARCH_INTEL" # else # error "Unknown CPU arch" # endif #else # error "Unsupported compiler" #endif // SIMD #define ANKI_ENABLE_SIMD ${_ANKI_ENABLE_SIMD} #define ANKI_SIMD_NONE 1 #define ANKI_SIMD_SSE 2 #define ANKI_SIMD_NEON 3 #if !ANKI_ENABLE_SIMD # define ANKI_SIMD ANKI_SIMD_NONE #else # if ANKI_CPU_ARCH == ANKI_CPU_ARCH_INTEL # define ANKI_SIMD ANKI_SIMD_SSE # elif ANKI_CPU_ARCH == ANKI_CPU_ARCH_ARM # define ANKI_SIMD ANKI_SIMD_NEON # endif #endif // Window backend #define ANKI_WINDOW_BACKEND_GLXX11 1 #define ANKI_WINDOW_BACKEND_EGLX11 2 #define ANKI_WINDOW_BACKEND_EGLFBDEV 3 #define ANKI_WINDOW_BACKEND_MACOS 4 #define ANKI_WINDOW_BACKEND_ANDROID 5 #define ANKI_WINDOW_BACKEND_SDL 6 #define ANKI_WINDOW_BACKEND ANKI_WINDOW_BACKEND_${ANKI_WINDOW_BACKEND} #define ANKI_WINDOW_BACKEND_STR "ANKI_WINDOW_BACKEND_${ANKI_WINDOW_BACKEND}" // OpenGL version #define ANKI_GL_DESKTOP 1 #define ANKI_GL_ES 2 #if ANKI_OS == ANKI_OS_LINUX \ || ANKI_OS == ANKI_OS_MACOS \ || ANKI_OS == ANKI_OS_WINDOWS # define ANKI_GL ANKI_GL_DESKTOP # define ANKI_GL_STR "ANKI_GL_DESKTOP" #else # define ANKI_GL ANKI_GL_ES # define ANKI_GL_STR "ANKI_GL_ES" #endif // Enable performance counters #define ANKI_ENABLE_COUNTERS ${_ANKI_ENABLE_COUNTERS} //============================================================================== // Engine config = //============================================================================== // General config #define ANKI_SAFE_ALIGNMENT 16 // Renderer and rendering related config options #define ANKI_RENDERER_MAX_TILES_X 32 #define ANKI_RENDERER_MAX_TILES_Y 32 #define ANKI_RENDERER_USE_MATERIAL_UBOS 0 // Scene config #define ANKI_SCENE_OPTIMAL_SCENE_NODES_COUNT 1024 #define ANKI_SCENE_ALLOCATOR_SIZE (1024 * 1024) #define ANKI_SCENE_FRAME_ALLOCATOR_SIZE (1024 * 512) /// @{ /// Used to optimize the initial vectors of VisibilityTestResults #define ANKI_FRUSTUMABLE_AVERAGE_VISIBLE_RENDERABLES_COUNT 16 #define ANKI_FRUSTUMABLE_AVERAGE_VISIBLE_LIGHTS_COUNT 8 /// @} /// If true then we can place spatials in a thread-safe way #define ANKI_CFG_OCTREE_THREAD_SAFE 1 // GL #define ANKI_GL_MAX_MIPMAPS 32 #define ANKI_GL_MAX_TEXTURE_LAYERS 32 #define ANKI_GL_MAX_SUB_DRAWCALLS 64 #define ANKI_GL_MAX_INSTANCES 32 //============================================================================== // Other = //============================================================================== #define ANKI_FILE __FILE__ #define ANKI_FUNC __func__ // Some compiler struff #if defined(__GNUC__) # define ANKI_LIKELY(x) __builtin_expect((x), 1) # define ANKI_UNLIKELY(x) __builtin_expect((x), 0) # define ANKI_RESTRICT __restrict # define ANKI_ATTRIBUTE_ALIGNED(attr_, al_) \ attr_ __attribute__ ((aligned (al_))) #else # define ANKI_LIKELY(x) ((x) == 1) # define ANKI_UNLIKELY(x) ((x) == 1) # define ANKI_RESTRICT #endif /// @} // Workaround some GCC C++11 problems #if ${_ANKI_GCC_TO_STRING_WORKAROUND} # include <sstream> namespace std { template<typename T> std::string to_string(const T x) { stringstream ss; ss << x; return ss.str(); } inline float stof(const string& str) { stringstream ss(str); float f; ss >> f; return f; } inline int stoi(const string& str) { stringstream ss(str); int i; ss >> i; return i; } } // end namespace std #endif #endif
{ "content_hash": "adfbd3eb8dc4c269adb26c06b7bdb3b1", "timestamp": "", "source": "github", "line_count": 173, "max_line_length": 80, "avg_line_length": 25.00578034682081, "alnum_prop": 0.6331484049930652, "repo_name": "svn2github/anki-3d-engine", "id": "f14f4d66dbc8b4fb261e5bb274d94b53c7564c3f", "size": "4920", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "include/anki/Config.h.cmake", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "123080" }, { "name": "C++", "bytes": "1205463" }, { "name": "Objective-C", "bytes": "12007" }, { "name": "Python", "bytes": "1099" }, { "name": "Shell", "bytes": "1019" } ], "symlink_target": "" }
package com.cinchapi.concourse.test; /** * A marker interface for end-to-end tests of Concourse {@link Plugin plugins}. * <p> * Test cases that implement this interface will run any plugins on the current * classpath in distinct JVM containers. * </p> * * @author Jeff Nelson */ public interface PluginTest {}
{ "content_hash": "2bdb49a479fce819b8e3c6386a336855", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 79, "avg_line_length": 24.692307692307693, "alnum_prop": 0.7165109034267912, "repo_name": "kylycht/concourse", "id": "476b213b6edb55b035a504d4170e60a5f407c066", "size": "925", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "concourse-ete-test-core/src/main/java/com/cinchapi/concourse/test/PluginTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "6985" }, { "name": "Groff", "bytes": "47944" }, { "name": "Groovy", "bytes": "98681" }, { "name": "HTML", "bytes": "36688" }, { "name": "Java", "bytes": "3541395" }, { "name": "Makefile", "bytes": "123" }, { "name": "PHP", "bytes": "2569904" }, { "name": "Python", "bytes": "178166" }, { "name": "Ruby", "bytes": "270835" }, { "name": "Shell", "bytes": "124127" }, { "name": "Smarty", "bytes": "1323" }, { "name": "Thrift", "bytes": "143368" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>NUnitCommon - FAKE - F# Make</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content="Steffen Forkmann, Mauricio Scheffer, Colin Bull"> <script src="https://code.jquery.com/jquery-1.8.0.js"></script> <script src="https://code.jquery.com/ui/1.8.23/jquery-ui.js"></script> <script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/js/bootstrap.min.js"></script> <script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet"> <link type="text/css" rel="stylesheet" href="http://fsharp.github.io/FAKE/content/style.css" /> <script type="text/javascript" src="http://fsharp.github.io/FAKE/content/tips.js"></script> <!-- HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="masthead"> <ul class="nav nav-pills pull-right"> <li><a href="http://fsharp.org">fsharp.org</a></li> <li><a href="http://github.com/fsharp/fake">github page</a></li> </ul> <h3 class="muted"><a href="http://fsharp.github.io/FAKE/index.html">FAKE - F# Make</a></h3> </div> <hr /> <div class="row"> <div class="span9" id="main"> <h1>NUnitCommon</h1> <div class="xmldoc"> <p>Contains types and utility functions relaited to running <a href="http://www.nunit.org/">NUnit</a> unit tests.</p> </div> <!-- Render nested types and modules, if there are any --> <h2>Nested types and modules</h2> <div> <table class="table table-bordered type-list"> <thead> <tr><td>Type</td><td>Description</td></tr> </thead> <tbody> <tr> <td class="type-name"> <a href="fake-nunitcommon-nunitdomainmodel.html">NUnitDomainModel</a> </td> <td class="xmldoc"><p>The /domain option controls of the creation of AppDomains for running tests. See <a href="http://www.nunit.org/index.php?p=consoleCommandLine&amp;r=2.6.4">NUnit-Console Command Line Options</a></p> </td> </tr> <tr> <td class="type-name"> <a href="fake-nunitcommon-nuniterrorlevel.html">NUnitErrorLevel</a> </td> <td class="xmldoc"><p>Option which allows to specify if a NUnit error should break the build.</p> </td> </tr> <tr> <td class="type-name"> <a href="fake-nunitcommon-nunitparams.html">NUnitParams</a> </td> <td class="xmldoc"><p>The <a href="http://www.nunit.org/">NUnit</a> Console Parameters type. FAKE will use <a href="fake-nunitcommon.html">NUnitDefaults</a> for values not provided.</p> <p>For reference, see: <a href="http://www.nunit.org/index.php?p=consoleCommandLine&amp;r=2.6.4">NUnit-Console Command Line Options</a></p> </td> </tr> <tr> <td class="type-name"> <a href="fake-nunitcommon-nunitprocessmodel.html">NUnitProcessModel</a> </td> <td class="xmldoc"><p>Process model for nunit to use, see <a href="http://www.nunit.org/index.php?p=projectEditor&amp;r=2.6.4">Project Editor</a></p> </td> </tr> </tbody> </table> </div> <h3>Functions and values</h3> <table class="table table-bordered member-list"> <thead> <tr><td>Function or value</td><td>Description</td></tr> </thead> <tbody> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '462', 462)" onmouseover="showTip(event, '462', 462)"> NUnitDefaults </code> <div class="tip" id="462"> <strong>Signature:</strong> NUnitParams<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/UnitTest/NUnit/Common.fs#L124-124" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> <p>The <a href="fake-nunitcommon-nunitparams.html">NUnitParams</a> default parameters.</p> <h2>Defaults</h2> <ul> <li><code>IncludeCategory</code> - <code>""</code></li> <li><code>ExcludeCategory</code> - <code>""</code></li> <li><code>ToolPath</code> - The <code>nunit-console.exe</code> path if it exists in a subdirectory of the current directory.</li> <li><code>ToolName</code> - <code>"nunit-console.exe"</code></li> <li><code>DontTestInNewThread</code>- <code>false</code></li> <li><code>StopOnError</code> - <code>false</code></li> <li><code>OutputFile</code> - <code>"TestResult.xml"</code></li> <li><code>Out</code> - <code>""</code></li> <li><code>ErrorOutputFile</code> - <code>""</code></li> <li><code>WorkingDir</code> - <code>""</code></li> <li><code>Framework</code> - <code>""</code></li> <li><code>ProcessModel</code> - <code>DefaultProcessModel</code></li> <li><code>ShowLabels</code> - <code>true</code></li> <li><code>XsltTransformFile</code> - <code>""</code></li> <li><code>TimeOut</code> - 5 minutes</li> <li><code>DisableShadowCopy</code> - <code>false</code></li> <li><code>Domain</code> - <code>DefaultDomainModel</code></li> <li><code>ErrorLevel</code> - <code>Error</code></li> <li><code>Fixture</code> - <code>""</code></li> </ul> </td> </tr> </tbody> </table> <h3>Active patterns</h3> <table class="table table-bordered member-list"> <thead> <tr><td>Active pattern</td><td>Description</td></tr> </thead> <tbody> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '463', 463)" onmouseover="showTip(event, '463', 463)"> ( |OK|TestsFailed|FatalError| ) (...) </code> <div class="tip" id="463"> <strong>Signature:</strong> errorCode:int -&gt; Choice&lt;unit,unit,string&gt;<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/UnitTest/NUnit/Common.fs#L178-178" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> <p>NUnit console returns negative error codes for errors and sum of failed, ignored and exceptional tests otherwise. Zero means that all tests passed.</p> </td> </tr> </tbody> </table> </div> <div class="span3"> <a href="http://fsharp.github.io/FAKE/index.html"> <img src="http://fsharp.github.io/FAKE/pics/logo.png" style="width:140px;height:140px;margin:10px 0px 0px 35px;border-style:none;" /> </a> <ul class="nav nav-list" id="menu"> <li class="nav-header">FAKE - F# Make</li> <li class="divider"></li> <li><a href="http://fsharp.github.io/FAKE/index.html">Home page</a></li> <li class="divider"></li> <li><a href="https://www.nuget.org/packages/FAKE">Get FAKE - F# Make via NuGet</a></li> <li><a href="http://github.com/fsharp/fake">Source Code on GitHub</a></li> <li><a href="http://github.com/fsharp/fake/blob/master/License.txt">License (Apache 2)</a></li> <li><a href="http://fsharp.github.io/FAKE/RELEASE_NOTES.html">Release Notes</a></li> <li><a href="http://fsharp.github.io/FAKE//contributing.html">Contributing to FAKE - F# Make</a></li> <li><a href="http://fsharp.github.io/FAKE/users.html">Who is using FAKE?</a></li> <li><a href="http://stackoverflow.com/questions/tagged/f%23-fake">Ask a question</a></li> <li class="nav-header">Tutorials</li> <li><a href="http://fsharp.github.io/FAKE/gettingstarted.html">Getting started</a></li> <li><a href="http://fsharp.github.io/FAKE/cache.html">Build script caching</a></li> <li class="divider"></li> <li><a href="http://fsharp.github.io/FAKE/nuget.html">NuGet package restore</a></li> <li><a href="http://fsharp.github.io/FAKE/fxcop.html">Using FxCop in a build</a></li> <li><a href="http://fsharp.github.io/FAKE/assemblyinfo.html">Generating AssemblyInfo</a></li> <li><a href="http://fsharp.github.io/FAKE/create-nuget-package.html">Create NuGet packages</a></li> <li><a href="http://fsharp.github.io/FAKE/specifictargets.html">Running specific targets</a></li> <li><a href="http://fsharp.github.io/FAKE/commandline.html">Running FAKE from command line</a></li> <li><a href="http://fsharp.github.io/FAKE/parallel-build.html">Running targets in parallel</a></li> <li><a href="http://fsharp.github.io/FAKE/fsc.html">Using the F# compiler from FAKE</a></li> <li><a href="http://fsharp.github.io/FAKE/customtasks.html">Creating custom tasks</a></li> <li><a href="http://fsharp.github.io/FAKE/soft-dependencies.html">Soft dependencies</a></li> <li><a href="http://fsharp.github.io/FAKE/teamcity.html">TeamCity integration</a></li> <li><a href="http://fsharp.github.io/FAKE/canopy.html">Running canopy tests</a></li> <li><a href="http://fsharp.github.io/FAKE/octopusdeploy.html">Octopus Deploy</a></li> <li><a href="http://fsharp.github.io/FAKE/typescript.html">TypeScript support</a></li> <li><a href="http://fsharp.github.io/FAKE/azurewebjobs.html">Azure WebJobs support</a></li> <li><a href="http://fsharp.github.io/FAKE/azurecloudservices.html">Azure Cloud Services support</a></li> <li><a href="http://fsharp.github.io/FAKE/fluentmigrator.html">FluentMigrator support</a></li> <li><a href="http://fsharp.github.io/FAKE/androidpublisher.html">Android publisher</a></li> <li><a href="http://fsharp.github.io/FAKE/watch.html">File Watcher</a></li> <li><a href="http://fsharp.github.io/FAKE/wix.html">WiX Setup Generation</a></li> <li class="divider"></li> <li><a href="http://fsharp.github.io/FAKE/deploy.html">Fake.Deploy</a></li> <li><a href="http://fsharp.github.io/FAKE/iis.html">Fake.IIS</a></li> <li class="nav-header">Reference</li> <li><a href="http://fsharp.github.io/FAKE/apidocs/index.html">API Reference</a></li> </ul> </div> </div> </div> <a href="http://github.com/fsharp/fake"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_gray_6d6d6d.png" alt="Fork me on GitHub"></a> </body> </html>
{ "content_hash": "3ae670f10c34ae20df3908eb548dca54", "timestamp": "", "source": "github", "line_count": 229, "max_line_length": 229, "avg_line_length": 48.379912663755455, "alnum_prop": 0.6041158949363661, "repo_name": "hackle/AutoFixture", "id": "3f53d2489bf7542df435db13fc856dabeb6eb44c", "size": "11079", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Packages/FAKE.4.19.0/docs/apidocs/fake-nunitcommon.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "63" }, { "name": "C#", "bytes": "3842116" }, { "name": "F#", "bytes": "50701" }, { "name": "PowerShell", "bytes": "675" }, { "name": "Puppet", "bytes": "170" }, { "name": "Shell", "bytes": "1024" }, { "name": "Smalltalk", "bytes": "2018" }, { "name": "XSLT", "bytes": "17270" } ], "symlink_target": "" }
"""Foundational utilities common to many sql modules. """ import itertools import operator import re from .visitors import ClauseVisitor from .. import exc from .. import util coercions = None # type: types.ModuleType elements = None # type: types.ModuleType type_api = None # type: types.ModuleType PARSE_AUTOCOMMIT = util.symbol("PARSE_AUTOCOMMIT") NO_ARG = util.symbol("NO_ARG") class Immutable(object): """mark a ClauseElement as 'immutable' when expressions are cloned.""" def unique_params(self, *optionaldict, **kwargs): raise NotImplementedError("Immutable objects do not support copying") def params(self, *optionaldict, **kwargs): raise NotImplementedError("Immutable objects do not support copying") def _clone(self): return self def _from_objects(*elements): return itertools.chain(*[element._from_objects for element in elements]) @util.decorator def _generative(fn, *args, **kw): """Mark a method as generative.""" self = args[0]._generate() fn(self, *args[1:], **kw) return self def _clone(element, **kw): return element._clone() def _expand_cloned(elements): """expand the given set of ClauseElements to be the set of all 'cloned' predecessors. """ return itertools.chain(*[x._cloned_set for x in elements]) def _cloned_intersection(a, b): """return the intersection of sets a and b, counting any overlap between 'cloned' predecessors. The returned set is in terms of the entities present within 'a'. """ all_overlap = set(_expand_cloned(a)).intersection(_expand_cloned(b)) return set( elem for elem in a if all_overlap.intersection(elem._cloned_set) ) def _cloned_difference(a, b): all_overlap = set(_expand_cloned(a)).intersection(_expand_cloned(b)) return set( elem for elem in a if not all_overlap.intersection(elem._cloned_set) ) class _DialectArgView(util.collections_abc.MutableMapping): """A dictionary view of dialect-level arguments in the form <dialectname>_<argument_name>. """ def __init__(self, obj): self.obj = obj def _key(self, key): try: dialect, value_key = key.split("_", 1) except ValueError: raise KeyError(key) else: return dialect, value_key def __getitem__(self, key): dialect, value_key = self._key(key) try: opt = self.obj.dialect_options[dialect] except exc.NoSuchModuleError: raise KeyError(key) else: return opt[value_key] def __setitem__(self, key, value): try: dialect, value_key = self._key(key) except KeyError: raise exc.ArgumentError( "Keys must be of the form <dialectname>_<argname>" ) else: self.obj.dialect_options[dialect][value_key] = value def __delitem__(self, key): dialect, value_key = self._key(key) del self.obj.dialect_options[dialect][value_key] def __len__(self): return sum( len(args._non_defaults) for args in self.obj.dialect_options.values() ) def __iter__(self): return ( util.safe_kwarg("%s_%s" % (dialect_name, value_name)) for dialect_name in self.obj.dialect_options for value_name in self.obj.dialect_options[ dialect_name ]._non_defaults ) class _DialectArgDict(util.collections_abc.MutableMapping): """A dictionary view of dialect-level arguments for a specific dialect. Maintains a separate collection of user-specified arguments and dialect-specified default arguments. """ def __init__(self): self._non_defaults = {} self._defaults = {} def __len__(self): return len(set(self._non_defaults).union(self._defaults)) def __iter__(self): return iter(set(self._non_defaults).union(self._defaults)) def __getitem__(self, key): if key in self._non_defaults: return self._non_defaults[key] else: return self._defaults[key] def __setitem__(self, key, value): self._non_defaults[key] = value def __delitem__(self, key): del self._non_defaults[key] class DialectKWArgs(object): """Establish the ability for a class to have dialect-specific arguments with defaults and constructor validation. The :class:`.DialectKWArgs` interacts with the :attr:`.DefaultDialect.construct_arguments` present on a dialect. .. seealso:: :attr:`.DefaultDialect.construct_arguments` """ @classmethod def argument_for(cls, dialect_name, argument_name, default): """Add a new kind of dialect-specific keyword argument for this class. E.g.:: Index.argument_for("mydialect", "length", None) some_index = Index('a', 'b', mydialect_length=5) The :meth:`.DialectKWArgs.argument_for` method is a per-argument way adding extra arguments to the :attr:`.DefaultDialect.construct_arguments` dictionary. This dictionary provides a list of argument names accepted by various schema-level constructs on behalf of a dialect. New dialects should typically specify this dictionary all at once as a data member of the dialect class. The use case for ad-hoc addition of argument names is typically for end-user code that is also using a custom compilation scheme which consumes the additional arguments. :param dialect_name: name of a dialect. The dialect must be locatable, else a :class:`.NoSuchModuleError` is raised. The dialect must also include an existing :attr:`.DefaultDialect.construct_arguments` collection, indicating that it participates in the keyword-argument validation and default system, else :class:`.ArgumentError` is raised. If the dialect does not include this collection, then any keyword argument can be specified on behalf of this dialect already. All dialects packaged within SQLAlchemy include this collection, however for third party dialects, support may vary. :param argument_name: name of the parameter. :param default: default value of the parameter. .. versionadded:: 0.9.4 """ construct_arg_dictionary = DialectKWArgs._kw_registry[dialect_name] if construct_arg_dictionary is None: raise exc.ArgumentError( "Dialect '%s' does have keyword-argument " "validation and defaults enabled configured" % dialect_name ) if cls not in construct_arg_dictionary: construct_arg_dictionary[cls] = {} construct_arg_dictionary[cls][argument_name] = default @util.memoized_property def dialect_kwargs(self): """A collection of keyword arguments specified as dialect-specific options to this construct. The arguments are present here in their original ``<dialect>_<kwarg>`` format. Only arguments that were actually passed are included; unlike the :attr:`.DialectKWArgs.dialect_options` collection, which contains all options known by this dialect including defaults. The collection is also writable; keys are accepted of the form ``<dialect>_<kwarg>`` where the value will be assembled into the list of options. .. versionadded:: 0.9.2 .. versionchanged:: 0.9.4 The :attr:`.DialectKWArgs.dialect_kwargs` collection is now writable. .. seealso:: :attr:`.DialectKWArgs.dialect_options` - nested dictionary form """ return _DialectArgView(self) @property def kwargs(self): """A synonym for :attr:`.DialectKWArgs.dialect_kwargs`.""" return self.dialect_kwargs @util.dependencies("sqlalchemy.dialects") def _kw_reg_for_dialect(dialects, dialect_name): dialect_cls = dialects.registry.load(dialect_name) if dialect_cls.construct_arguments is None: return None return dict(dialect_cls.construct_arguments) _kw_registry = util.PopulateDict(_kw_reg_for_dialect) def _kw_reg_for_dialect_cls(self, dialect_name): construct_arg_dictionary = DialectKWArgs._kw_registry[dialect_name] d = _DialectArgDict() if construct_arg_dictionary is None: d._defaults.update({"*": None}) else: for cls in reversed(self.__class__.__mro__): if cls in construct_arg_dictionary: d._defaults.update(construct_arg_dictionary[cls]) return d @util.memoized_property def dialect_options(self): """A collection of keyword arguments specified as dialect-specific options to this construct. This is a two-level nested registry, keyed to ``<dialect_name>`` and ``<argument_name>``. For example, the ``postgresql_where`` argument would be locatable as:: arg = my_object.dialect_options['postgresql']['where'] .. versionadded:: 0.9.2 .. seealso:: :attr:`.DialectKWArgs.dialect_kwargs` - flat dictionary form """ return util.PopulateDict( util.portable_instancemethod(self._kw_reg_for_dialect_cls) ) def _validate_dialect_kwargs(self, kwargs): # validate remaining kwargs that they all specify DB prefixes if not kwargs: return for k in kwargs: m = re.match("^(.+?)_(.+)$", k) if not m: raise TypeError( "Additional arguments should be " "named <dialectname>_<argument>, got '%s'" % k ) dialect_name, arg_name = m.group(1, 2) try: construct_arg_dictionary = self.dialect_options[dialect_name] except exc.NoSuchModuleError: util.warn( "Can't validate argument %r; can't " "locate any SQLAlchemy dialect named %r" % (k, dialect_name) ) self.dialect_options[dialect_name] = d = _DialectArgDict() d._defaults.update({"*": None}) d._non_defaults[arg_name] = kwargs[k] else: if ( "*" not in construct_arg_dictionary and arg_name not in construct_arg_dictionary ): raise exc.ArgumentError( "Argument %r is not accepted by " "dialect %r on behalf of %r" % (k, dialect_name, self.__class__) ) else: construct_arg_dictionary[arg_name] = kwargs[k] class Generative(object): """Allow a ClauseElement to generate itself via the @_generative decorator. """ def _generate(self): s = self.__class__.__new__(self.__class__) s.__dict__ = self.__dict__.copy() return s class Executable(Generative): """Mark a ClauseElement as supporting execution. :class:`.Executable` is a superclass for all "statement" types of objects, including :func:`select`, :func:`delete`, :func:`update`, :func:`insert`, :func:`text`. """ supports_execution = True _execution_options = util.immutabledict() _bind = None @_generative def execution_options(self, **kw): """ Set non-SQL options for the statement which take effect during execution. Execution options can be set on a per-statement or per :class:`.Connection` basis. Additionally, the :class:`.Engine` and ORM :class:`~.orm.query.Query` objects provide access to execution options which they in turn configure upon connections. The :meth:`execution_options` method is generative. A new instance of this statement is returned that contains the options:: statement = select([table.c.x, table.c.y]) statement = statement.execution_options(autocommit=True) Note that only a subset of possible execution options can be applied to a statement - these include "autocommit" and "stream_results", but not "isolation_level" or "compiled_cache". See :meth:`.Connection.execution_options` for a full list of possible options. .. seealso:: :meth:`.Connection.execution_options` :meth:`.Query.execution_options` :meth:`.Executable.get_execution_options` """ if "isolation_level" in kw: raise exc.ArgumentError( "'isolation_level' execution option may only be specified " "on Connection.execution_options(), or " "per-engine using the isolation_level " "argument to create_engine()." ) if "compiled_cache" in kw: raise exc.ArgumentError( "'compiled_cache' execution option may only be specified " "on Connection.execution_options(), not per statement." ) self._execution_options = self._execution_options.union(kw) def get_execution_options(self): """ Get the non-SQL options which will take effect during execution. .. versionadded:: 1.3 .. seealso:: :meth:`.Executable.execution_options` """ return self._execution_options def execute(self, *multiparams, **params): """Compile and execute this :class:`.Executable`.""" e = self.bind if e is None: label = getattr(self, "description", self.__class__.__name__) msg = ( "This %s is not directly bound to a Connection or Engine. " "Use the .execute() method of a Connection or Engine " "to execute this construct." % label ) raise exc.UnboundExecutionError(msg) return e._execute_clauseelement(self, multiparams, params) def scalar(self, *multiparams, **params): """Compile and execute this :class:`.Executable`, returning the result's scalar representation. """ return self.execute(*multiparams, **params).scalar() @property def bind(self): """Returns the :class:`.Engine` or :class:`.Connection` to which this :class:`.Executable` is bound, or None if none found. This is a traversal which checks locally, then checks among the "from" clauses of associated objects until a bound engine or connection is found. """ if self._bind is not None: return self._bind for f in _from_objects(self): if f is self: continue engine = f.bind if engine is not None: return engine else: return None class SchemaEventTarget(object): """Base class for elements that are the targets of :class:`.DDLEvents` events. This includes :class:`.SchemaItem` as well as :class:`.SchemaType`. """ def _set_parent(self, parent): """Associate with this SchemaEvent's parent object.""" def _set_parent_with_dispatch(self, parent): self.dispatch.before_parent_attach(self, parent) self._set_parent(parent) self.dispatch.after_parent_attach(self, parent) class SchemaVisitor(ClauseVisitor): """Define the visiting for ``SchemaItem`` objects.""" __traverse_options__ = {"schema_visitor": True} class ColumnCollection(object): """Collection of :class:`.ColumnElement` instances, typically for selectables. The :class:`.ColumnCollection` has both mapping- and sequence- like behaviors. A :class:`.ColumnCollection` usually stores :class:`.Column` objects, which are then accessible both via mapping style access as well as attribute access style. The name for which a :class:`.Column` would be present is normally that of the :paramref:`.Column.key` parameter, however depending on the context, it may be stored under a special label name:: >>> from sqlalchemy import Column, Integer >>> from sqlalchemy.sql import ColumnCollection >>> x, y = Column('x', Integer), Column('y', Integer) >>> cc = ColumnCollection(columns=[x, y]) >>> cc.x Column('x', Integer(), table=None) >>> cc.y Column('y', Integer(), table=None) >>> cc['x'] Column('x', Integer(), table=None) >>> cc['y'] :class`.ColumnCollection` also indexes the columns in order and allows them to be accessible by their integer position:: >>> cc[0] Column('x', Integer(), table=None) >>> cc[1] Column('y', Integer(), table=None) .. versionadded:: 1.4 :class:`.ColumnCollection` allows integer-based index access to the collection. Iterating the collection yields the column expressions in order:: >>> list(cc) [Column('x', Integer(), table=None), Column('y', Integer(), table=None)] The base :class:`.ColumnCollection` object can store duplicates, which can mean either two columns with the same key, in which case the column returned by key access is **arbitrary**:: >>> x1, x2 = Column('x', Integer), Column('x', Integer) >>> cc = ColumnCollection(columns=[x1, x2]) >>> list(cc) [Column('x', Integer(), table=None), Column('x', Integer(), table=None)] >>> cc['x'] is x1 False >>> cc['x'] is x2 True Or it can also mean the same column multiple times. These cases are supported as :class:`.ColumnCollection` is used to represent the columns in a SELECT statement which may include duplicates. A special subclass :class:`.DedupeColumnCollection` exists which instead maintains SQLAlchemy's older behavior of not allowing duplicates; this collection is used for schema level objects like :class:`.Table` and :class:`.PrimaryKeyConstraint` where this deduping is helpful. The :class:`.DedupeColumnCollection` class also has additional mutation methods as the schema constructs have more use cases that require removal and replacement of columns. .. versionchanged:: 1.4 :class:`.ColumnCollection` now stores duplicate column keys as well as the same column in multiple positions. The :class:`.DedupeColumnCollection` class is added to maintain the former behavior in those cases where deduplication as well as additional replace/remove operations are needed. """ __slots__ = "_collection", "_index", "_colset" def __init__(self, columns=None): object.__setattr__(self, "_colset", set()) object.__setattr__(self, "_index", {}) object.__setattr__(self, "_collection", []) if columns: self._initial_populate(columns) def _initial_populate(self, iter_): self._populate_separate_keys(iter_) @property def _all_columns(self): return [col for (k, col) in self._collection] def keys(self): return [k for (k, col) in self._collection] def __len__(self): return len(self._collection) def __iter__(self): # turn to a list first to maintain over a course of changes return iter([col for k, col in self._collection]) def __getitem__(self, key): try: return self._index[key] except KeyError: if isinstance(key, util.int_types): raise IndexError(key) else: raise def __getattr__(self, key): try: return self._index[key] except KeyError: raise AttributeError(key) def __contains__(self, key): if key not in self._index: if not isinstance(key, util.string_types): raise exc.ArgumentError( "__contains__ requires a string argument" ) return False else: return True def compare(self, other): for l, r in util.zip_longest(self, other): if l is not r: return False else: return True def __eq__(self, other): return self.compare(other) def get(self, key, default=None): if key in self._index: return self._index[key] else: return default def __str__(self): return repr([str(c) for c in self]) def __setitem__(self, key, value): raise NotImplementedError() def __delitem__(self, key): raise NotImplementedError() def __setattr__(self, key, obj): raise NotImplementedError() def clear(self): raise NotImplementedError() def remove(self, column): raise NotImplementedError() def update(self, iter_): raise NotImplementedError() __hash__ = None def _populate_separate_keys(self, iter_): """populate from an iterator of (key, column)""" cols = list(iter_) self._collection[:] = cols self._colset.update(c for k, c in self._collection) self._index.update( (idx, c) for idx, (k, c) in enumerate(self._collection) ) self._index.update({k: col for k, col in reversed(self._collection)}) def add(self, column, key=None): if key is None: key = column.key l = len(self._collection) self._collection.append((key, column)) self._colset.add(column) self._index[l] = column if key not in self._index: self._index[key] = column def __getstate__(self): return {"_collection": self._collection, "_index": self._index} def __setstate__(self, state): object.__setattr__(self, "_index", state["_index"]) object.__setattr__(self, "_collection", state["_collection"]) object.__setattr__( self, "_colset", {col for k, col in self._collection} ) def contains_column(self, col): return col in self._colset def as_immutable(self): return ImmutableColumnCollection(self) def corresponding_column(self, column, require_embedded=False): """Given a :class:`.ColumnElement`, return the exported :class:`.ColumnElement` object from this :class:`.ColumnCollection` which corresponds to that original :class:`.ColumnElement` via a common ancestor column. :param column: the target :class:`.ColumnElement` to be matched :param require_embedded: only return corresponding columns for the given :class:`.ColumnElement`, if the given :class:`.ColumnElement` is actually present within a sub-element of this :class:`.Selectable`. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this :class:`.Selectable`. .. seealso:: :meth:`.Selectable.corresponding_column` - invokes this method against the collection returned by :attr:`.Selectable.exported_columns`. .. versionchanged:: 1.4 the implementation for ``corresponding_column`` was moved onto the :class:`.ColumnCollection` itself. """ def embedded(expanded_proxy_set, target_set): for t in target_set.difference(expanded_proxy_set): if not set(_expand_cloned([t])).intersection( expanded_proxy_set ): return False return True # don't dig around if the column is locally present if column in self._colset: return column col, intersect = None, None target_set = column.proxy_set cols = [c for (k, c) in self._collection] for c in cols: expanded_proxy_set = set(_expand_cloned(c.proxy_set)) i = target_set.intersection(expanded_proxy_set) if i and ( not require_embedded or embedded(expanded_proxy_set, target_set) ): if col is None: # no corresponding column yet, pick this one. col, intersect = c, i elif len(i) > len(intersect): # 'c' has a larger field of correspondence than # 'col'. i.e. selectable.c.a1_x->a1.c.x->table.c.x # matches a1.c.x->table.c.x better than # selectable.c.x->table.c.x does. col, intersect = c, i elif i == intersect: # they have the same field of correspondence. see # which proxy_set has fewer columns in it, which # indicates a closer relationship with the root # column. Also take into account the "weight" # attribute which CompoundSelect() uses to give # higher precedence to columns based on vertical # position in the compound statement, and discard # columns that have no reference to the target # column (also occurs with CompoundSelect) col_distance = util.reduce( operator.add, [ sc._annotations.get("weight", 1) for sc in col._uncached_proxy_set() if sc.shares_lineage(column) ], ) c_distance = util.reduce( operator.add, [ sc._annotations.get("weight", 1) for sc in c._uncached_proxy_set() if sc.shares_lineage(column) ], ) if c_distance < col_distance: col, intersect = c, i return col class DedupeColumnCollection(ColumnCollection): """A :class:`.ColumnCollection that maintains deduplicating behavior. This is useful by schema level objects such as :class:`.Table` and :class:`.PrimaryKeyConstraint`. The collection includes more sophisticated mutator methods as well to suit schema objects which require mutable column collections. .. versionadded: 1.4 """ def add(self, column, key=None): if key is not None and column.key != key: raise exc.ArgumentError( "DedupeColumnCollection requires columns be under " "the same key as their .key" ) key = column.key if key is None: raise exc.ArgumentError( "Can't add unnamed column to column collection" ) if key in self._index: existing = self._index[key] if existing is column: return self.replace(column) # pop out memoized proxy_set as this # operation may very well be occurring # in a _make_proxy operation util.memoized_property.reset(column, "proxy_set") else: l = len(self._collection) self._collection.append((key, column)) self._colset.add(column) self._index[l] = column self._index[key] = column def _populate_separate_keys(self, iter_): """populate from an iterator of (key, column)""" cols = list(iter_) replace_col = [] for k, col in cols: if col.key != k: raise exc.ArgumentError( "DedupeColumnCollection requires columns be under " "the same key as their .key" ) if col.name in self._index and col.key != col.name: replace_col.append(col) elif col.key in self._index: replace_col.append(col) else: self._index[k] = col self._collection.append((k, col)) self._colset.update(c for (k, c) in self._collection) self._index.update( (idx, c) for idx, (k, c) in enumerate(self._collection) ) for col in replace_col: self.replace(col) def extend(self, iter_): self._populate_separate_keys((col.key, col) for col in iter_) def remove(self, column): if column not in self._colset: raise ValueError( "Can't remove column %r; column is not in this collection" % column ) del self._index[column.key] self._colset.remove(column) self._collection[:] = [ (k, c) for (k, c) in self._collection if c is not column ] self._index.update( {idx: col for idx, (k, col) in enumerate(self._collection)} ) # delete higher index del self._index[len(self._collection)] def replace(self, column): """add the given column to this collection, removing unaliased versions of this column as well as existing columns with the same key. e.g.:: t = Table('sometable', metadata, Column('col1', Integer)) t.columns.replace(Column('col1', Integer, key='columnone')) will remove the original 'col1' from the collection, and add the new column under the name 'columnname'. Used by schema.Column to override columns during table reflection. """ remove_col = set() # remove up to two columns based on matches of name as well as key if column.name in self._index and column.key != column.name: other = self._index[column.name] if other.name == other.key: remove_col.add(other) if column.key in self._index: remove_col.add(self._index[column.key]) new_cols = [] replaced = False for k, col in self._collection: if col in remove_col: if not replaced: replaced = True new_cols.append((column.key, column)) else: new_cols.append((k, col)) if remove_col: self._colset.difference_update(remove_col) if not replaced: new_cols.append((column.key, column)) self._colset.add(column) self._collection[:] = new_cols self._index.clear() self._index.update( {idx: col for idx, (k, col) in enumerate(self._collection)} ) self._index.update(self._collection) class ImmutableColumnCollection(util.ImmutableContainer, ColumnCollection): __slots__ = ("_parent",) def __init__(self, collection): object.__setattr__(self, "_parent", collection) object.__setattr__(self, "_colset", collection._colset) object.__setattr__(self, "_index", collection._index) object.__setattr__(self, "_collection", collection._collection) def __getstate__(self): return {"_parent": self._parent} def __setstate__(self, state): parent = state["_parent"] self.__init__(parent) add = extend = remove = util.ImmutableContainer._immutable class ColumnSet(util.ordered_column_set): def contains_column(self, col): return col in self def extend(self, cols): for col in cols: self.add(col) def __add__(self, other): return list(self) + list(other) def __eq__(self, other): l = [] for c in other: for local in self: if c.shares_lineage(local): l.append(c == local) return elements.and_(*l) def __hash__(self): return hash(tuple(x for x in self)) def _bind_or_error(schemaitem, msg=None): bind = schemaitem.bind if not bind: name = schemaitem.__class__.__name__ label = getattr( schemaitem, "fullname", getattr(schemaitem, "name", None) ) if label: item = "%s object %r" % (name, label) else: item = "%s object" % name if msg is None: msg = ( "%s is not bound to an Engine or Connection. " "Execution can not proceed without a database to execute " "against." % item ) raise exc.UnboundExecutionError(msg) return bind
{ "content_hash": "71d723683dffa3ea8d979d19d80a0cb9", "timestamp": "", "source": "github", "line_count": 993, "max_line_length": 79, "avg_line_length": 33.152064451158104, "alnum_prop": 0.5808930741190765, "repo_name": "wujuguang/sqlalchemy", "id": "da384bdabcb34703efd87c183cfb8fb5fd9603aa", "size": "33152", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/sqlalchemy/sql/base.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "45930" }, { "name": "Python", "bytes": "11287383" } ], "symlink_target": "" }
package com.cosylab.logging.engine.audience; import com.cosylab.logging.engine.log.ILogEntry; import com.cosylab.logging.engine.log.LogField; import com.cosylab.logging.engine.log.LogTypeHelper; /** * The audience for the science log: this accepts all the logs having * the audience set to SciLog and a level of NOTICE. * <P> * <I>Note</I>: an instance of this class should be acquired from * {@link AudienceInfo} * * @author acaproni * @since ACS 8.1.0 */ public class SciLogAudience implements Audience { /** * The audience as defined in the IDL */ private static final String audience = alma.log_audience.SCILOG.value; /** * The Audienceinfo for this audience */ private static final AudienceInfo info=AudienceInfo.SCILOG; /** * @see Audience */ @Override public AudienceInfo getInfo() { return SciLogAudience.info; } /** * @see Audience */ @Override public boolean matches(ILogEntry log){ return audience.equals(log.getField(LogField.AUDIENCE)) && log.getType()==LogTypeHelper.NOTICE; } }
{ "content_hash": "a5e97d4f613654f53a01d58f26655c07", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 71, "avg_line_length": 23.355555555555554, "alnum_prop": 0.7155090390104663, "repo_name": "csrg-utfsm/acscb", "id": "9a4a40f5b07f4a9ea250d7c1d50cf5beed6f88ac", "size": "1948", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "LGPL/CommonSoftware/jlogEngine/src/com/cosylab/logging/engine/audience/SciLogAudience.java", "mode": "33188", "license": "mit", "language": [ { "name": "Awk", "bytes": "633" }, { "name": "Batchfile", "bytes": "2346" }, { "name": "C", "bytes": "751150" }, { "name": "C++", "bytes": "7892598" }, { "name": "CSS", "bytes": "21364" }, { "name": "Elixir", "bytes": "906" }, { "name": "Emacs Lisp", "bytes": "1990066" }, { "name": "FreeMarker", "bytes": "7369" }, { "name": "GAP", "bytes": "14867" }, { "name": "Gnuplot", "bytes": "437" }, { "name": "HTML", "bytes": "1857062" }, { "name": "Haskell", "bytes": "764" }, { "name": "Java", "bytes": "13573740" }, { "name": "JavaScript", "bytes": "19058" }, { "name": "Lex", "bytes": "5101" }, { "name": "Makefile", "bytes": "1624406" }, { "name": "Module Management System", "bytes": "4925" }, { "name": "Objective-C", "bytes": "3223" }, { "name": "PLSQL", "bytes": "9496" }, { "name": "Perl", "bytes": "120411" }, { "name": "Python", "bytes": "4191000" }, { "name": "Roff", "bytes": "9920" }, { "name": "Shell", "bytes": "1198375" }, { "name": "Smarty", "bytes": "21615" }, { "name": "Tcl", "bytes": "227078" }, { "name": "XSLT", "bytes": "100454" }, { "name": "Yacc", "bytes": "5006" } ], "symlink_target": "" }
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <TextView android:id="@+id/testua" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="@string/hello_world" /> </RelativeLayout>
{ "content_hash": "d993250dbb31db3e53222129ba7920a1", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 74, "avg_line_length": 36.666666666666664, "alnum_prop": 0.6690909090909091, "repo_name": "CarlosIribarren/Ejemplos-Examples", "id": "dd1c2d4d3a123539cbaa7faf7c477b747132f1a4", "size": "550", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Android/AndroidPoligonoak2/res/layout/activity_main.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "110405" }, { "name": "C", "bytes": "48796" }, { "name": "CSS", "bytes": "93962" }, { "name": "HTML", "bytes": "85221" }, { "name": "Java", "bytes": "971790" }, { "name": "JavaScript", "bytes": "118893" }, { "name": "PHP", "bytes": "175996" }, { "name": "PLSQL", "bytes": "4877" }, { "name": "Shell", "bytes": "20208" }, { "name": "Visual Basic", "bytes": "155712" }, { "name": "XSLT", "bytes": "3471" } ], "symlink_target": "" }
""" >>> pingpong = thriftpy.load("pingpong.thrift") >>> >>> class Dispatcher(object): >>> def ping(self): >>> return "pong" >>> server = make_server(pingpong.PingPong, Dispatcher()) >>> server.listen(6000) >>> client = ioloop.IOLoop.current().run_sync( lambda: make_client(pingpong.PingPong, '127.0.0.1', 6000)) >>> ioloop.IOLoop.current().run_sync(client.ping) 'pong' """ from __future__ import absolute_import from contextlib import contextmanager from tornado import tcpserver, ioloop, iostream, gen from io import BytesIO from datetime import timedelta from .transport import TTransportException, TTransportBase from .transport.memory import TMemoryBuffer from .thrift import TApplicationException, TProcessor, TClient # TODO need TCyTornadoStreamTransport to work with cython binary protocol from .protocol.binary import TBinaryProtocolFactory import logging import socket import struct import toro class TTornadoStreamTransport(TTransportBase): """a framed, buffered transport over a Tornado stream""" DEFAULT_CONNECT_TIMEOUT = timedelta(seconds=1) DEFAULT_READ_TIMEOUT = timedelta(seconds=1) def __init__(self, host, port, stream=None, io_loop=None, read_timeout=DEFAULT_READ_TIMEOUT): self.host = host self.port = port self.io_loop = io_loop or ioloop.IOLoop.current() self.read_timeout = read_timeout self.is_queuing_reads = False self.read_queue = [] self.__wbuf = BytesIO() self._read_lock = toro.Lock() # servers provide a ready-to-go stream self.stream = stream if self.stream is not None: self._set_close_callback() def with_timeout(self, timeout, future): return gen.with_timeout(timeout, future, self.io_loop) @gen.coroutine def open(self, timeout=DEFAULT_CONNECT_TIMEOUT): logging.debug('socket connecting') sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) self.stream = iostream.IOStream(sock) try: yield self.with_timeout(timeout, self.stream.connect( (self.host, self.port))) except (socket.error, OSError, IOError): message = 'could not connect to {}:{}'.format(self.host, self.port) raise TTransportException( type=TTransportException.NOT_OPEN, message=message) self._set_close_callback() raise gen.Return(self) def _set_close_callback(self): self.stream.set_close_callback(self.close) def close(self): # don't raise if we intend to close self.stream.set_close_callback(None) self.stream.close() def read(self, _): # The generated code for Tornado shouldn't do individual reads -- only # frames at a time assert False, "you're doing it wrong" @contextmanager def io_exception_context(self): try: yield except (socket.error, OSError, IOError) as e: raise TTransportException( type=TTransportException.END_OF_FILE, message=str(e)) except iostream.StreamBufferFullError as e: raise TTransportException( type=TTransportException.UNKNOWN, message=str(e)) except gen.TimeoutError as e: raise TTransportException( type=TTransportException.TIMED_OUT, message=str(e)) @gen.coroutine def read_frame(self): # IOStream processes reads one at a time with (yield self._read_lock.acquire()): with self.io_exception_context(): frame_header = yield self._read_bytes(4) if len(frame_header) == 0: raise iostream.StreamClosedError( 'Read zero bytes from stream') frame_length, = struct.unpack('!i', frame_header) logging.debug('received frame header, frame length = %d', frame_length) frame = yield self._read_bytes(frame_length) logging.debug('received frame payload: %r', frame) raise gen.Return(frame) def _read_bytes(self, n): return self.with_timeout(self.read_timeout, self.stream.read_bytes(n)) def write(self, buf): self.__wbuf.write(buf) def flush(self): frame = self.__wbuf.getvalue() # reset wbuf before write/flush to preserve state on underlying failure frame_length = struct.pack('!i', len(frame)) self.__wbuf = BytesIO() with self.io_exception_context(): return self.stream.write(frame_length + frame) class TTornadoServer(tcpserver.TCPServer): def __init__(self, processor, iprot_factory, oprot_factory=None, transport_read_timeout=TTornadoStreamTransport.DEFAULT_READ_TIMEOUT, # noqa *args, **kwargs): super(TTornadoServer, self).__init__(*args, **kwargs) self._processor = processor self._iprot_factory = iprot_factory self._oprot_factory = (oprot_factory if oprot_factory is not None else iprot_factory) self.transport_read_timeout = transport_read_timeout @gen.coroutine def handle_stream(self, stream, address): host, port = address trans = TTornadoStreamTransport( host=host, port=port, stream=stream, io_loop=self.io_loop, read_timeout=self.transport_read_timeout) try: oprot = self._oprot_factory.get_protocol(trans) iprot = self._iprot_factory.get_protocol(TMemoryBuffer()) while not trans.stream.closed(): # TODO: maybe read multiple frames in advance for concurrency try: frame = yield trans.read_frame() except TTransportException as e: if e.type == TTransportException.END_OF_FILE: break else: raise iprot.trans.setvalue(frame) api, seqid, result, call = self._processor.process_in(iprot) if isinstance(result, TApplicationException): self._processor.send_exception(oprot, api, result, seqid) else: try: result.success = yield gen.maybe_future(call()) except Exception as e: # raise if api don't have throws self._processor.handle_exception(e, result) self._processor.send_result(oprot, api, result, seqid) except Exception: logging.exception('thrift exception in handle_stream') trans.close() logging.info('client disconnected %s:%d', host, port) class TTornadoClient(TClient): @gen.coroutine def _recv(self, api): frame = yield self._oprot.trans.read_frame() self._iprot.trans.setvalue(frame) result = super(TTornadoClient, self)._recv(api) raise gen.Return(result) def close(self): self._oprot.trans.close() def make_server( service, handler, proto_factory=TBinaryProtocolFactory(), io_loop=None, transport_read_timeout=TTornadoStreamTransport.DEFAULT_READ_TIMEOUT): processor = TProcessor(service, handler) server = TTornadoServer(processor, iprot_factory=proto_factory, transport_read_timeout=transport_read_timeout, io_loop=io_loop) return server @gen.coroutine def make_client( service, host, port, proto_factory=TBinaryProtocolFactory(), io_loop=None, connect_timeout=TTornadoStreamTransport.DEFAULT_CONNECT_TIMEOUT, read_timeout=TTornadoStreamTransport.DEFAULT_READ_TIMEOUT): transport = TTornadoStreamTransport(host, port, io_loop=io_loop, read_timeout=read_timeout) iprot = proto_factory.get_protocol(TMemoryBuffer()) oprot = proto_factory.get_protocol(transport) yield transport.open(connect_timeout) client = TTornadoClient(service, iprot, oprot) raise gen.Return(client)
{ "content_hash": "7d43dff99f6b05eb3c59060b6ffc9307", "timestamp": "", "source": "github", "line_count": 225, "max_line_length": 93, "avg_line_length": 36.80888888888889, "alnum_prop": 0.6108427915962328, "repo_name": "importcjj/thriftpy", "id": "2006823ae30b6ece48853c1f2e70f48ee9877c80", "size": "8307", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "thriftpy/tornado.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "705" }, { "name": "Makefile", "bytes": "342" }, { "name": "Python", "bytes": "214653" }, { "name": "Thrift", "bytes": "22032" } ], "symlink_target": "" }
/** * @fileoverview Load native app or move to install page */ 'use strict'; var defineClass = require('tui-code-snippet/defineClass/defineClass'); var extend = require('tui-code-snippet/object/extend'); var sendHostname = require('tui-code-snippet/request/sendHostname'); var UAParser = require('ua-parser-js'); var Detector = require('./detectors'); var iOSDetector = require('./iosDetectors'); var EtcDetector = require('./etcDetectors'); var defaultOptions = { ios: { scheme: '', url: '' }, android: { scheme: '', url: '' } }; /** * Mobile App loader * @constructor * @class * @param {object} options - Option object * @param {boolean} [options.usageStatistics=true] - Let us know the hostname. If you don't want to send the hostname, please set to false. * @see AppLoader#exec * @example <caption>node, commonjs</caption> * // ES6 * import AppLoader from 'tui-app-loader'; // ES6 * * // CommonJS * const AppLoader = require('tui-app-loader'); // CommonJS * * // Browser * const appLoader = new tui.AppLoader(); * * const appLoader = new AppLoader(); * appLoader.exec(...); */ var AppLoader = defineClass( /** @lends AppLoader.prototype */ { init: function(options) { var agent = new UAParser().getResult(); var os = agent.os; this.agent = agent; this.ua = agent.ua; this.osName = os.name; this.osVersion = os.version; this.detector = null; options = extend( { usageStatistics: true }, options ); if (options.usageStatistics) { sendHostname('app-loader', 'UA-129987462-1'); } }, /** * Set Detector by OS * @private * @param {object} context The options */ _setDetector: function(context) { var osName = this.osName; var isAndroid = osName === 'Android'; var isIOS = osName === 'iOS'; if (isAndroid) { this._setAndroidDetector(context); } else if (isIOS && context.iosStoreURL) { this._setIOSDetector(); } else { this._setEtcDetector(context); } }, /** * Set IOS Detector * @private * @param {object} context The information for app */ _setIOSDetector: function() { var iosVersion = parseInt(this.osVersion, 10); if (iosVersion > 8) { this.detector = iOSDetector.iOS9AndLater; } else if (iosVersion === 8) { this.detector = iOSDetector.iOS8; } else { this.detector = iOSDetector.iOS7AndBefore; } }, /** * Set android Detector * @private * @param {object} context The information for app */ _setAndroidDetector: function(context) { if (context.intentURI && this.doesBrowserSupportIntent()) { this.detector = Detector.androidIntentDetector; } else { this.detector = Detector.androidSchemeDetector; } }, /** * Set EtcDetector * @private * @param {object} context The information for app */ _setEtcDetector: function(context) { this.detector = EtcDetector; setTimeout(function() { if (context.etcCallback) { context.etcCallback(); } }, 100); }, /** * Run selected detector * @private * @param {object} context The information for app */ _runDetector: function(context) { if (this.detector && this.detector !== EtcDetector) { this.detector.run(context); } }, /** * Whether the intent is supported * @returns {boolean} * @private */ doesBrowserSupportIntent: function() { return !/firefox|opr/i.test(this.ua); }, /** * Call app * @param {object} options The option for app * @param {object} options.ios IOS app information * @param {object} options.android Android information * @param {object} options.timerSet A timer time set for callback deley time * @param {Function} options.etcCallback If unsupportable mobile * @param {Function} options.notFoundCallback It not found * * @example * const loader = new AppLoader(); * loader.exec({ * ios: { * scheme: '<app-scheme>://', // iphone app scheme * url: 'https://itunes.apple.com/app/<id-app>', // app store url, * universalLink: 'app:///<universal-link>/' * }, * android: { * intentURI: 'intent://<action>#Intent;scheme=<app-scheme>;package=<package-name>;end' // android intent uri * }, * timerSet: { // optional values * ios: 2000, // default: 2000 * android: 1000 // default: 800 * }, * notFoundCallback: function() { // if not installed * alert('not found'); * }, * etcCallback: function() { // if not mobile * alert('etc'); * } * }); */ exec: function(options) { var timerSet, context; options = extend(defaultOptions, options); timerSet = options.timerSet; context = { urlScheme: options.ios.scheme, iosStoreURL: options.ios.url, universalLink: options.ios.universalLink, intentURI: options.android.intentURI, useIframe: options.android.useIframe, onErrorIframe: options.android.onErrorIframe, etcCallback: options.etcCallback, notFoundCallback: options.notFoundCallback }; this._setDetector(context); if (timerSet) { this._setTimerTime(timerSet); } this._runDetector(context); }, /** * Set timer time set * @param {object} timerSet A set of timer times * @private */ _setTimerTime: function(timerSet) { if (!this.detector.TIMEOUT) { this.detector.TIMEOUT = {}; } this.detector.TIMEOUT.IOS = timerSet.ios || this.detector.TIMEOUT.IOS; this.detector.TIMEOUT.ANDROID = timerSet.android || this.detector.TIMEOUT.ANDROID; } } ); module.exports = AppLoader;
{ "content_hash": "88ae5bbbc7b31e9388216dba1e27d06e", "timestamp": "", "source": "github", "line_count": 224, "max_line_length": 139, "avg_line_length": 27.178571428571427, "alnum_prop": 0.5827858081471747, "repo_name": "nhnent/fe.component-m-app-loader", "id": "be75ca8c6e5831b3debe2b86b504c8ab6653d634", "size": "6088", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/js/appLoader.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "138034" } ], "symlink_target": "" }
define({ "productVersion": "Produktversion: ", "kernelVersion": "Kerneversion: ", "_widgetLabel": "Om" });
{ "content_hash": "43b64fd69a301ead99a7b7ec008ae8e1", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 39, "avg_line_length": 22.4, "alnum_prop": 0.6428571428571429, "repo_name": "tmcgee/cmv-wab-widgets", "id": "9b29457e249cf7263a007c3ebbddd3c2be804843", "size": "112", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "wab/2.15/widgets/About/nls/da/strings.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1198579" }, { "name": "HTML", "bytes": "946685" }, { "name": "JavaScript", "bytes": "22190423" }, { "name": "Pascal", "bytes": "4207" }, { "name": "TypeScript", "bytes": "102918" } ], "symlink_target": "" }
package aQute.bnd.build; public interface ErrorDetails { }
{ "content_hash": "611a79d923b3c379e4e3c0b064618dc0", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 31, "avg_line_length": 12.2, "alnum_prop": 0.7704918032786885, "repo_name": "psoreide/bnd", "id": "e13e860c2ddf8ca96fbd21090c96cd6668ed4e1a", "size": "61", "binary": false, "copies": "14", "ref": "refs/heads/master", "path": "biz.aQute.bndlib/src/aQute/bnd/build/ErrorDetails.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5971" }, { "name": "Groovy", "bytes": "137212" }, { "name": "HTML", "bytes": "20589" }, { "name": "Java", "bytes": "4890082" }, { "name": "Shell", "bytes": "13535" }, { "name": "XSLT", "bytes": "24433" } ], "symlink_target": "" }
package com.izhbg.typz.sso.auth.dao; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.apache.log4j.Logger; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.GrantedAuthorityImpl; import org.springframework.security.core.userdetails.UserDetails; import com.izhbg.typz.sso.auth.SpringSecurityUserAuth; import com.izhbg.typz.sso.auth.dto.TXtAuthorities; import com.izhbg.typz.sso.auth.dto.TXtGnjsAuthorities; import com.izhbg.typz.sso.auth.dto.TXtYh; import com.izhbg.typz.sso.auth.dto.TXtYhGnjs; import com.izhbg.typz.sso.auth.manager.TXtAuthoritiesManager; import com.izhbg.typz.sso.auth.manager.TXtGnjsAuthoritiesManger; import com.izhbg.typz.sso.auth.manager.TXtYhGnjsManager; import com.izhbg.typz.sso.auth.manager.TXtYhManager; import com.izhbg.typz.sso.common.TreeNodeUtil; import com.izhbg.typz.sso.util.SpringContextWrapper; public class UserDao { protected static Logger logger = Logger.getLogger("UserDao"); private static final String QUERY_BY_YHDM_HQL = " from TXtYh where yhDm=? and yxBj=1 and scBj=2 "; private static final String QUERY_ALL_AUTHORITIES_SQL = " select authority_name from t_xt_authorities "; private static final String QUERY_RESOURCESNAMEBYAUTHORITIESNAME_SQL = " select b.resource_string from " + " t_xt_authorities_resources a, " + " t_xt_resources b, " + " t_xt_authorities c " + " where " + " a.resource_id = b.resource_id " + " and a.authority_id=c.authority_id " + " and c.authority_name=? "; private static final String QUERY_FINDPASSWORD_SQL = "select MM from t_xt_yh where YH_ID=?"; private static final String QUERY_FINDPERMISSIONS_SQL = "select * from t_xt_gnjs_zy"; private static final String QUERY_FINDROLES_SQL = "select js_dm as role from t_xt_yh_gnjs where YH_ID=?"; TXtYhManager tXtYhManager = (TXtYhManager) SpringContextWrapper.getBean("TXtYhManager"); /** * 根据username 获取唯一用户 * @param username * @return */ public SpringSecurityUserAuth loadUserByUserName(String username) { TXtYh tXtYh = tXtYhManager.findUnique(QUERY_BY_YHDM_HQL, username); if(tXtYh!=null){ return process(tXtYh); } logger.error("User does not exist!"); throw new RuntimeException("User does not exist!"); } /** * 设置权限 * @param auth * @return */ private SpringSecurityUserAuth process(TXtYh tXtYh){ SpringSecurityUserAuth userAuthResult = new SpringSecurityUserAuth(); userAuthResult.setAppId(tXtYh.getAppId()); userAuthResult.setDisplayName(tXtYh.getYhMc()); userAuthResult.setId(tXtYh.getYhId()); userAuthResult.setUsername(tXtYh.getYhDm()); userAuthResult.setPassword(tXtYh.getMm()); if(tXtYh.getScBj()==2) userAuthResult.setEnabled(true); else userAuthResult.setEnabled(false); if(tXtYh.getYxBj()==1) userAuthResult.setAccountNonLocked(true); else userAuthResult.setAccountNonLocked(false); // roles List<Map<String, Object>> roles = tXtYhManager.getJdbcTemplate().queryForList( QUERY_FINDROLES_SQL, tXtYh.getYhId()); userAuthResult.setRoles(roles); List<Map<String, Object>> permissions = null; String findsql = QUERY_FINDPERMISSIONS_SQL; if(roles!=null&&roles.size()>0){ findsql = findsql+" where "; String jsDm = ""; for(Map role:roles){ jsDm = role.get("role")+""; if(!jsDm.equals("")) findsql+=" JS_DM='"+jsDm+"' or"; } findsql = findsql.substring(0,findsql.length()-2); permissions = tXtYhManager.getJdbcTemplate().queryForList(findsql); } List<Map<String,Object>> txgJgYhList =tXtYhManager.getJdbcTemplate().queryForList("select * from t_xt_jg_yh where yh_id ='"+tXtYh.getYhId()+"'"); String jg_mc = ""; String jg_id = ""; if(txgJgYhList!=null&&txgJgYhList.size()>0) { Map map2 = txgJgYhList.get(0); Object obj = map2.get("jg_id"); if(obj!=null){ List<Map<String,Object>> txgJgList = tXtYhManager.getJdbcTemplate().queryForList("select jg_mc from t_xt_jg where jg_id ='"+obj+"'"); if(txgJgList!=null&&txgJgList.size()>0){ Map map3 = txgJgList.get(0); jg_mc = map3.get("jg_mc")+""; jg_id = obj+""; } } } userAuthResult.setDepName(jg_mc); userAuthResult.setDepId(jg_id); userAuthResult.setPermissions(permissions); //左侧功能树 TreeNodeUtil treeNodeUtil = new TreeNodeUtil(tXtYhManager.getJdbcTemplate(),tXtYh.getYhId()); userAuthResult.setTreeNode(treeNodeUtil.getTreeNode()); return userAuthResult; } /** * 根据username 获取用户资源权限 * @param username * @return */ public Collection<GrantedAuthority> loadUserAuthoritiesByUserName(String username) { TXtYhGnjsManager tXtYhGnjsManager = (TXtYhGnjsManager) SpringContextWrapper.getBean("TXtYhGnjsManager"); TXtGnjsAuthoritiesManger tXtGnjsAuthoritiesManger = (TXtGnjsAuthoritiesManger) SpringContextWrapper.getBean("TXtGnjsAuthoritiesManger"); TXtAuthoritiesManager tXtAuthoritiesManager = (TXtAuthoritiesManager) SpringContextWrapper.getBean("TXtAuthoritiesManager"); Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>(); //获取用户,获取用户角色,获取权限 TXtYh tXtYh = tXtYhManager.findUnique(QUERY_BY_YHDM_HQL, username); if(tXtYh!=null){ List<TXtYhGnjs> tXtYhGnjs = tXtYhGnjsManager.findBy("yhId", tXtYh.getYhId()); if(tXtYhGnjs!=null){ List<TXtGnjsAuthorities> tgauthorities = null; TXtAuthorities authorities = null; for(TXtYhGnjs gnjs:tXtYhGnjs){ tgauthorities = tXtGnjsAuthoritiesManger.findBy("roleId", gnjs.getJsDm()); if(tgauthorities!=null){ for(TXtGnjsAuthorities tgauthoritie:tgauthorities){ authorities = tXtAuthoritiesManager.findUniqueBy("authorityId", tgauthoritie.getAuthorityId()); if(authorities!=null) auths.add(new GrantedAuthorityImpl(authorities.getAuthorityName())); } } } } } return auths; } /** * 获取所有的资源权限 * @return */ public List<Map<String,Object>> loadAllAuthoritesName(){ List<Map<String,Object>> authoritesNames = tXtYhManager.getJdbcTemplate().queryForList(QUERY_ALL_AUTHORITIES_SQL); return authoritesNames; } /** * 获取资源名称 * @param authName * @return */ public List<Map<String,Object>> loadResourcesNameByAuthoritiesName(String authName){ List<Map<String,Object>> resourcesNames = tXtYhManager.getJdbcTemplate().queryForList(QUERY_RESOURCESNAMEBYAUTHORITIESNAME_SQL,authName); return resourcesNames; } }
{ "content_hash": "bb4c7a2c7de85f66311fb938cd2dac3f", "timestamp": "", "source": "github", "line_count": 182, "max_line_length": 153, "avg_line_length": 39.0989010989011, "alnum_prop": 0.6693367060146149, "repo_name": "izhbg/typz", "id": "11bc6df59827229c7f7847bf09c77fe8738352af", "size": "7232", "binary": false, "copies": "1", "ref": "refs/heads/shop_0.1", "path": "typz-all/typz-sso/src/main/java/com/izhbg/typz/sso/auth/dao/UserDao.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "553872" }, { "name": "CoffeeScript", "bytes": "105801" }, { "name": "FreeMarker", "bytes": "1156" }, { "name": "HTML", "bytes": "579555" }, { "name": "Java", "bytes": "1633285" }, { "name": "JavaScript", "bytes": "4805618" }, { "name": "Shell", "bytes": "1345" } ], "symlink_target": "" }
#include "SkImage_Base.h" #include "SkImagePriv.h" #include "SkBitmap.h" #include "SkCanvas.h" #include "SkData.h" #include "SkDecodingImageGenerator.h" #include "SkMallocPixelRef.h" class SkImage_Raster : public SkImage_Base { public: static bool ValidArgs(const Info& info, size_t rowBytes) { const int maxDimension = SK_MaxS32 >> 2; const size_t kMaxPixelByteSize = SK_MaxS32; if (info.fWidth < 0 || info.fHeight < 0) { return false; } if (info.fWidth > maxDimension || info.fHeight > maxDimension) { return false; } if ((unsigned)info.fColorType > (unsigned)kLastEnum_SkColorType) { return false; } if ((unsigned)info.fAlphaType > (unsigned)kLastEnum_SkAlphaType) { return false; } if (kUnknown_SkColorType == info.colorType()) { return false; } // TODO: check colorspace if (rowBytes < SkImageMinRowBytes(info)) { return false; } int64_t size = (int64_t)info.fHeight * rowBytes; if (size > (int64_t)kMaxPixelByteSize) { return false; } return true; } static SkImage* NewEmpty(); SkImage_Raster(const SkImageInfo&, SkData*, size_t rb); virtual ~SkImage_Raster(); virtual void onDraw(SkCanvas*, SkScalar, SkScalar, const SkPaint*) const SK_OVERRIDE; virtual void onDrawRectToRect(SkCanvas*, const SkRect*, const SkRect&, const SkPaint*) const SK_OVERRIDE; virtual bool onReadPixels(SkBitmap*, const SkIRect&) const SK_OVERRIDE; virtual const void* onPeekPixels(SkImageInfo*, size_t* /*rowBytes*/) const SK_OVERRIDE; virtual bool getROPixels(SkBitmap*) const SK_OVERRIDE; // exposed for SkSurface_Raster via SkNewImageFromPixelRef SkImage_Raster(const SkImageInfo&, SkPixelRef*, size_t rowBytes); SkPixelRef* getPixelRef() const { return fBitmap.pixelRef(); } virtual SkShader* onNewShader(SkShader::TileMode, SkShader::TileMode, const SkMatrix* localMatrix) const SK_OVERRIDE; virtual bool isOpaque() const SK_OVERRIDE; SkImage_Raster(const SkBitmap& bm) : INHERITED(bm.width(), bm.height()) , fBitmap(bm) {} private: SkImage_Raster() : INHERITED(0, 0) {} SkBitmap fBitmap; typedef SkImage_Base INHERITED; }; /////////////////////////////////////////////////////////////////////////////// SkImage* SkImage_Raster::NewEmpty() { // Returns lazily created singleton static SkImage* gEmpty; if (NULL == gEmpty) { gEmpty = SkNEW(SkImage_Raster); } gEmpty->ref(); return gEmpty; } static void release_data(void* addr, void* context) { SkData* data = static_cast<SkData*>(context); data->unref(); } SkImage_Raster::SkImage_Raster(const Info& info, SkData* data, size_t rowBytes) : INHERITED(info.fWidth, info.fHeight) { data->ref(); void* addr = const_cast<void*>(data->data()); SkColorTable* ctable = NULL; fBitmap.installPixels(info, addr, rowBytes, ctable, release_data, data); fBitmap.setImmutable(); fBitmap.lockPixels(); } SkImage_Raster::SkImage_Raster(const Info& info, SkPixelRef* pr, size_t rowBytes) : INHERITED(info.fWidth, info.fHeight) { fBitmap.setInfo(info, rowBytes); fBitmap.setPixelRef(pr); fBitmap.lockPixels(); } SkImage_Raster::~SkImage_Raster() {} SkShader* SkImage_Raster::onNewShader(SkShader::TileMode tileX, SkShader::TileMode tileY, const SkMatrix* localMatrix) const { return SkShader::CreateBitmapShader(fBitmap, tileX, tileY, localMatrix); } void SkImage_Raster::onDraw(SkCanvas* canvas, SkScalar x, SkScalar y, const SkPaint* paint) const { canvas->drawBitmap(fBitmap, x, y, paint); } void SkImage_Raster::onDrawRectToRect(SkCanvas* canvas, const SkRect* src, const SkRect& dst, const SkPaint* paint) const { canvas->drawBitmapRectToRect(fBitmap, src, dst, paint); } bool SkImage_Raster::onReadPixels(SkBitmap* dst, const SkIRect& subset) const { if (dst->pixelRef()) { return this->INHERITED::onReadPixels(dst, subset); } else { SkBitmap src; if (!fBitmap.extractSubset(&src, subset)) { return false; } return src.copyTo(dst, src.colorType()); } } const void* SkImage_Raster::onPeekPixels(SkImageInfo* infoPtr, size_t* rowBytesPtr) const { const SkImageInfo info = fBitmap.info(); if ((kUnknown_SkColorType == info.colorType()) || !fBitmap.getPixels()) { return NULL; } *infoPtr = info; *rowBytesPtr = fBitmap.rowBytes(); return fBitmap.getPixels(); } bool SkImage_Raster::getROPixels(SkBitmap* dst) const { *dst = fBitmap; return true; } /////////////////////////////////////////////////////////////////////////////// SkImage* SkImage::NewRasterCopy(const SkImageInfo& info, const void* pixels, size_t rowBytes) { if (!SkImage_Raster::ValidArgs(info, rowBytes)) { return NULL; } if (0 == info.fWidth && 0 == info.fHeight) { return SkImage_Raster::NewEmpty(); } // check this after empty-check if (NULL == pixels) { return NULL; } // Here we actually make a copy of the caller's pixel data SkAutoDataUnref data(SkData::NewWithCopy(pixels, info.fHeight * rowBytes)); return SkNEW_ARGS(SkImage_Raster, (info, data, rowBytes)); } SkImage* SkImage::NewRasterData(const SkImageInfo& info, SkData* data, size_t rowBytes) { if (!SkImage_Raster::ValidArgs(info, rowBytes)) { return NULL; } if (0 == info.fWidth && 0 == info.fHeight) { return SkImage_Raster::NewEmpty(); } // check this after empty-check if (NULL == data) { return NULL; } // did they give us enough data? size_t size = info.fHeight * rowBytes; if (data->size() < size) { return NULL; } return SkNEW_ARGS(SkImage_Raster, (info, data, rowBytes)); } SkImage* SkImage::NewFromGenerator(SkImageGenerator* generator) { SkBitmap bitmap; if (!SkInstallDiscardablePixelRef(generator, &bitmap)) { return NULL; } return SkNEW_ARGS(SkImage_Raster, (bitmap)); } SkImage* SkNewImageFromPixelRef(const SkImageInfo& info, SkPixelRef* pr, size_t rowBytes) { return SkNEW_ARGS(SkImage_Raster, (info, pr, rowBytes)); } SkPixelRef* SkBitmapImageGetPixelRef(SkImage* image) { return ((SkImage_Raster*)image)->getPixelRef(); } bool SkImage_Raster::isOpaque() const { return fBitmap.isOpaque(); }
{ "content_hash": "d8709f5e4e174416a770eb0320469c11", "timestamp": "", "source": "github", "line_count": 222, "max_line_length": 99, "avg_line_length": 30.2972972972973, "alnum_prop": 0.6196848052334225, "repo_name": "xin3liang/platform_external_chromium_org_third_party_skia", "id": "a7e4e009e5c2fd2d9b3a1f58457e45b116fc5b6f", "size": "6869", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/image/SkImage_Raster.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "51856" }, { "name": "C", "bytes": "2128647" }, { "name": "C++", "bytes": "24176087" }, { "name": "CSS", "bytes": "17321" }, { "name": "Go", "bytes": "29067" }, { "name": "Java", "bytes": "24340" }, { "name": "JavaScript", "bytes": "423148" }, { "name": "Objective-C", "bytes": "49769" }, { "name": "Objective-C++", "bytes": "111441" }, { "name": "Python", "bytes": "567376" }, { "name": "Shell", "bytes": "62081" } ], "symlink_target": "" }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_UTIL_H #define BITCOIN_UTIL_H #include "uint256.h" #include <stdarg.h> #ifndef WIN32 #include <sys/types.h> #include <sys/time.h> #include <sys/resource.h> #else typedef int pid_t; /* define for Windows compatibility */ #endif #include <map> #include <list> #include <utility> #include <vector> #include <string> #include <boost/thread.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/path.hpp> #include <boost/date_time/gregorian/gregorian_types.hpp> #include <boost/date_time/posix_time/posix_time_types.hpp> #include "netbase.h" // for AddTimeData typedef long long int64; typedef unsigned long long uint64; static const int64 COIN = 100000; static const int64 CENT = COIN / 100; #define BEGIN(a) ((char*)&(a)) #define END(a) ((char*)&((&(a))[1])) #define UBEGIN(a) ((unsigned char*)&(a)) #define UEND(a) ((unsigned char*)&((&(a))[1])) #define ARRAYLEN(array) (sizeof(array)/sizeof((array)[0])) #ifndef PRI64d #if defined(_MSC_VER) || defined(__MSVCRT__) #define PRI64d "I64d" #define PRI64u "I64u" #define PRI64x "I64x" #else #define PRI64d "lld" #define PRI64u "llu" #define PRI64x "llx" #endif #endif /* Format characters for (s)size_t and ptrdiff_t */ #if defined(_MSC_VER) || defined(__MSVCRT__) /* (s)size_t and ptrdiff_t have the same size specifier in MSVC: http://msdn.microsoft.com/en-us/library/tcxf1dw6%28v=vs.100%29.aspx */ #define PRIszx "Ix" #define PRIszu "Iu" #define PRIszd "Id" #define PRIpdx "Ix" #define PRIpdu "Iu" #define PRIpdd "Id" #else /* C99 standard */ #define PRIszx "zx" #define PRIszu "zu" #define PRIszd "zd" #define PRIpdx "tx" #define PRIpdu "tu" #define PRIpdd "td" #endif // This is needed because the foreach macro can't get over the comma in pair<t1, t2> #define PAIRTYPE(t1, t2) std::pair<t1, t2> // Align by increasing pointer, must have extra space at end of buffer template <size_t nBytes, typename T> T* alignup(T* p) { union { T* ptr; size_t n; } u; u.ptr = p; u.n = (u.n + (nBytes-1)) & ~(nBytes-1); return u.ptr; } #ifdef WIN32 #define MSG_NOSIGNAL 0 #define MSG_DONTWAIT 0 #ifndef S_IRUSR #define S_IRUSR 0400 #define S_IWUSR 0200 #endif #else #define MAX_PATH 1024 #endif inline void MilliSleep(int64 n) { #if BOOST_VERSION >= 105000 boost::this_thread::sleep_for(boost::chrono::milliseconds(n)); #else boost::this_thread::sleep(boost::posix_time::milliseconds(n)); #endif } /* This GNU C extension enables the compiler to check the format string against the parameters provided. * X is the number of the "format string" parameter, and Y is the number of the first variadic parameter. * Parameters count from 1. */ #ifdef __GNUC__ #define ATTR_WARN_PRINTF(X,Y) __attribute__((format(printf,X,Y))) #else #define ATTR_WARN_PRINTF(X,Y) #endif extern std::map<std::string, std::string> mapArgs; extern std::map<std::string, std::vector<std::string> > mapMultiArgs; extern bool fDebug; extern bool fDebugNet; extern bool fPrintToConsole; extern bool fPrintToDebugger; extern bool fDaemon; extern bool fServer; extern bool fCommandLine; extern std::string strMiscWarning; extern bool fTestNet; extern bool fNoListen; extern bool fLogTimestamps; extern volatile bool fReopenDebugLog; void RandAddSeed(); void RandAddSeedPerfmon(); int ATTR_WARN_PRINTF(1,2) OutputDebugStringF(const char* pszFormat, ...); /* Rationale for the real_strprintf / strprintf construction: It is not allowed to use va_start with a pass-by-reference argument. (C++ standard, 18.7, paragraph 3). Use a dummy argument to work around this, and use a macro to keep similar semantics. */ /** Overload strprintf for char*, so that GCC format type warnings can be given */ std::string ATTR_WARN_PRINTF(1,3) real_strprintf(const char *format, int dummy, ...); /** Overload strprintf for std::string, to be able to use it with _ (translation). * This will not support GCC format type warnings (-Wformat) so be careful. */ std::string real_strprintf(const std::string &format, int dummy, ...); #define strprintf(format, ...) real_strprintf(format, 0, __VA_ARGS__) std::string vstrprintf(const char *format, va_list ap); bool ATTR_WARN_PRINTF(1,2) error(const char *format, ...); /* Redefine printf so that it directs output to debug.log * * Do this *after* defining the other printf-like functions, because otherwise the * __attribute__((format(printf,X,Y))) gets expanded to __attribute__((format(OutputDebugStringF,X,Y))) * which confuses gcc. */ #define printf OutputDebugStringF void LogException(std::exception* pex, const char* pszThread); void PrintException(std::exception* pex, const char* pszThread); void PrintExceptionContinue(std::exception* pex, const char* pszThread); void ParseString(const std::string& str, char c, std::vector<std::string>& v); std::string FormatMoney(int64 n, bool fPlus=false); bool ParseMoney(const std::string& str, int64& nRet); bool ParseMoney(const char* pszIn, int64& nRet); std::vector<unsigned char> ParseHex(const char* psz); std::vector<unsigned char> ParseHex(const std::string& str); bool IsHex(const std::string& str); std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL); std::string DecodeBase64(const std::string& str); std::string EncodeBase64(const unsigned char* pch, size_t len); std::string EncodeBase64(const std::string& str); std::vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid = NULL); std::string DecodeBase32(const std::string& str); std::string EncodeBase32(const unsigned char* pch, size_t len); std::string EncodeBase32(const std::string& str); void ParseParameters(int argc, const char*const argv[]); bool WildcardMatch(const char* psz, const char* mask); bool WildcardMatch(const std::string& str, const std::string& mask); void FileCommit(FILE *fileout); int GetFilesize(FILE* file); bool TruncateFile(FILE *file, unsigned int length); int RaiseFileDescriptorLimit(int nMinFD); void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length); bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest); boost::filesystem::path GetDefaultDataDir(); const boost::filesystem::path &GetDataDir(bool fNetSpecific = true); boost::filesystem::path GetConfigFile(); boost::filesystem::path GetPidFile(); void CreatePidFile(const boost::filesystem::path &path, pid_t pid); void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet); #ifdef WIN32 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate = true); #endif boost::filesystem::path GetTempPath(); void ShrinkDebugFile(); int GetRandInt(int nMax); uint64 GetRand(uint64 nMax); uint256 GetRandHash(); int64 GetTime(); void SetMockTime(int64 nMockTimeIn); int64 GetAdjustedTime(); int64 GetTimeOffset(); std::string FormatFullVersion(); std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments); void AddTimeData(const CNetAddr& ip, int64 nTime); void runCommand(std::string strCommand); inline std::string i64tostr(int64 n) { return strprintf("%"PRI64d, n); } inline std::string itostr(int n) { return strprintf("%d", n); } inline int64 atoi64(const char* psz) { #ifdef _MSC_VER return _atoi64(psz); #else return strtoll(psz, NULL, 10); #endif } inline int64 atoi64(const std::string& str) { #ifdef _MSC_VER return _atoi64(str.c_str()); #else return strtoll(str.c_str(), NULL, 10); #endif } inline int atoi(const std::string& str) { return atoi(str.c_str()); } inline int roundint(double d) { return (int)(d > 0 ? d + 0.5 : d - 0.5); } inline int64 roundint64(double d) { return (int64)(d > 0 ? d + 0.5 : d - 0.5); } inline int64 abs64(int64 n) { return (n >= 0 ? n : -n); } template<typename T> std::string HexStr(const T itbegin, const T itend, bool fSpaces=false) { std::string rv; static const char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; rv.reserve((itend-itbegin)*3); for(T it = itbegin; it < itend; ++it) { unsigned char val = (unsigned char)(*it); if(fSpaces && it != itbegin) rv.push_back(' '); rv.push_back(hexmap[val>>4]); rv.push_back(hexmap[val&15]); } return rv; } inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false) { return HexStr(vch.begin(), vch.end(), fSpaces); } template<typename T> void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true) { printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str()); } inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true) { printf(pszFormat, HexStr(vch, fSpaces).c_str()); } inline int64 GetPerformanceCounter() { int64 nCounter = 0; #ifdef WIN32 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter); #else timeval t; gettimeofday(&t, NULL); nCounter = (int64) t.tv_sec * 1000000 + t.tv_usec; #endif return nCounter; } inline int64 GetTimeMillis() { return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) - boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds(); } inline int64 GetTimeMicros() { return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) - boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds(); } inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime) { time_t n = nTime; struct tm* ptmTime = gmtime(&n); char pszTime[200]; strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime); return pszTime; } template<typename T> void skipspaces(T& it) { while (isspace(*it)) ++it; } inline bool IsSwitchChar(char c) { #ifdef WIN32 return c == '-' || c == '/'; #else return c == '-'; #endif } /** * Return string argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param default (e.g. "1") * @return command-line argument or default value */ std::string GetArg(const std::string& strArg, const std::string& strDefault); /** * Return integer argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param default (e.g. 1) * @return command-line argument (0 if invalid number) or default value */ int64 GetArg(const std::string& strArg, int64 nDefault); /** * Return boolean argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param default (true or false) * @return command-line argument or default value */ bool GetBoolArg(const std::string& strArg, bool fDefault=false); /** * Set an argument if it doesn't already have a value * * @param strArg Argument to set (e.g. "-foo") * @param strValue Value (e.g. "1") * @return true if argument gets set, false if it already had a value */ bool SoftSetArg(const std::string& strArg, const std::string& strValue); /** * Set a boolean argument if it doesn't already have a value * * @param strArg Argument to set (e.g. "-foo") * @param fValue Value (e.g. false) * @return true if argument gets set, false if it already had a value */ bool SoftSetBoolArg(const std::string& strArg, bool fValue); /** * MWC RNG of George Marsaglia * This is intended to be fast. It has a period of 2^59.3, though the * least significant 16 bits only have a period of about 2^30.1. * * @return random value */ extern uint32_t insecure_rand_Rz; extern uint32_t insecure_rand_Rw; static inline uint32_t insecure_rand(void) { insecure_rand_Rz = 36969 * (insecure_rand_Rz & 65535) + (insecure_rand_Rz >> 16); insecure_rand_Rw = 18000 * (insecure_rand_Rw & 65535) + (insecure_rand_Rw >> 16); return (insecure_rand_Rw << 16) + insecure_rand_Rz; } /** * Seed insecure_rand using the random pool. * @param Deterministic Use a determinstic seed */ void seed_insecure_rand(bool fDeterministic=false); /** Median filter over a stream of values. * Returns the median of the last N numbers */ template <typename T> class CMedianFilter { private: std::vector<T> vValues; std::vector<T> vSorted; unsigned int nSize; public: CMedianFilter(unsigned int size, T initial_value): nSize(size) { vValues.reserve(size); vValues.push_back(initial_value); vSorted = vValues; } void input(T value) { if(vValues.size() == nSize) { vValues.erase(vValues.begin()); } vValues.push_back(value); vSorted.resize(vValues.size()); std::copy(vValues.begin(), vValues.end(), vSorted.begin()); std::sort(vSorted.begin(), vSorted.end()); } T median() const { int size = vSorted.size(); assert(size>0); if(size & 1) // Odd number of elements { return vSorted[size/2]; } else // Even number of elements { return (vSorted[size/2-1] + vSorted[size/2]) / 2; } } int size() const { return vValues.size(); } std::vector<T> sorted () const { return vSorted; } }; bool NewThread(void(*pfn)(void*), void* parg); #ifdef WIN32 inline void SetThreadPriority(int nPriority) { SetThreadPriority(GetCurrentThread(), nPriority); } #else #define THREAD_PRIORITY_LOWEST PRIO_MAX #define THREAD_PRIORITY_BELOW_NORMAL 2 #define THREAD_PRIORITY_NORMAL 0 #define THREAD_PRIORITY_ABOVE_NORMAL 0 inline void SetThreadPriority(int nPriority) { // It's unclear if it's even possible to change thread priorities on Linux, // but we really and truly need it for the generation threads. #ifdef PRIO_THREAD setpriority(PRIO_THREAD, 0, nPriority); #else setpriority(PRIO_PROCESS, 0, nPriority); #endif } inline void ExitThread(size_t nExitCode) { pthread_exit((void*)nExitCode); } #endif void RenameThread(const char* name); inline uint32_t ByteReverse(uint32_t value) { value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8); return (value<<16) | (value>>16); } // Standard wrapper for do-something-forever thread functions. // "Forever" really means until the thread is interrupted. // Use it like: // new boost::thread(boost::bind(&LoopForever<void (*)()>, "dumpaddr", &DumpAddresses, 10000)); // or maybe: // boost::function<void()> f = boost::bind(&FunctionWithArg, argument); // threadGroup.create_thread(boost::bind(&LoopForever<boost::function<void()> >, "nothing", f, milliseconds)); template <typename Callable> void LoopForever(const char* name, Callable func, int64 msecs) { std::string s = strprintf("populacecoin-%s", name); RenameThread(s.c_str()); printf("%s thread start\n", name); try { while (1) { MilliSleep(msecs); func(); } } catch (boost::thread_interrupted) { printf("%s thread stop\n", name); throw; } catch (std::exception& e) { PrintException(&e, name); } catch (...) { PrintException(NULL, name); } } // .. and a wrapper that just calls func once template <typename Callable> void TraceThread(const char* name, Callable func) { std::string s = strprintf("populacecoin-%s", name); RenameThread(s.c_str()); try { printf("%s thread start\n", name); func(); printf("%s thread exit\n", name); } catch (boost::thread_interrupted) { printf("%s thread interrupt\n", name); throw; } catch (std::exception& e) { PrintException(&e, name); } catch (...) { PrintException(NULL, name); } } #endif
{ "content_hash": "d091fb7fac09e30c96827b53fd954173", "timestamp": "", "source": "github", "line_count": 586, "max_line_length": 143, "avg_line_length": 27.74061433447099, "alnum_prop": 0.6668307086614174, "repo_name": "bitcapital/populacecoins", "id": "2add90a68deccfe84ddfe267360a4cbf38db976d", "size": "16256", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/util.h", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
CREATE TABLE RM_ENVIRONMENT( ID INTEGER, NAME VARCHAR2(128) NOT NULL, TENANT_ID INTEGER NOT NULL, PRIMARY KEY (ID), UNIQUE (NAME, TENANT_ID) ) / CREATE SEQUENCE RM_ENVIRONMENT_SEQ START WITH 1 INCREMENT BY 1 NOCACHE / CREATE OR REPLACE TRIGGER RM_ENVIRONMENT_TRIGGER BEFORE INSERT ON RM_ENVIRONMENT REFERENCING NEW AS NEW FOR EACH ROW BEGIN SELECT RM_ENVIRONMENT_SEQ.NEXTVAL INTO :NEW.ID FROM DUAL; END; / CREATE TABLE RM_SERVER_INSTANCE ( ID INTEGER, ENVIRONMENT_ID INTEGER NOT NULL, NAME VARCHAR2(128) NOT NULL, SERVER_URL VARCHAR2(1024) NOT NULL, DBMS_TYPE VARCHAR2(128) NOT NULL, INSTANCE_TYPE VARCHAR2(128) NOT NULL, SERVER_CATEGORY VARCHAR2(128) NOT NULL, ADMIN_USERNAME VARCHAR2(128), ADMIN_PASSWORD VARCHAR2(255), DRIVER_CLASS VARCHAR(128) NOT NULL , TENANT_ID INTEGER NOT NULL, SSH_HOST VARCHAR(128), SSH_PORT INTEGER, SSH_USERNAME VARCHAR(128), SNAPSHOT_TARGET_DIRECTORY VARCHAR(1024), UNIQUE (NAME, ENVIRONMENT_ID, TENANT_ID), PRIMARY KEY (ID), FOREIGN KEY (ENVIRONMENT_ID) REFERENCES RM_ENVIRONMENT (ID) ) / CREATE SEQUENCE RM_SERVER_INSTANCE_SEQ START WITH 1 INCREMENT BY 1 NOCACHE / CREATE OR REPLACE TRIGGER RM_SERVER_INSTANCE_TRIGGER BEFORE INSERT ON RM_SERVER_INSTANCE REFERENCING NEW AS NEW FOR EACH ROW BEGIN SELECT RM_SERVER_INSTANCE_SEQ.NEXTVAL INTO :NEW.ID FROM DUAL; END; / CREATE TABLE RM_DATABASE ( ID INTEGER, NAME VARCHAR2(128) NOT NULL, RSS_INSTANCE_ID INTEGER NOT NULL, TYPE VARCHAR2(15) NOT NULL, TENANT_ID INTEGER NOT NULL, UNIQUE (NAME, RSS_INSTANCE_ID, TENANT_ID), PRIMARY KEY (ID), FOREIGN KEY (RSS_INSTANCE_ID) REFERENCES RM_SERVER_INSTANCE (ID) ) / CREATE SEQUENCE RM_DATABASE_SEQ START WITH 1 INCREMENT BY 1 NOCACHE / CREATE OR REPLACE TRIGGER RM_DATABASE_TRIGGER BEFORE INSERT ON RM_DATABASE REFERENCING NEW AS NEW FOR EACH ROW BEGIN SELECT RM_DATABASE_SEQ.NEXTVAL INTO :NEW.ID FROM DUAL; END; / CREATE TABLE RM_DATABASE_USER ( ID INTEGER, USERNAME VARCHAR2(16) NOT NULL, RSS_INSTANCE_ID INTEGER NOT NULL, TYPE VARCHAR2(15) NOT NULL, TENANT_ID INTEGER NOT NULL, INSTANCE_NAME VARCHAR2(128) NOT NULL, UNIQUE (USERNAME, RSS_INSTANCE_ID, TENANT_ID, TYPE, INSTANCE_NAME), PRIMARY KEY (ID) ) / CREATE SEQUENCE RM_DATABASE_USER_SEQ START WITH 1 INCREMENT BY 1 NOCACHE / CREATE OR REPLACE TRIGGER RM_DATABASE_USER_TRIGGER BEFORE INSERT ON RM_DATABASE_USER REFERENCING NEW AS NEW FOR EACH ROW BEGIN SELECT RM_DATABASE_USER_SEQ.NEXTVAL INTO :NEW.ID FROM DUAL; END; / CREATE TABLE RM_USER_DATABASE_ENTRY ( ID INTEGER, DATABASE_USER_ID INTEGER NOT NULL, DATABASE_ID INTEGER NOT NULL, PRIMARY KEY (ID), UNIQUE (DATABASE_USER_ID, DATABASE_ID), FOREIGN KEY (DATABASE_USER_ID) REFERENCES RM_DATABASE_USER (ID), FOREIGN KEY (DATABASE_ID) REFERENCES RM_DATABASE (ID) ) / CREATE SEQUENCE RM_USER_DATABASE_ENTRY_SEQ START WITH 1 INCREMENT BY 1 NOCACHE / CREATE OR REPLACE TRIGGER RM_USER_DATABASE_ENTRY_TRIGGER BEFORE INSERT ON RM_USER_DATABASE_ENTRY REFERENCING NEW AS NEW FOR EACH ROW BEGIN SELECT RM_USER_DATABASE_ENTRY_SEQ.NEXTVAL INTO :NEW.ID FROM DUAL; END; / CREATE TABLE RM_USER_DATABASE_PRIVILEGE ( ID INTEGER, USER_DATABASE_ENTRY_ID INTEGER NOT NULL, SELECT_PRIV CHAR(1) CHECK (SELECT_PRIV IN('N','Y')), INSERT_PRIV CHAR(1) CHECK (INSERT_PRIV IN('N','Y')), UPDATE_PRIV CHAR(1) CHECK (UPDATE_PRIV IN('N','Y')), DELETE_PRIV CHAR(1) CHECK (DELETE_PRIV IN('N','Y')), CREATE_PRIV CHAR(1) CHECK (CREATE_PRIV IN('N','Y')), DROP_PRIV CHAR(1) CHECK (DROP_PRIV IN('N','Y')), REFERENCES_PRIV CHAR(1) CHECK (REFERENCES_PRIV IN('N','Y')), INDEX_PRIV CHAR(1) CHECK (INDEX_PRIV IN('N','Y')), ALTER_PRIV CHAR(1) CHECK (ALTER_PRIV IN('N','Y')), EXECUTE_PRIV CHAR(1) CHECK (EXECUTE_PRIV IN('N','Y')), EVENT_PRIV CHAR(1) CHECK (EVENT_PRIV IN('N','Y')), TRIGGER_PRIV CHAR(1) CHECK (TRIGGER_PRIV IN('N','Y')), DEBUG_PRIV CHAR(1) CHECK (DEBUG_PRIV IN('N','Y')), FLASHBACK_PRIV CHAR(1) CHECK (FLASHBACK_PRIV IN('N','Y')), READ_PRIV CHAR(1) CHECK (READ_PRIV IN('N','Y')), WRITE_PRIV CHAR(1) CHECK (WRITE_PRIV IN('N','Y')), UNDER_PRIV CHAR(1) CHECK (UNDER_PRIV IN('N','Y')), ON_COMMIT_REFRESH_PRIV CHAR(1) CHECK (ON_COMMIT_REFRESH_PRIV IN('N','Y')), QUERY_REWRITE_PRIV CHAR(1) CHECK (QUERY_REWRITE_PRIV IN('N','Y')), PRIMARY KEY (ID), UNIQUE (USER_DATABASE_ENTRY_ID), FOREIGN KEY (USER_DATABASE_ENTRY_ID) REFERENCES RM_USER_DATABASE_ENTRY (ID) ) / CREATE SEQUENCE RM_USER_PRIVILEGE_SEQ START WITH 1 INCREMENT BY 1 NOCACHE / CREATE OR REPLACE TRIGGER RM_USER_PRIVILEGE_TRIGGER BEFORE INSERT ON RM_USER_DATABASE_PRIVILEGE REFERENCING NEW AS NEW FOR EACH ROW BEGIN SELECT RM_USER_PRIVILEGE_SEQ.NEXTVAL INTO :NEW.ID FROM DUAL; END; / CREATE TABLE RM_SYSTEM_DATABASE_COUNT ( ID INTEGER NOT NULL, ENVIRONMENT_ID INTEGER NOT NULL, COUNT INTEGER DEFAULT 0, PRIMARY KEY (ID), FOREIGN KEY (ENVIRONMENT_ID) REFERENCES RM_ENVIRONMENT (ID) ) / CREATE TABLE RM_PRIVILEGE_TEMPLATE ( ID INTEGER, ENVIRONMENT_ID INTEGER NOT NULL, NAME VARCHAR2(128) NOT NULL, TENANT_ID INTEGER NOT NULL, PRIMARY KEY (ID), UNIQUE (ENVIRONMENT_ID, NAME, TENANT_ID), FOREIGN KEY (ENVIRONMENT_ID) REFERENCES RM_ENVIRONMENT (ID) ) / CREATE SEQUENCE RM_PRIVILEGE_TEMPLATE_SEQ START WITH 1 INCREMENT BY 1 NOCACHE / CREATE OR REPLACE TRIGGER RM_PRIVILEGE_TEMPLATE_TRIGGER BEFORE INSERT ON RM_PRIVILEGE_TEMPLATE REFERENCING NEW AS NEW FOR EACH ROW BEGIN SELECT RM_PRIVILEGE_TEMPLATE_SEQ.NEXTVAL INTO :NEW.ID FROM DUAL; END; / CREATE TABLE RM_PRIVILEGE_TEMPLATE_ENTRY ( ID INTEGER, TEMPLATE_ID INTEGER NOT NULL, SELECT_PRIV CHAR(1) CHECK (SELECT_PRIV IN('N','Y')), INSERT_PRIV CHAR(1) CHECK (INSERT_PRIV IN('N','Y')), UPDATE_PRIV CHAR(1) CHECK (UPDATE_PRIV IN('N','Y')), DELETE_PRIV CHAR(1) CHECK (DELETE_PRIV IN('N','Y')), CREATE_PRIV CHAR(1) CHECK (CREATE_PRIV IN('N','Y')), DROP_PRIV CHAR(1) CHECK (DROP_PRIV IN('N','Y')), REFERENCES_PRIV CHAR(1) CHECK (REFERENCES_PRIV IN('N','Y')), INDEX_PRIV CHAR(1) CHECK (INDEX_PRIV IN('N','Y')), ALTER_PRIV CHAR(1) CHECK (ALTER_PRIV IN('N','Y')), EXECUTE_PRIV CHAR(1) CHECK (EXECUTE_PRIV IN('N','Y')), EVENT_PRIV CHAR(1) CHECK (EVENT_PRIV IN('N','Y')), TRIGGER_PRIV CHAR(1) CHECK (TRIGGER_PRIV IN('N','Y')), DEBUG_PRIV CHAR(1) CHECK (DEBUG_PRIV IN('N','Y')), FLASHBACK_PRIV CHAR(1) CHECK (FLASHBACK_PRIV IN('N','Y')), READ_PRIV CHAR(1) CHECK (READ_PRIV IN('N','Y')), WRITE_PRIV CHAR(1) CHECK (WRITE_PRIV IN('N','Y')), UNDER_PRIV CHAR(1) CHECK (UNDER_PRIV IN('N','Y')), ON_COMMIT_REFRESH_PRIV CHAR(1) CHECK (ON_COMMIT_REFRESH_PRIV IN('N','Y')), QUERY_REWRITE_PRIV CHAR(1) CHECK (QUERY_REWRITE_PRIV IN('N','Y')), PRIMARY KEY (ID), FOREIGN KEY (TEMPLATE_ID) REFERENCES RM_PRIVILEGE_TEMPLATE (ID) ) / CREATE SEQUENCE RM_TEMPLATE_ENTRY_SEQ START WITH 1 INCREMENT BY 1 NOCACHE / CREATE OR REPLACE TRIGGER RM_TEMPLATE_ENTRY_TRIGGER BEFORE INSERT ON RM_PRIVILEGE_TEMPLATE_ENTRY REFERENCING NEW AS NEW FOR EACH ROW BEGIN SELECT RM_TEMPLATE_ENTRY_SEQ.NEXTVAL INTO :NEW.ID FROM DUAL; END; /
{ "content_hash": "a64d2325f4bf44af18ef2f06ee3f34ab", "timestamp": "", "source": "github", "line_count": 245, "max_line_length": 88, "avg_line_length": 33.57142857142857, "alnum_prop": 0.6111854103343465, "repo_name": "wso2/carbon-storage-management", "id": "a06552fb0258cddb30efc4f403abec1a9fe5d009", "size": "8225", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "features/rss-manager/org.wso2.carbon.rssmanager.server.feature/resources/dbscripts/rss-manager/oracle/rss_oracle.sql", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "6360" }, { "name": "Java", "bytes": "1306743" }, { "name": "JavaScript", "bytes": "54851" }, { "name": "PLSQL", "bytes": "8225" } ], "symlink_target": "" }
/** * Automatically generated file. Please do not edit. * @author Highcharts Config Generator by Karasiq * @see [[http://api.highcharts.com/highstock]] */ package com.highstock.config import scalajs.js, js.`|` import com.highcharts.CleanJsObject import com.highcharts.HighchartsUtils._ /** * @note JavaScript name: <code>series&lt;sankey&gt;-states-normal</code> */ @js.annotation.ScalaJSDefined class SeriesSankeyStatesNormal extends com.highcharts.HighchartsGenericObject { /** * <p>Animation options for the fill color when returning from hover * state to normal state. The animation adds some latency in order * to reduce the effect of flickering when hovering in and out of * for example an uneven coastline.</p> * @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/maps/plotoptions/series-states-animation-false/">No animation of fill color</a> */ val animation: js.UndefOr[js.Object | Boolean] = js.undefined } object SeriesSankeyStatesNormal { /** * @param animation <p>Animation options for the fill color when returning from hover. state to normal state. The animation adds some latency in order. to reduce the effect of flickering when hovering in and out of. for example an uneven coastline.</p> */ def apply(animation: js.UndefOr[js.Object | Boolean] = js.undefined): SeriesSankeyStatesNormal = { val animationOuter: js.UndefOr[js.Object | Boolean] = animation com.highcharts.HighchartsGenericObject.toCleanObject(new SeriesSankeyStatesNormal { override val animation: js.UndefOr[js.Object | Boolean] = animationOuter }) } }
{ "content_hash": "a13a19203e8e728ee8ad4b28145f7a55", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 255, "avg_line_length": 43.68421052631579, "alnum_prop": 0.744578313253012, "repo_name": "Karasiq/scalajs-highcharts", "id": "788efd504aba6566052dab9b06d2436107996d20", "size": "1660", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/scala/com/highstock/config/SeriesSankeyStatesNormal.scala", "mode": "33188", "license": "mit", "language": [ { "name": "Scala", "bytes": "131509301" } ], "symlink_target": "" }
module Holidays # This file is generated by the Ruby Holidays gem. # # Definitions loaded: data/vi.yaml # # To use the definitions in this file, load it right after you load the # Holiday gem: # # require 'holidays' # require 'holidays/vi' # # All the definitions are available at https://github.com/alexdunae/holidays module VI # :nodoc: def self.defined_regions [:vi] end def self.holidays_by_month { 1 => [{:mday => 1, :name => "New Year", :regions => [:vi]}], 4 => [{:mday => 30, :name => "Liberation Day", :regions => [:vi]}], 5 => [{:mday => 1, :name => "International Workers' Day", :regions => [:vi]}], 9 => [{:mday => 2, :name => "National Day", :regions => [:vi]}] } end end end Holidays.merge_defs(Holidays::VI.defined_regions, Holidays::VI.holidays_by_month)
{ "content_hash": "5a6476b60d475fa810e2db821da10518", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 84, "avg_line_length": 28.096774193548388, "alnum_prop": 0.5809414466130884, "repo_name": "seanhandley/holidays", "id": "ef7a7d536b23178d70a6f98f762b154160c0703a", "size": "889", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "lib/holidays/vi.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "359104" } ], "symlink_target": "" }
A D-Bus implementation for .NET Core. Design goals: * Be asynchronous at the heart * Favor code generation over runtime reflection * Fast, lean, blah, blah :)
{ "content_hash": "3a7e5455381075970f3404e44c866a20", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 47, "avg_line_length": 26.833333333333332, "alnum_prop": 0.7453416149068323, "repo_name": "Tragetaschen/DbusCore", "id": "0aaa2887713c4521224f17a1bfba31e72b090daa", "size": "172", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "143441" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- ~ Copyright 2017 Red Hat, Inc. and/or its affiliates. ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ you may not use this file except in compliance with the License. ~ You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, software ~ distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the License for the specific language governing permissions and ~ limitations under the License. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>kie-wb-common-cli-tools</artifactId> <groupId>org.kie.workbench</groupId> <version>7.54.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>kie-wb-common-cli-forms-migration</artifactId> <name>KIE Workbench Common CLI Forms Migration</name> <dependencies> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-project-api</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-project-backend</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-services-api</artifactId> </dependency> <dependency> <groupId>org.kie.workbench.services</groupId> <artifactId>kie-wb-common-services-backend</artifactId> </dependency> <dependency> <groupId>org.jboss.errai</groupId> <artifactId>errai-security-server</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-metadata-backend-lucene</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-metadata-commons-io</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-nio2-jgit</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-structure-api</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-backend-server</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-metadata-api</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-server</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-io</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-nio2-api</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-nio2-model</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-api</artifactId> </dependency> <dependency> <groupId>org.kie</groupId> <artifactId>kie-api</artifactId> </dependency> <dependency> <groupId>org.kie.workbench.screens</groupId> <artifactId>kie-wb-common-library-api</artifactId> </dependency> <dependency> <groupId>org.kie.workbench.services</groupId> <artifactId>kie-wb-common-refactoring-backend</artifactId> </dependency> <dependency> <groupId>org.kie.soup</groupId> <artifactId>kie-soup-project-datamodel-commons</artifactId> </dependency> <dependency> <groupId>org.jboss.weld.se</groupId> <artifactId>weld-se-core</artifactId> <exclusions> <!-- collides with javax.inject:javax.inject:jar:1:compile --> <exclusion> <groupId>jakarta.enterprise</groupId> <artifactId>jakarta.enterprise.cdi-api</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.jboss.spec.javax.servlet</groupId> <artifactId>jboss-servlet-api_3.1_spec</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency> <dependency> <groupId>commons-cli</groupId> <artifactId>commons-cli</artifactId> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> </dependency> <dependency> <groupId>org.apache.lucene</groupId> <artifactId>lucene-core</artifactId> </dependency> <dependency> <groupId>org.kie.workbench</groupId> <artifactId>kie-wb-common-cli-api</artifactId> </dependency> <dependency> <groupId>xerces</groupId> <artifactId>xercesImpl</artifactId> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> </dependency> <dependency> <groupId>org.drools</groupId> <artifactId>jbpm-simulation</artifactId> </dependency> <dependency> <groupId>org.eclipse</groupId> <artifactId>org.eclipse.bpmn2</artifactId> </dependency> <dependency> <groupId>org.kie.workbench</groupId> <artifactId>kie-wb-common-cli-project-migration</artifactId> </dependency> <dependency> <groupId>org.jboss.errai</groupId> <artifactId>errai-common</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.jboss.errai</groupId> <artifactId>errai-bus</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-layout-editor-api</artifactId> </dependency> <dependency> <groupId>org.kie.workbench.forms</groupId> <artifactId>kie-wb-common-forms-backend-services</artifactId> </dependency> <dependency> <groupId>org.kie.workbench.forms</groupId> <artifactId>kie-wb-common-forms-api</artifactId> </dependency> <dependency> <groupId>org.kie.workbench.forms</groupId> <artifactId>kie-wb-common-forms-fields</artifactId> </dependency> <dependency> <groupId>org.kie.workbench.forms</groupId> <artifactId>kie-wb-common-forms-data-modeller-integration-api</artifactId> </dependency> <dependency> <groupId>org.kie.workbench.forms</groupId> <artifactId>kie-wb-common-forms-jbpm-integration-api</artifactId> </dependency> <!-- test --> <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.kie.workbench.forms</groupId> <artifactId>kie-wb-common-forms-fields</artifactId> <scope>test</scope> <type>test-jar</type> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-nio2-fs</artifactId> <scope>test</scope> </dependency> </dependencies> </project>
{ "content_hash": "f902bbb17fdbf1db62c6056eb0a12480", "timestamp": "", "source": "github", "line_count": 237, "max_line_length": 108, "avg_line_length": 31.11392405063291, "alnum_prop": 0.6642256577163005, "repo_name": "romartin/kie-wb-common", "id": "f7c8f3f180a6cc40cc94542283586e33efee9205", "size": "7374", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "kie-wb-common-cli/kie-wb-common-cli-tools/kie-wb-common-cli-forms-migration/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2591" }, { "name": "CSS", "bytes": "171885" }, { "name": "Dockerfile", "bytes": "210" }, { "name": "FreeMarker", "bytes": "38625" }, { "name": "GAP", "bytes": "86275" }, { "name": "HTML", "bytes": "448966" }, { "name": "Java", "bytes": "51118150" }, { "name": "JavaScript", "bytes": "34587" }, { "name": "Shell", "bytes": "905" }, { "name": "TypeScript", "bytes": "26851" }, { "name": "VBA", "bytes": "86549" }, { "name": "XSLT", "bytes": "2327" } ], "symlink_target": "" }
package org.apache.ambari.serviceadvisor; // TODO, use this class instead of org.apache.ambari.server.api.services.stackadvisor.commands.StackAdvisorCommandType public enum ServiceAdvisorCommandType { RECOMMEND_COMPONENT_LAYOUT("recommend-component-layout"), VALIDATE_COMPONENT_LAYOUT("validate-component-layout"), RECOMMEND_CONFIGURATIONS("recommend-configurations"), RECOMMEND_CONFIGURATION_DEPENDENCIES("recommend-configuration-dependencies"), VALIDATE_CONFIGURATIONS("validate-configurations"); private final String name; private ServiceAdvisorCommandType(String name) { this.name = name; } public String getValue() { return this.name.toLowerCase(); } @Override public String toString() { return this.name; } /** * Instead of Enum.valueOf("value"), use this method instead to map the string to the correct Enum. * @param name Name with lowercase and dashes. * @return Enum that matches the string. */ public static ServiceAdvisorCommandType getEnum(String name) { for (ServiceAdvisorCommandType v : values()) { if (v.getValue().equalsIgnoreCase(name.replace("_", "-"))) { return v; } } throw new IllegalArgumentException(); } }
{ "content_hash": "3208ca19e6461627401b765cd08a17c5", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 118, "avg_line_length": 26.23404255319149, "alnum_prop": 0.7234387672343877, "repo_name": "radicalbit/ambari", "id": "f067668e754e5f7ac8ffb0189551221b53b52041", "size": "2039", "binary": false, "copies": "1", "ref": "refs/heads/trunk", "path": "ambari-serviceadvisor/src/main/java/org/apache/ambari/serviceadvisor/ServiceAdvisorCommandType.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "42212" }, { "name": "C", "bytes": "331204" }, { "name": "C#", "bytes": "182799" }, { "name": "C++", "bytes": "257" }, { "name": "CSS", "bytes": "1287531" }, { "name": "CoffeeScript", "bytes": "4323" }, { "name": "FreeMarker", "bytes": "2654" }, { "name": "Groovy", "bytes": "88056" }, { "name": "HTML", "bytes": "5098825" }, { "name": "Java", "bytes": "29006663" }, { "name": "JavaScript", "bytes": "17274453" }, { "name": "Makefile", "bytes": "11111" }, { "name": "PHP", "bytes": "149648" }, { "name": "PLSQL", "bytes": "2160" }, { "name": "PLpgSQL", "bytes": "314333" }, { "name": "PowerShell", "bytes": "2087991" }, { "name": "Python", "bytes": "14584206" }, { "name": "R", "bytes": "1457" }, { "name": "Roff", "bytes": "13935" }, { "name": "Ruby", "bytes": "14478" }, { "name": "SQLPL", "bytes": "2117" }, { "name": "Shell", "bytes": "741459" }, { "name": "Vim script", "bytes": "5813" } ], "symlink_target": "" }
from __future__ import unicode_literals from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title
{ "content_hash": "3e647a67bf8ceabb79b193d18ee227ed", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 44, "avg_line_length": 25.857142857142858, "alnum_prop": 0.6574585635359116, "repo_name": "django-girls/best-blog-in-the-world", "id": "454a89829dcf659184ad6d1c86d40bd8e34fc005", "size": "567", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "blog/models.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "746" }, { "name": "HTML", "bytes": "2076" }, { "name": "Python", "bytes": "10202" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ShippoExample")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ShippoExample")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7712ec9c-2581-49ee-8b61-745843f2cd6f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "6cc1d076e3547b173881c5358f4711ec", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 84, "avg_line_length": 38.72222222222222, "alnum_prop": 0.7482065997130559, "repo_name": "goshippo/shippo-csharp-client", "id": "e11055a80e42208dc9e5f1332cad5d61f68311d8", "size": "1397", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ShippoExample/Properties/AssemblyInfo.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "120629" } ], "symlink_target": "" }