text:
using System.Collections.Generic;
using System.IO;
using System.Net;
using ZKWebStandard.Collections;

namespace ZKWebStandard.Web.Wrappers {
	///
	/// Http request wrapper base class

	/// Http请求包装类的基类

	///
	public abstract class HttpRequestWrapper : IHttpRequest {
#pragma warning disable CS1591
		protected IHttpRequest OriginalRequest { get; set; }

		public virtual Stream Body {
			get { return OriginalRequest.Body; }
		}
		public virtual long? ContentLength {
			get { return OriginalRequest.ContentLength; }
		}
		public virtual string ContentType {
			get { return OriginalRequest.ContentType; }
		}
		public virtual string Host {
			get { return OriginalRequest.Host; }
		}
		public virtual IHttpContext HttpContext {
			get { return OriginalRequest.HttpContext; }
		}
		public virtual bool IsHttps {
			get { return OriginalRequest.IsHttps; }
		}
		public virtual string Method {
			get { return OriginalRequest.Method; }
		}
		public virtual string Path {
			get { return OriginalRequest.Path; }
		}
		public virtual string Protocol {
			get { return OriginalRequest.Protocol; }
		}
		public virtual string QueryString {
			get { return OriginalRequest.QueryString; }
		}
		public virtual IPAddress RemoteIpAddress {
			get { return OriginalRequest.RemoteIpAddress; }
		}
		public virtual int RemotePort {
			get { return OriginalRequest.RemotePort; }
		}
		public virtual string Scheme {
			get { return OriginalRequest.Scheme; }
		}
		public virtual IDictionary<string, object> CustomParameters {
			get { return OriginalRequest.CustomParameters; }
		}
		public virtual string GetCookie(string key) {
			return OriginalRequest.GetCookie(key);
		}
		public virtual IEnumerable<Pair<string, string>> GetCookies() {
			return OriginalRequest.GetCookies();
		}
		public virtual IList<string> GetFormValue(string key) {
			return OriginalRequest.GetFormValue(key);
		}
		public virtual IEnumerable<Pair<string, IList<string>>> GetFormValues() {
			return OriginalRequest.GetFormValues();
		}
		public virtual string GetHeader(string key) {
			return OriginalRequest.GetHeader(key);
		}
		public virtual IEnumerable<Pair<string, string>> GetHeaders() {
			return OriginalRequest.GetHeaders();
		}
		public virtual IList<string> GetQueryValue(string key) {
			return OriginalRequest.GetQueryValue(key);
		}
		public virtual IEnumerable<Pair<string, IList<string>>> GetQueryValues() {
			return OriginalRequest.GetQueryValues();
		}
		public virtual IHttpPostedFile GetPostedFile(string key) {
			return OriginalRequest.GetPostedFile(key);
		}
		public virtual IEnumerable<Pair<string, IHttpPostedFile>> GetPostedFiles() {
			return OriginalRequest.GetPostedFiles();
		}

		protected HttpRequestWrapper(IHttpRequest originalRequest) {
			OriginalRequest = originalRequest;
		}
#pragma warning restore CS1591
	}
}


text:
import ciEnvironment from 'ci-info'

const { isCI: _isCI, name: _name } = ciEnvironment

const isZeitNow = !!process.env.NOW_BUILDER

export const isCI = isZeitNow || _isCI
export const name = isZeitNow ? 'ZEIT Now' : _name

redpajama_set_name: RedPajamaGithub


text:
//////////////////////////////////////////////////////////////////////////////
//
//                    Copyright 2012, Cornutum Project
//                             www.cornutum.org
//
//////////////////////////////////////////////////////////////////////////////

package org.cornutum.tcases.io;

import org.cornutum.tcases.SystemInputDef;

import org.apache.commons.io.IOUtils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStream;

/**
 * Provides access to system input definition resources.
 *
 */
public class SystemInputResources
  {

  /**
   * Creates a new SystemInputResources object.
   */
  public SystemInputResources( Class<?> type)
    {
    class_ = type;
    }

  /**
   * Writes the {@link SystemInputDef} to the the given file.
   */
  public void write( SystemInputDef systemInput, File file)
    {
    SystemInputDocWriter writer = createWriter( file);
    try
      {
      writer.write( systemInput);
      }
    catch( Exception e)
      {
      throw new RuntimeException( "Can't write " + systemInput + " to file=" + file, e);
      }
    finally
      {
      IOUtils.closeQuietly( writer, null);
      }
    }

  /**
   * Creates a {@link SystemInputDocWriter} for the given file.
   */
  private SystemInputDocWriter createWriter( File file)
    {
    try
      {
      return new SystemInputDocWriter( new FileWriter( file));
      }
    catch( Exception e)
      {
      throw new RuntimeException( "Can't open file=" + file, e);
      }
    }

  /**
   * Returns the {@link SystemInputDef} defined by the given resource.
   */
  public SystemInputDef read( String resource)
    {
    try
      {
      InputStream stream = class_.getResourceAsStream( resource);
      if( stream == null)
        {
        throw
          new RuntimeException
          ( "Can't find resource=" + class_.getName() + "." + resource);
        }

      return read( stream);
      }
    catch( Exception e)
      {
      throw new RuntimeException( "Can't read resource=" + resource, e);
      }
    }

  /**
   * Returns the {@link SystemInputDef} defined by the given file.
   */
  public SystemInputDef read( File file)
    {
    try
      {
      return read( new FileInputStream( file));
      }
    catch( Exception e)
      {
      throw new RuntimeException( "Can't read file=" + file, e);
      }
    }

  /**
   * Returns the {@link SystemInputDef} defined by the given string.
   */
  public SystemInputDef readString( String string)
    {
    try
      {
      return read( new ByteArrayInputStream( string.getBytes( "UTF-8")));
      }
    catch( Exception e)
      {
      throw new RuntimeException( "Can't read string", e);
      }
    }

  /**
   * Returns the {@link SystemInputDef} defined by the given stream.
   */
  public SystemInputDef read( InputStream stream) throws Exception
    {
    try( SystemInputDocReader reader = new SystemInputDocReader( stream))
      {
      return reader.getSystemInputDef();
      }
    }

  /**
   * Returns the {@link SystemInputDef} defined by the given JSON resource.
   */
  public SystemInputDef readJson( String resource)
    {
    try
      {
      InputStream stream  = class_.getResourceAsStream( resource);
      if( stream == null)
        {
        throw
          new RuntimeException
          ( "Can't find resource=" + class_.getName() + "." + resource);
        }

      return readJson( stream);
      }
    catch( Exception e)
      {
      throw new RuntimeException( "Can't read resource=" + resource, e);
      }
    }

  /**
   * Returns the {@link SystemInputDef} defined by the given JSON file.
   */
  public SystemInputDef readJson( File file)
    {
    try
      {
      return readJson( new FileInputStream( file));
      }
    catch( Exception e)
      {
      throw new RuntimeException( "Can't read file=" + file, e);
      }
    }

  /**
   * Returns the {@link SystemInputDef} defined by the given JSON string.
   */
  public SystemInputDef readJsonString( String string)
    {
    try
      {
      return readJson( new ByteArrayInputStream( string.getBytes( "UTF-8")));
      }
    catch( Exception e)
      {
      throw new RuntimeException( "Can't read string", e);
      }
    }

  /**
   * Returns the {@link SystemInputDef} defined by the given JSON stream.
   */
  public SystemInputDef readJson( InputStream stream) throws Exception
    {
    try( SystemInputJsonReader reader = new SystemInputJsonReader( stream))
      {
      return reader.getSystemInputDef();
      }
    }

  /**
   * Writes the {@link SystemInputDef} to the the given file.
   */
  public void writeJson( SystemInputDef systemInputDef, File file)
    {
    try( SystemInputJsonWriter writer = new SystemInputJsonWriter( new FileOutputStream( file)))
      {
      writer.write( systemInputDef);
      }
    catch( Exception e)
      {
      throw new RuntimeException( "Can't write file=" + file, e);
      }
    }

  private Class<?> class_;
  }


text:
package ws.epigraph.wire.json.writer;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.junit.Test;
import ws.epigraph.data.Data;
import ws.epigraph.projections.op.OpProjection;
import ws.epigraph.projections.req.ReqEntityProjection;
import ws.epigraph.projections.req.ReqProjection;
import ws.epigraph.refs.SimpleTypesResolver;
import ws.epigraph.refs.TypesResolver;
import ws.epigraph.tests.*;
import ws.epigraph.types.DataType;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import static org.junit.Assert.assertEquals;
import static ws.epigraph.test.TestUtil.lines;
import static ws.epigraph.wire.WireTestUtil.parseOpProjection;
import static ws.epigraph.wire.WireTestUtil.parseReqProjection;

/**
 * @author Konstantin Sobolev
 */
public class ReqOutputJsonFormatWriterTest {
  private final TypesResolver resolver = new SimpleTypesResolver(
      PersonId.type,
      Person.type,
      User.type,
      UserId.type,
      UserRecord.type,
      User2.type,
      UserId2.type,
      UserRecord2.type,
      SubUser.type,
      SubUserId.type,
      SubUserRecord.type,
      String_Person_Map.type,
      PaginationInfo.type,
      PersonMap.type,
      SingleTagEntity.type,
      epigraph.String.type,
      epigraph.Boolean.type
  );

  private final DataType personDataType = new DataType(Person.type, Person.id);
  private final OpProjection<?, ?> personOpProjection = parseOpProjection(personDataType, lines(
      ":(",
      "  id,",
      "  `record` (",
      "    id {",
      "      ;param1 : epigraph.String,",
      "    },",
      "    bestFriend :`record` (",
      "      id,",
      "      bestFriend :`record` (",
      "        id,",
      "        firstName",
      "      ),",
      "    ),",
      "    bestFriend2 $bf2 = :`record` ( id, bestFriend2 $bf2 ),",
      "    bestFriend3 :( id, `record` ( id, firstName, bestFriend3 :`record` ( id, lastName, bestFriend3 : `record` ( id, bestFriend3 $bf3 = :`record` ( id, bestFriend3 $bf3 ) ) ) ) ),",
      "    worstEnemy ( id ) ~ws.epigraph.tests.UserRecord ( profile ),",
      "    friends *( :id ),",
      "    friendsMap [;keyParam:epigraph.String]( :(id, `record` (id, firstName) ) ),",
      "    singleTagField :tag",
      "  )",
      ") :~(",
      "      ws.epigraph.tests.User :`record` (profile)",
      "        :~ws.epigraph.tests.SubUser :`record` (worstEnemy(id)),",
      "      ws.epigraph.tests.User2 :`record` (worstEnemy(id))",
      ")"
  ), resolver);

  @Test
  public void testRenderEmpty() throws IOException {
    final Person.@NotNull Imm person =
        Person.create()
            .setId(PersonId.create(1))
            .toImmutable();

    testRender(":()", person, "{}");
  }

  @Test
  public void testRenderId() throws IOException {
    final Person.@NotNull Imm person =
        Person.create()
            .setId(PersonId.create(1))
            .toImmutable();

    testRender(":id", person, "1");
  }

  @Test
  public void testRenderIdParens() throws IOException {
    final Person.@NotNull Imm person =
        Person.create()
            .setId(PersonId.create(1))
            .toImmutable();

    testRender(":(id)", person, "{\"id\":1}");
  }

  @Test
  public void testRenderIdAndRecord() throws IOException {
    final Person.@NotNull Imm person =
        Person.create()
            .setId(PersonId.create(1))
            .setRecord(
                PersonRecord.create()
                    .setId(PersonId.create(1))
            )
            .toImmutable();

    testRender(":(id,record(id))", person, "{\"id\":1,\"record\":{\"id\":1}}");
  }

  @Test
  public void testRenderRecordWithMissingId() throws IOException {
    final Person.@NotNull Imm person =
        Person.create()
            .setRecord(
                PersonRecord.create()
                    .setId(PersonId.create(1))
            )
            .toImmutable();

    testRender(":(id,record(id))", person, "{\"id\":null,\"record\":{\"id\":1}}");
  }

  @Test
  public void testRenderRecordWithId() throws IOException {
    final Person.@NotNull Imm person =
        Person.create()
            .setRecord(
                PersonRecord.create()
                    .setId(PersonId.create(1))
            )
            .toImmutable();

    testRender(":record(id)", person, "{\"id\":1}");
  }

  @Test
  public void testRenderList() throws IOException {
    final Person.@NotNull Imm person =
        Person.create()
            .setRecord(
                PersonRecord.create()
                    .setFriends(
                        Person_List.create()
                            .add(Person.create().setId(PersonId.create(2)))
                            .add(Person.create().setId(PersonId.create(3)))
                            .add(Person.create().setId(PersonId.create(4)))
                    )
            )
            .toImmutable();

    testRender(":record(friends*(:id))", person, "{\"friends\":[2,3,4]}");
  }

  @Test
  public void testRenderMap() throws IOException {
    final Person.@NotNull Imm person =
        Person.create()
            .setRecord(
                PersonRecord.create()
                    .setFriendsMap(
                        String_Person_Map.create()
                            .put$("key1", Person.create().setId(PersonId.create(1)))
                            .put$("key2", Person.create().setId(PersonId.create(2)))
                            .put$("key3", Person.create().setId(PersonId.create(3)))
                    )
            )
            .toImmutable();

    testRender(
        ":record(friendsMap['key1','key2','key3'](:id))",
        person,
        "{\"friendsMap\":[{\"K\":\"key1\",\"V\":1},{\"K\":\"key2\",\"V\":2},{\"K\":\"key3\",\"V\":3}]}"
    );
  }

  @Test
  public void testRenderTailNoMatch() throws IOException {
    final Person.@NotNull Imm person =
        Person.create()
            .setRecord(
                UserRecord.create() // should not match even though this is a UserRecord
                    .setId(PersonId.create(1))
                    .setProfile(Url.create("http://foo"))
            )
            .toImmutable();

    testRender(
        ":record(id):~ws.epigraph.tests.User :record(profile)",
        person,
        "{\"TYPE\":\"ws.epigraph.tests.Person\",\"DATA\":{\"id\":1}}"
    );
  }

  @Test
  public void testRenderSimpleTail() throws IOException {
    final Person.@NotNull Imm person =
        User.create()
            .setId(UserId.create(1))
            .setRecord(
                UserRecord.create()
                    .setId(PersonId.create(1))
                    .setProfile(Url.create("http://foo"))
            )
            .toImmutable();

    testRender(
        ":id:~ws.epigraph.tests.User :record(profile)",
        person,
        "{\"TYPE\":\"ws.epigraph.tests.User\",\"DATA\":{\"id\":1,\"record\":{\"profile\":\"http://foo\"}}}"
    );
  }

  @Test
  public void testRenderSubTail() throws IOException {
    final Person.@NotNull Imm person =
        SubUser.create()
            .setRecord(
                SubUserRecord.create()
                    .setId(PersonId.create(1))
                    .setWorstEnemy(SubUserRecord.create().setId(PersonId.create(1)))
            )
            .toImmutable();

    testRender(
        ":record(id):~ws.epigraph.tests.User :record(profile) :~ws.epigraph.tests.SubUser :record(worstEnemy(id))",
        person,
        "{\"TYPE\":\"ws.epigraph.tests.SubUser\",\"DATA\":{\"id\":1,\"worstEnemy\":{\"id\":1}}}"
    );
  }

  @Test
  public void testRenderModelTail() throws IOException {
    final Person.Imm person =
        Person.create()
            .setRecord(
                PersonRecord.create()
                    .setId(PersonId.create(1))
                    .setWorstEnemy(
                        SubUserRecord.create()
                            .setId(PersonId.create(1))
                            .setProfile(Url.create("foo"))
                    )

            )
            .toImmutable();

    testRender(
        ":record(id,worstEnemy(id)~ws.epigraph.tests.UserRecord(profile))",
        person,
        "{\"id\":1,\"worstEnemy\":{\"TYPE\":\"ws.epigraph.tests.UserRecord\",\"DATA\":{\"id\":1,\"profile\":\"foo\"}}}"
    );
  }

  @Test
  public void testRenderMeta() throws IOException {
    final DataType personMapDataType = new DataType(PersonMap.type, null);
    final OpProjection<?, ?> personMapOpProjection = parseOpProjection(personMapDataType,
        "{ meta: (start, count) } [ required ]( :`record` ( id, firstName ) )", resolver
    );

    String reqProjectionStr = "@(start,count)[ 2 ]:record(id, firstName)";
    final ReqProjection<?, ?> reqProjection =
        parseReqProjection(
            personMapDataType,
            personMapOpProjection,
            reqProjectionStr,
            resolver
        ).projection();

    final PersonMap.Builder personMap = PersonMap.create();
    personMap.put$(
        PersonId.create(2),
        Person.create().setRecord(
            PersonRecord.create().setId(PersonId.create(2)).setFirstName("Alfred")
        )
    );
    personMap.setMeta(PaginationInfo.create()
        .setStart(10L).setCount(20L));

    String expectedJson =
        "{\"META\":{\"start\":10,\"count\":20},\"DATA\":[{\"K\":2,\"V\":{\"id\":2,\"firstName\":\"Alfred\"}}]}";
    testRender(reqProjection, PersonMap.type.createDataBuilder().set(personMap), expectedJson);
  }

  @Test
  public void testRenderRec() throws IOException {
    Person.Builder bf = Person.create();
    bf.setRecord(
        PersonRecord.create()
            .setId(PersonId.create(11))
            .setBestFriend2$(bf)
    );

    Person.Builder person = Person.create()
        .setId(PersonId.create(1))
        .setRecord(
            PersonRecord.create().setId(PersonId.create(1)).setBestFriend2$(bf)
        );

    testRender(
        ":(id,record(id,bestFriend2 $bf= :record(id, bestFriend2 $bf) ))",
        person,
        "{\"id\":1,\"record\":{\"id\":1,\"bestFriend2\":{\"id\":11,\"bestFriend2\":{\"REC\":1}}}}"
    );
  }

  @Test
  public void testRenderRec2() throws IOException {
    Person.Builder bf = Person.create();
    bf.setRecord(
        PersonRecord.create()
            .setId(PersonId.create(11))
            .setFirstName("Alfred")
            .setLastName("Hitchcock")
            .setBestFriend3(bf)
    );

    Person.Builder person = Person.create()
        .setId(PersonId.create(1))
        .setRecord(
            PersonRecord.create().setId(PersonId.create(1)).setBestFriend3(bf)
        );

    testRender(
        ":(id,record(id, " + // parent
        "  bestFriend3 :record( id, firstName, " + // bf-fn
        "    bestFriend3 :record( id, lastName, " + // bf-ln
        "      bestFriend3 $bf= :record(id, bestFriend3 $bf) ))))", //bf-id + bf-rec
        person,
        "{\"id\":1,\"record\":{\"id\":1," + //parent
        "\"bestFriend3\":{\"id\":11,\"firstName\":\"Alfred\"," + // bf-fn
        "\"bestFriend3\":{\"id\":11,\"lastName\":\"Hitchcock\"," + // bf-ln
        "\"bestFriend3\":{\"id\":11," + // bf-id
        "\"bestFriend3\":{\"REC\":1}}}}}}" // bf-red
    );
  }

  @Test
  public void testPolyDataNoProjection() throws IOException {
    Person.Builder pb = Person.create();
    pb.setRecord(
        PersonRecord.create()
            .setId(PersonId.create(11))
            .setFirstName("Alfred")
            .setLastName("Hitchcock")
            .setBestFriend( // Using `User` instead of `Person`
                User.create().setId(UserId.create(1))
            )
            .setWorstEnemy( // Using `UserRecord` instead of `PersonRecord`
                UserRecord.create().setFirstName("Bruce")
            )
    );

    testRender(
        (ReqEntityProjection) null,
        pb,
        "{\"record\":{" +
        "\"id\":11," +
        "\"firstName\":\"Alfred\"," +
        "\"lastName\":\"Hitchcock\"," +
        "\"bestFriend\":{\"TYPE\":\"ws.epigraph.tests.User\",\"DATA\":{\"id\":1}}," +
        "\"worstEnemy\":{\"TYPE\":\"ws.epigraph.tests.UserRecord\",\"DATA\":{\"firstName\":\"Bruce\"}}}}"
    );
  }

  @Test
  public void testPolyListDatumNoProjection() throws IOException {
    Person.Builder pb = Person.create();
    pb.setRecord(
        PersonRecord.create()
            .setFriendRecords(
                PersonRecord_List.create()
                    .add(PersonRecord.create().setFirstName("fn1"))
                    .add(UserRecord.create().setFirstName("fn2"))
            )
    );

    testRender(
        (ReqEntityProjection) null,
        pb,
        "{\"record\":{\"friendRecords\":[" +
        "{\"firstName\":\"fn1\"}," +
        "{\"TYPE\":\"ws.epigraph.tests.UserRecord\",\"DATA\":{\"firstName\":\"fn2\"}}" +
        "]}}"
    );
  }

  @Test
  public void testSingleTagEntity() throws IOException {
    testRender(
        ":record(singleTagField:tag)",
        Person.create()
            .setRecord(PersonRecord.create()
                .setSingleTagField(SingleTagEntity.create().setTag(epigraph.String.create("foo")))),
        "{\"singleTagField\":\"foo\"}"
    );
  }

  private void testRender(@NotNull String reqProjectionStr, @NotNull Data data, @NotNull String expectedJson)
      throws IOException {

    final ReqProjection<?, ?> reqProjection =
        parseReqProjection(personDataType, personOpProjection, reqProjectionStr, resolver).projection();

    testRender(reqProjection, data, expectedJson);

  }

  private void testRender(
      @Nullable ReqProjection<?, ?> reqProjection,
      @NotNull Data data,
      @NotNull String expectedJson)
      throws IOException {

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();

    final ReqJsonFormatWriter jsonWriter = new ReqJsonFormatWriter(baos);

    if (reqProjection == null)
      jsonWriter.writeData(data.type(), data);
    else
      jsonWriter.writeData(reqProjection, data);

    jsonWriter.close();

    assertEquals(expectedJson, baos.toString());
  }

}


text:
import * as THREE from "three";
import "imports-loader?THREE=three!three/examples/js/controls/OrbitControls.js";

import routingPointPin from "assets/images/routing/pin.png";

import PARAMETERS from "store/config/parameters.yml";
import STORE from "store";
import WS from "store/websocket";
import { drawImage } from "utils/draw";

export default class RoutingEditor {
    constructor() {
        this.routePoints = [];
        this.inEditingMode = false;
    }

    isInEditingMode() {
        return this.inEditingMode;
    }

    enableEditingMode(camera, adc) {
        this.inEditingMode = true;

        const pov = "Map";
        camera.fov = PARAMETERS.camera[pov].fov;
        camera.near = PARAMETERS.camera[pov].near;
        camera.far = PARAMETERS.camera[pov].far;

        camera.updateProjectionMatrix();
        WS.requestMapElementIdsByRadius(this.EDITING_MAP_RADIUS);
    }

    disableEditingMode(scene) {
        this.inEditingMode = false;
        this.removeAllRoutePoints(scene);
    }

    addRoutingPoint(point, coordinates, scene) {
        const offsetPoint = coordinates.applyOffset({x:point.x, y:point.y});
        const pointMesh = drawImage(routingPointPin, 3.5, 3.5, offsetPoint.x, offsetPoint.y, 0.3);
        this.routePoints.push(pointMesh);
        scene.add(pointMesh);
    }

    removeLastRoutingPoint(scene) {
        const lastPoint = this.routePoints.pop();
        if (lastPoint) {
            scene.remove(lastPoint);
            if (lastPoint.geometry) {
                lastPoint.geometry.dispose();
            }
            if (lastPoint.material) {
                lastPoint.material.dispose();
            }
        }
    }

    removeAllRoutePoints(scene) {
        this.routePoints.forEach((object) => {
            scene.remove(object);
            if (object.geometry) {
                object.geometry.dispose();
            }
            if (object.material) {
                object.material.dispose();
            }
        });
        this.routePoints = [];
    }

    sendRoutingRequest(carOffsetPosition, coordinates) {
        if (this.routePoints.length === 0) {
            alert("Please provide at least an end point.");
            return false;
        }

        const points = this.routePoints.map((object) => {
            object.position.z = 0;
            return coordinates.applyOffset(object.position, true);
        });

        const start    = (points.length > 1) ? points[0]
                         : coordinates.applyOffset(carOffsetPosition, true);
        const end      = points[points.length-1];
        const waypoint = (points.length > 1) ? points.slice(1,-1) : [];
        WS.requestRoute(start, waypoint, end);

        return true;
    }
}

RoutingEditor.prototype.EDITING_MAP_RADIUS = 1500.0; //meters


text:
package org.dbpedia.spotlight.exceptions;

/**
 * @author Joachim Daiber
 */
public class NotADBpediaResourceException extends ItemNotFoundException {

    private static final long serialVersionUID = 5557180885572250317L;

    public NotADBpediaResourceException(String msg) {
        super(msg);
    }

    public NotADBpediaResourceException(String msg, Exception e) {
        super(msg, e);
    }

}


text:
Stanowimy inicjatywę obywatelską która postawiła sobie za cel, stworzenie systemu informatycznego umożliwiającego niezależną jak i obiektywną weryfikację wyników wyborów. Tworzymy niedochodowy i niezaangażowany politycznie projekt obywatelski.

# Członkowie
Sortowanie alfabetyczne po imieniu.

| Członek  | Rola  |
| ------------- | ------------- |
| AdamK | Architektura, Java  |
| KacperJ | Media, jQuery |
| KarolF | AngularJS |
| MaciekS | DevOps |
| MagdaB | Media |
| MarcinT | AngularJS |
| PawełP | Architektura, Java |
| PrzemekJ | Analiza |
| RobertP | Analiza |

#Jak do nas dołączyć?
Aby do nas dołączyć utwórz proszę nowy issue bezpośrednio w tym repozytorium. Komunikacja odbywa się poprzez E-Mail i Skype.

**Zapraszamy do współpracy**
1. Doświadczonego architekta REST, który pomoże nam dalej rozwijać nasze serwisy (security, best practices ipt.).
2. Doświadczonego administratora kontenera Java EE GlassFish 4.1 bądź WildFly 8.2.0.
3. Grafików którzy pomogą nam stworzyć jednolitą i przejrzystą identyfikację wizualną dla OPW: infografiki, kolorystyka, typografia.
4. Programistów Java, Java EE.
5. Programistów JavaScript - AngularJS, jQuery.
6. Administratora baz danych PostreSQL.
7. Informatyków gminnych.
8. Osoby które z perspektywy obywatela pomogą nam edukować i czynić polskie prawo wyborcze bardziej przejrzystym i zrozumiałym.
9. Osoby zainteresowane polskim prawem bądź procesem wyborczym.

# Linki
* https://otwartapw.pl/
* http://otwartapw.atlassian.net/
* https://trello.com/b/hKes4OCP/otwarta-platforma-wyborcza
* https://twitter.com/otwartapw

# Projekty

## OPW
System [OPW](https://github.com/OtwartaPlatformaWyborcza/Organizacja/blob/master/Projekt-OPW.md) (Otwarta Platforma Wyborcza) to nasz główny produkt.

## OOW
System [OOW](https://github.com/OtwartaPlatformaWyborcza/Organizacja/blob/master/Projekt-OOW.md) (Otwarte Organy Wyborcze).

## ODW
Aplikacja [ODW](https://github.com/OtwartaPlatformaWyborcza/Organizacja/blob/master/Projekt-ODW.md) (Otwarta Drukarka Wyborcza).

# Historia

# Roadmap
1. [2015.05] Demobilizacja infrastruktury OPW/PROD dla akji wyborczej Prezydent 2015
2. Konfiguracja środowiska DEV, TEST i PROD na serwerze JPROD dla akcji wyborczej Referendum 2015
3. Konfiguracja JIRA, Confluence


text:
import os
import sys
import time
import socket
import random
from chord import *

nnodes = int(sys.argv[1])
print "Creating chord network with : %s nodes" % nnodes

# create ports
ports_list = [random.randrange(10000, 60000) for x in range(nnodes)]
print "Ports list : %s" % ports_list
# create addresses
address_list = map(lambda port: Address('127.0.0.1', port), ports_list)
# keep unique ones
address_list = sorted(set(address_list))
# hash the addresses
hash_list 	 = map(lambda addr: addr.__hash__(), address_list)
# create the nodes
locals_list   = []
for i in range(0, len(address_list)):
	if len(locals_list) == 0:
		local = Local(address_list[i])
	else:
		# use a random already created peer's address as a remote
		remote = locals_list[random.randrange(len(locals_list))].address_
		local = Local(address_list[i], remote)
	local.start()
	print "Created at %s"  % address_list[i]
	locals_list.append(local)
	time.sleep(0.5)

print "Done creating peers, our pid %s is" % os.getpid()

while 1:
	command = raw_input("Command: ")
	if command == "add_node":
		while 1:
			address = Address("127.0.0.1", random.randrange(10000, 60000))
			if not address.__hash__() in hash_list:
				ports_list.append(address.port)
				print "New node at port %s" % address.port
				address_list.append(address)
				locals_list.append(Local(address, locals_list[random.randrange(len(locals_list))].address))
				break
	else:
		address = address_list[random.randrange(len(address_list))]
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.connect((address.ip, address.port))
		s.sendall(command + "\r\n")
		print "Response : '%s'" % s.recv(10000)
		s.close()


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:c="http://www.springframework.org/schema/c" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="foo" class="java.lang.String" c:_="foo-level-2" />

	<bean id="baz" class="java.lang.String" c:_="baz" />

</beans>


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
var AUTH_LOGIN = exports.AUTH_LOGIN = 'AUTH_LOGIN';
var AUTH_CHECK = exports.AUTH_CHECK = 'AUTH_CHECK';
var AUTH_ERROR = exports.AUTH_ERROR = 'AUTH_ERROR';
var AUTH_LOGOUT = exports.AUTH_LOGOUT = 'AUTH_LOGOUT';


text:
cookbook_file '/root/subhash/destination/new.rb' do
  source 'new.rb'
  owner 'root'
  group 'root'
  mode '0755'
  action :create
end


text:
namespace ash::quick_start {

// Represents a connection to the remote source device and is an abstraction of
// a Nearby Connection.
class Connection {
 public:
  Connection() = default;
  virtual ~Connection() = default;
};

}  // namespace ash::quick_start

#endif  // CHROME_BROWSER_ASH_LOGIN_OOBE_QUICK_START_CONNECTIVITY_CONNECTION_H_


text:
import api from '../../api'

const SOURCE_UPDATED = 'selectedModel/SOURCE_UPDATED'
const SAVING = 'selectedModel/SAVING'
const LOADING = 'selectedModel/LOADING'
const LOADED = 'selectedModel/LOADED'
const LOAD_ERROR = 'selectedModel/LOAD_ERROR'
const RENDERING = 'selectedModel/RENDERING'
const RENDERED = 'selectedModel/RENDERED'
const RENDER_ERROR = 'selectedModel/RENDER_ERROR'

const emptyModel = {
  url: null,
  id: null,
  source: '// New SAN Model',
  parsedModel: {},
  modelHash: null,
  transitionsHash: null,
  graphUrl: null,
  createdAt: null,
  updatedAt: null
}

const initialState = {
  loading: false,
  loaded: false,
  dirty: false,
  saving: false,
  rendering: false,
  rendered: false,
  data: { ...emptyModel },
  error: null
}

const mutations = {
  [LOADING] (state) {
    state.loading = true
  },

  [LOADED] (state, model) {
    state.dirty = false
    state.loading = false
    state.saving = false
    state.loaded = true
    state.rendering = false
    state.rendered = true
    state.data = model
    state.error = null
  },

  [LOAD_ERROR] (state, error) {
    state.loading = false
    state.error = error
  },

  [SOURCE_UPDATED] (state, newSource) {
    state.dirty = true
    state.data.source = newSource
  },

  [SAVING] (state) {
    state.saving = true
  },

  [RENDERING] (state) {
    state.rendering = true
    state.error = null
  },

  [RENDERED] (state, { url, transitionsHash }) {
    state.data.graphUrl = `data:image/png;base64,${url}`
    state.rendering = false
    state.rendered = true
  },

  [RENDER_ERROR] (state, error) {
    state.rendering = false
    state.rendered = false
    state.error = error
  }
}

const actions = {
  initializeNewModel ({ commit }) {
    commit(LOADED, { ...emptyModel })
  },
  parseModel ({ commit, dispatch, state }, cb) {
    // HACK: Should have mutations specific to parsing insted of using the render ones
    commit(RENDERING)
    api.parseModel(state.data.source,
      () => dispatch('renderModelGraph'),
      (error) => commit(RENDER_ERROR, error)
    )
  },
  updateModelSource ({ commit, dispatch }, newSource) {
    commit(SOURCE_UPDATED, newSource)
    dispatch('parseModel')
  },
  saveModel ({ commit, state }, params) {
    commit(SAVING)

    const { id } = state.data
    if (id) {
      api.updateModel(id, params, (data) => commit(LOADED, data))
    } else {
      api.createModel({...state.data, ...params},
        (data) => commit(LOADED, data)
      )
    }
  },
  loadModel ({ commit }, modelID) {
    commit(LOADING)
    api.findModel(
      modelID,
      (data) => commit(LOADED, data),
      (error) => commit(LOAD_ERROR, error)
    )
  },
  renderModelGraph ({ commit, state }) {
    commit(RENDERING)

    const { source } = state.data
    api.renderGraph(source,
      (data) => commit(RENDERED, data),
      (error) => commit(RENDER_ERROR, error)
    )
  }
}

export default {
  state: initialState,
  mutations,
  actions
}


text:
// Copyright 2009 - 2010 Sina Iravanian - <sina@sinairv.com>
//
// This source file(s) may be redistributed, altered and customized
// by any means PROVIDING the authors name and all copyright
// notices remain intact.
// THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED. USE IT AT YOUR OWN RISK. THE AUTHOR ACCEPTS NO
// LIABILITY FOR ANY DATA DAMAGE/LOSS THAT THIS PRODUCT MAY CAUSE.
//-----------------------------------------------------------------------

using System;
using System.Xml.Linq;
using System.Globalization;
using System.Collections.Generic;
using System.Text;
using System.Linq;

namespace Arch.CFramework.AppInternals.Serialization.XMLSerialize
{
    /// <summary>
    /// Provides utility methods for manipulating XML.
    /// There are four methods for each unit. UnitExists, FindUnit, CanCreateUnit, CreateUnit
    /// Units are: Location, Element, and Attribute
    /// </summary>
    internal static class XMLUtils
    {
        /// <summary>
        /// Determines whether the location specified exists in the given XML element.
        /// </summary>
        /// <param name="baseElement">The XML element.</param>
        /// <param name="location">The location string.</param>
        /// <returns>a value indicating whether the location specified exists in the given XML element</returns>
        public static bool LocationExists(XElement baseElement, string location)
        {
            XElement newLoc = FindLocation(baseElement, location);
            return newLoc != null;
        }

        /// <summary>
        /// Finds the location specified in the given XML element specified.
        /// </summary>
        /// <param name="baseElement">The XML element.</param>
        /// <param name="location">The location string.</param>
        /// <returns>the XML element corresponding to the specified location, or <c>null</c> if it is not found</returns>
        public static XElement FindLocation(XElement baseElement, string location)
        {
            if (baseElement == null || location == null)
                throw new ArgumentNullException();

            var locSteps = location.SplitPathNamespaceSafe();

            XElement currentLocation = baseElement;
            foreach (string loc in locSteps)
            {
                if (loc == ".")
                {
                    continue;
                }
                else if (loc == "..")
                {
                    currentLocation = currentLocation.Parent;
                    if (currentLocation == null)
                        break;
                }
                else
                {
                    XName curLocName = loc;
                    if (curLocName.Namespace.IsEmpty())
                        currentLocation = currentLocation.Element(curLocName);
                    else
                        currentLocation = currentLocation.Element_NamespaceNeutral(curLocName);

                    if (currentLocation == null)
                        break;
                }
            }

            return currentLocation;
        }

        /// <summary>
        /// Determines whether the specified location can be created in the specified XML element.
        /// </summary>
        /// <param name="baseElement">The XML element.</param>
        /// <param name="location">The location string.</param>
        /// <returns>
        /// <c>true</c> if the specified location can be created in the specified XML element; otherwise, <c>false</c>.
        /// </returns>
        public static bool CanCreateLocation(XElement baseElement, string location)
        {
            var locSteps = location.SplitPathNamespaceSafe();

            XElement currentLocation = baseElement;
            foreach (string loc in locSteps)
            {
                if (loc == ".")
                {
                    continue;
                }
                else if (loc == "..")
                {
                    currentLocation = currentLocation.Parent;
                    if (currentLocation == null)
                        return false;
                }
                else
                {
                    XName curLocName = loc;
                    if (curLocName.Namespace.IsEmpty())
                        currentLocation = currentLocation.Element(curLocName);
                    else
                        currentLocation = currentLocation.Element_NamespaceNeutral(curLocName);

                    if (currentLocation == null)
                        return true;
                }
            }

            return true;
        }

        /// <summary>
        /// Creates and returns XML element corresponding to the sepcified location in the given XML element.
        /// </summary>
        /// <param name="baseElement">The XML element.</param>
        /// <param name="location">The location string.</param>
        /// <returns>XML element corresponding to the sepcified location created in the given XML element</returns>
        public static XElement CreateLocation(XElement baseElement, string location)
        {
            var locSteps = location.SplitPathNamespaceSafe();

            XElement currentLocation = baseElement;
            foreach (string loc in locSteps)
            {
                if (loc == ".")
                {
                    continue;
                }
                else if (loc == "..")
                {
                    currentLocation = currentLocation.Parent;
                    if (currentLocation == null)
                        break;
                }
                else
                {
                    XName curLocName = loc;
                    XElement newLoc;
                    if (curLocName.Namespace.IsEmpty())
                        newLoc = currentLocation.Element(curLocName);
                    else
                        newLoc = currentLocation.Element_NamespaceNeutral(curLocName);

                    if (newLoc == null)
                    {
                        var newElem = new XElement(curLocName.OverrideNsIfEmpty(currentLocation.Name.Namespace));
                        currentLocation.Add(newElem);
                        currentLocation = newElem;
                    }
                    else
                    {
                        currentLocation = newLoc;
                    }
                }
            }

            return currentLocation;
        }

        /// <summary>
        /// Determines whether the attribute with the given name located in the given location string exists in the given XML element.
        /// </summary>
        /// <param name="baseElement">The XML element.</param>
        /// <param name="location">The location string.</param>
        /// <param name="attrName">Name of the attribute.</param>
        /// <returns>
        /// a value indicating whether the attribute with the given name located in the given location string exists in the given XML element.
        /// </returns>
        public static bool AttributeExists(XElement baseElement, string location, XName attrName)
        {
            return FindAttribute(baseElement, location, attrName) != null;
        }

        /// <summary>
        /// Finds the attribute with the given name located in the given location string in the given XML element.
        /// </summary>
        /// <param name="baseElement">The XML element.</param>
        /// <param name="location">The location string.</param>
        /// <param name="attrName">Name of the attribute.</param>
        /// <returns>a value indicating whether the attribute with the given name located in
        /// the given location string in the given XML element has been found.</returns>
        public static XAttribute FindAttribute(XElement baseElement, string location, XName attrName)
        {
            XElement newLoc = FindLocation(baseElement, location);
            if (newLoc == null)
                return null;

            var newAttrName = attrName;
            // the following stupid code is because of odd behaviour of LINQ to XML
            if (newAttrName.Namespace == newLoc.Name.Namespace)
                newAttrName = newAttrName.RemoveNamespace();

            if (newAttrName.Namespace.IsEmpty())
                return newLoc.Attribute(newAttrName);
            else
                return newLoc.Attribute_NamespaceNeutral(newAttrName);
        }

        /// <summary>
        /// Determines whether the attribute with the given name can be created in the location
        /// specified by the given location string in the given XML element.
        /// </summary>
        /// <param name="baseElement">The XML element.</param>
        /// <param name="location">The location string.</param>
        /// <param name="attrName">Name of the attribute.</param>
        /// <returns>
        /// <c>true</c> if the attribute with the given name can be created in the location
        /// specified by the given location string in the given XML element; otherwise, <c>false</c>.
        /// </returns>
        public static bool CanCreateAttribute(XElement baseElement, string location, XName attrName)
        {
            XElement newLoc = FindLocation(baseElement, location);
            if (newLoc == null) //if the location does not exist
            {
                if (CanCreateLocation(baseElement, location)) // see if you can create the location
                {
                    // if you can create the location you can create the attribute too
                    return true;
                }
                else
                {
                    // if you can't create the location you can't create the attribute either
                    return false;
                }
            }

            var newAttrName = attrName;
            // the following stupid code is because of odd behaviour of LINQ to XML
            if (newAttrName.Namespace == newLoc.Name.Namespace)
                newAttrName = newAttrName.RemoveNamespace();

            // check if the attribute does not exist
            if (newAttrName.Namespace.IsEmpty())
                return newLoc.Attribute(newAttrName) == null;
            else
                return newLoc.Attribute_NamespaceNeutral(newAttrName) == null;
        }

        /// <summary>
        /// Creates and returns the attribute with the given name in the location
        /// specified by the given location string in the given XML element.
        /// </summary>
        /// <param name="baseElement">The XML element.</param>
        /// <param name="location">The location string.</param>
        /// <param name="attrName">Name of the attribute.</param>
        /// <param name="attrValue">The value to be assigned to the attribute.</param>
        /// <returns>returns the attribute with the given name in the location
        /// specified by the given location string in the given XML element.</returns>
        public static XAttribute CreateAttribute(XElement baseElement, string location, XName attrName, object attrValue, XNamespace documentDefaultNamespace)
        {
            XElement newLoc = FindLocation(baseElement, location);
            if (newLoc == null)
            {
                if (CanCreateLocation(baseElement, location))
                {
                    newLoc = CreateLocation(baseElement, location);
                }
                else
                {
                    return null;
                }
            }

            // check if the attribute does not exist
            if (attrName.Namespace.IsEmpty() && attrName.Namespace != documentDefaultNamespace)
            {
                // i.e., the attribute already exists
                if (newLoc.Attribute(attrName) != null)
                    return null; // we cannot create another one with the same name
            }
            else
            {
                if (newLoc.Attribute_NamespaceNeutral(attrName) != null) // i.e., the attribute already exists
                    return null; // we cannot create another one with the same name
            }

            return newLoc.AddAttributeNamespaceSafe(attrName, attrValue, documentDefaultNamespace);
        }

        /// <summary>
        /// Finds the element with the given name located in the given location string in the given XML element.
        /// </summary>
        /// <param name="baseElement">The XML element.</param>
        /// <param name="location">The location string.</param>
        /// <param name="elemName">Name of the element.</param>
        /// <returns>a value indicating whether the element with the given name located in
        /// the given location string in the given XML element has been found</returns>
        public static XElement FindElement(XElement baseElement, string location, XName elemName)
        {
            return FindLocation(baseElement, StringUtils.CombineLocationAndElementName(location, elemName));
        }

        /// <summary>
        /// Determines whether the XML element with the given name located in the
        /// given location string in the given XML element exists.
        /// </summary>
        /// <param name="baseElement">The XML element.</param>
        /// <param name="location">The location string.</param>
        /// <param name="elemName">Name of the element.</param>
        /// <returns>a value indicating whether the XML element with the given name located in the
        /// given location string in the given XML element exists</returns>
        public static bool ElementExists(XElement baseElement, string location, XName elemName)
        {
            return FindElement(baseElement, location, elemName) != null;
        }

        /// <summary>
        /// Determines whether the XML element with the given name located in the
        /// given location string in the given XML element can be created
        /// </summary>
        /// <param name="baseElement">The XML element.</param>
        /// <param name="location">The location string.</param>
        /// <param name="elemName">Name of the element.</param>
        /// <returns>
        /// <c>true</c> if the XML element with the given name located in the given
        /// location string in the given XML element can be created; otherwise, <c>false</c>.
        /// </returns>
        public static bool CanCreateElement(XElement baseElement, string location, XName elemName)
        {
            return CanCreateLocation(baseElement, StringUtils.CombineLocationAndElementName(location, elemName));
        }

        /// <summary>
        /// Creates and returns the XML element with the given name located in the
        /// given location string in the given XML element.
        /// </summary>
        /// <param name="baseElement">The parent XML element.</param>
        /// <param name="location">The location string.</param>
        /// <param name="elemName">Name of the element to create.</param>
        /// <returns>returns the XML element with the given name located in the
        /// given location string in the given XML element</returns>
        public static XElement CreateElement(XElement baseElement, string location, XName elemName)
        {
            return CreateLocation(baseElement, StringUtils.CombineLocationAndElementName(location, elemName));
        }

        /// <summary>
        /// Creates and returns the XML element with the given name located in the
        /// given location string in the given XML element.
        /// </summary>
        /// <param name="baseElement">The parent XML element.</param>
        /// <param name="location">The location string.</param>
        /// <param name="elemName">Name of the element to create.</param>
        /// <param name="elemValue">The element value to be assigned to the created element.</param>
        /// <returns>returns the XML element with the given name located in the
        /// given location string in the given XML element.</returns>
        public static XElement CreateElement(XElement baseElement, string location, XName elemName, object elemValue)
        {
            XElement elem = CreateElement(baseElement, location, elemName);
            if (elem != null)
                elem.SetValue(elemValue);
            return elem;
        }

        /// <summary>
        /// Moves all the children of src (including all its elements and attributes) to the
        /// destination element, dst.
        /// </summary>
        /// <param name="src">The source element.</param>
        /// <param name="dst">The destination element.</param>
        public static void MoveDescendants(XElement src, XElement dst)
        {
            foreach (XAttribute attr in src.Attributes())
            {
                if (dst.Attribute(attr.Name) != null)
                {
                    throw new YAXAttributeAlreadyExistsException(attr.Name.ToString());
                }

                dst.Add(attr);
            }

            foreach (XNode elem in src.Nodes())
            {
                dst.Add(elem);
            }
        }

        /// <summary>
        /// Determines whether the specified element has neither any child attributes nor any child elements.
        /// </summary>
        /// <param name="elem">The element.</param>
        /// <returns>
        /// <c>true</c> if the specified element has neither any child attributes nor any child elements; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsElementCompletelyEmpty(XElement elem)
        {
            return !elem.HasAttributes && !elem.HasElements && elem.IsEmpty;
        }

        /// <summary>
        /// Decodes the XML escape sequences into normal string
        /// </summary>
        /// <param name="str">The string to decode.</param>
        /// <returns></returns>
        public static string DecodeXMLString(string str)
        {
            if (str.IndexOf('&') >= 0)
            {
                return str.Replace("<", "<").Replace(">", ">").Replace(""", "\"").Replace("'", "'").Replace("&", "&");
                // Make sure that & is the final replace so that sequences such as &gt; do not get corrupted
            }

            return str;
        }

        /// <summary>
        /// Adds the 'xml:space="preserve"' attribute to the specified element.
        /// </summary>
        /// <param name="element">Element to add the 'xml:space="preserve"' attribute to</param>
        /// <returns></returns>
        public static XElement AddPreserveSpaceAttribute(XElement element)
        {
            element.AddAttributeNamespaceSafe(XNamespace.Xml + "space", "preserve", null);
            return element;
        }

        public static string GetRandomPrefix(this XElement self)
        {
            var q = self.Attributes().Where(xa => xa.Name.Namespace == XNamespace.Xmlns).Select(xa => xa.Name.LocalName).ToArray();
            var setPrefixes = new HashSet<string>(q);

            string prefix = "p";

            for(int i = 1; i <= 10000; i++)
            {
                if (!setPrefixes.Contains(prefix + i))
                    return prefix + i;
            }

            throw new InvalidOperationException("Cannot create a unique random prefix");
        }

        public static string ToXmlValue(this object self)
        {
            return Convert.ToString((self ?? String.Empty), CultureInfo.InvariantCulture);
        }

        public static XAttribute AddAttributeNamespaceSafe(this XElement parent, XName attrName, object attrValue, XNamespace documentDefaultNamespace)
        {
            var newAttrName = attrName;

            if (newAttrName.Namespace == documentDefaultNamespace)
                    newAttrName = newAttrName.RemoveNamespace();

            var newAttr = new XAttribute(newAttrName, attrValue.ToXmlValue());
            parent.Add(newAttr);
            return newAttr;
        }

        public static XAttribute Attribute_NamespaceSafe(this XElement parent, XName attrName, XNamespace documentDefaultNamespace)
        {
            if(attrName.Namespace == documentDefaultNamespace)
                attrName = attrName.RemoveNamespace();
            return parent.Attribute(attrName);
        }

        public static IEnumerable<XAttribute> Attributes_NamespaceSafe(this XElement parent, XName attrName, XNamespace documentDefaultNamespace)
        {
            if (attrName.Namespace == documentDefaultNamespace)
                attrName = attrName.RemoveNamespace();
            return parent.Attributes(attrName);
        }

        public static XElement AddXmlContent(this XElement self, object contentValue)
        {
            self.Add(new XText(contentValue.ToXmlValue()));
            return self;
        }

        public static string GetXmlContent(this XElement self)
        {
            XText[] values = self.Nodes().OfType<XText>().ToArray();
            if (values.Length > 0)
                return values[0].Value;
            else
                return null;
        }

        public static XAttribute Attribute_NamespaceNeutral(this XElement parent, XName name)
        {
            return parent.Attributes().FirstOrDefault(e => e.Name.LocalName == name.LocalName);
        }

        public static IEnumerable<XAttribute> Attributes_NamespaceNeutral(this XElement parent, XName name)
        {
            return parent.Attributes().Where(e => e.Name.LocalName == name.LocalName);
        }

        public static XElement Element_NamespaceNeutral(this XContainer parent, XName name)
        {
            return parent.Elements().FirstOrDefault(e => e.Name.LocalName == name.LocalName);
        }

        public static IEnumerable<XElement> Elements_NamespaceNeutral(this XContainer parent, XName name)
        {
            return parent.Elements().Where(e => e.Name.LocalName == name.LocalName);
        }

        public static bool IsEmpty(this XNamespace self)
        {
            return self != null && !String.IsNullOrEmpty(self.NamespaceName.Trim());
        }

        public static XNamespace IfEmptyThen(this XNamespace self, XNamespace next)
        {
            return self.IsEmpty() ? self : next;
        }

        public static XNamespace IfEmptyThenNone(this XNamespace self)
        {
            return IfEmptyThen(self, XNamespace.None);
        }

        public static XName OverrideNsIfEmpty(this XName self, XNamespace ns)
        {
            if (self.Namespace.IsEmpty())
                return self;
            else if (ns.IsEmpty())
                return ns + self.LocalName;
            else
                return self;
        }

        public static XName RemoveNamespace(this XName self)
        {
            return XName.Get(self.LocalName);
        }

    }
}


text:
<?php

declare(strict_types=1);

namespace SitemapPlugin\Factory;

use SitemapPlugin\Model\ImageInterface;

interface ImageFactoryInterface
{
    public function createNew(string $location): ImageInterface;
}


text:
package dev.clojurephant.plugin.common.internal;

import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.plugins.JavaBasePlugin;
import org.gradle.api.tasks.SourceSetContainer;

public class ClojureCommonBasePlugin implements Plugin<Project> {
  @Override
  public void apply(Project project) {
    project.getPluginManager().apply(JavaBasePlugin.class);

    SourceSetContainer sourceSets = project.getExtensions().getByType(SourceSetContainer.class);
    configureSourceSets(sourceSets);
  }

  private void configureSourceSets(SourceSetContainer sourceSets) {
    sourceSets.configureEach(sourceSet -> {
      sourceSet.getResources().exclude("**/.keep");
    });
  }
}


text:
import DS from 'ember-data';

export default DS.Model.extend({
  code: DS.attr('string'),
  title: DS.attr('string'),
  author: DS.attr('string'),
  release: DS.attr('string')
});


text:
window.onfontsready = function (fontNames, onReady, options, fIterator, finishedCount) {
    // Ensure options is defined to prevent access errors
    options = options || 0;

    // Combine assignment for compression
    fIterator = finishedCount = 0;

    for (; fIterator < fontNames.length; fIterator++) {
        window.onfontready(fontNames[fIterator], function () {
            // fIterator was not counted down here because some font
            //   detections might operate synchronously
            // Prefix increment allows inline increment with comparison
            if (++finishedCount >= fontNames.length) {
                // All fonts have been loaded and parsed
                onReady();
            }
        }, {
            // The timeoutAfter is included here to force onfontready to
            //   shutdown the detection elements in the event of a timeout
            // The onTimeout callback is handled below
            timeoutAfter: options.timeoutAfter,
            sampleText: options.sampleText instanceof Array ? options.sampleText[fIterator] : options.sampleText,
            generic: options.generic instanceof Array ? options.generic[fIterator] : options.generic
        });
    }

    if (options.timeoutAfter && options.onTimeout) {
        setTimeout(function () {
            // Prevent timeout call if already finished
            if (finishedCount < fontNames.length) {
                // All comparisions to NaN are false, preventing onReady call
                // Combine two operations, setting finishedCount value first
                options.onTimeout(finishedCount = NaN);
            }
        }, options.timeoutAfter);
    }
};


text:
package com.technicat.tictactoe;

import com.technicat.boardgame.*;

/**
 * @author Phil Chu
 */
final public class TicTacToe extends BoardGame {

    final static public int X = PLAYER0;
    final static public int O = PLAYER1;

    public TicTacToe() {
	super();
    }

    public Board createBoard() {
	return new RowGameBoard(3,3);
    }

    public boolean isWon(BoardPlayer player,Board board) {
	return ((RowGameBoard)board).hasRow(player.getSide(),3);
    }

    public String getName() {
	return "Tic Tac Toe";
    }

}


text:
from msrest.serialization import Model

class TokenInformation(Model):
    """The token information details.

    :param token: Token value.
    :type token: str
    :param expiry_time_in_utc_ticks: Expiry time of token.
    :type expiry_time_in_utc_ticks: long
    :param security_pin: Security PIN
    :type security_pin: str
    """

    _attribute_map = {
        'token': {'key': 'token', 'type': 'str'},
        'expiry_time_in_utc_ticks': {'key': 'expiryTimeInUtcTicks', 'type': 'long'},
        'security_pin': {'key': 'securityPIN', 'type': 'str'},
    }

    def __init__(self, token=None, expiry_time_in_utc_ticks=None, security_pin=None):
        self.token = token
        self.expiry_time_in_utc_ticks = expiry_time_in_utc_ticks
        self.security_pin = security_pin


text:
User Management

        User Management

            Name

            Email

            {{ppl.name}}

            {{ppl.email}}

                    <button type="button"  class="btn btn-primary">Edit</button>

                <button type="button" ng-click="deleteusr(ppl.name)" class="btn btn-danger">Delete</button>


text:
<resources>
    <string name="app_name">Ideas Jotter</string>
    <string name="action_settings">Settings</string>
</resources>


text:
<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="tf-graph-style.html">
<link rel="import" href="tf-graph-minimap.html">

<dom-module id="tf-graph-scene">
<template>

Main Graph

Auxiliary nodes

<svg id="svg">
  <defs>

    <marker id="arrowhead" markerWidth="10" markerHeight="10"
      refX="9" refY="5" orient="auto">
      <path d="M 0,0 L 10,5 L 0,10 C 3,7 3,3 0,0"/>
    </marker>
    <marker id="ref-arrowhead" markerWidth="10" markerHeight="10"
      refX="1" refY="5" orient="auto">
      <path d="M 10,0 L 0,5 L 10,10 C 7,7 7,3 10,0"/>
    </marker>

    <marker id="annotation-arrowhead" markerWidth="5" markerHeight="5"
      refX="5" refY="2.5" orient="auto">
      <path d="M 0,0 L 5,2.5 L 0,5 L 0,0"/>
    </marker>
    <marker id="ref-annotation-arrowhead" markerWidth="5" markerHeight="5"
      refX="0" refY="2.5" orient="auto">
      <path d="M 5,0 L 0,2.5 L 5,5 L 5,0"/>
    </marker>

    <ellipse id="op-node-stamp"
        rx="7.5" ry="3" stroke="inherit" fill="inherit" />

    <ellipse id="op-node-annotation-stamp"
        rx="5" ry="2" stroke="inherit" fill="inherit" />

    <g id="op-series-vertical-stamp">
      <use xlink:href="#op-node-stamp" x="8" y="9" />
      <use xlink:href="#op-node-stamp" x="8" y="6" />
      <use xlink:href="#op-node-stamp" x="8" y="3" />
    </g>

    <g id="op-series-horizontal-stamp">
      <use xlink:href="#op-node-stamp" x="16" y="4" />
      <use xlink:href="#op-node-stamp" x="12" y="4" />
      <use xlink:href="#op-node-stamp" x="8" y="4" />
    </g>

    <g id="op-series-annotation-stamp">
      <use xlink:href="#op-node-annotation-stamp" x="9" y="2" />
      <use xlink:href="#op-node-annotation-stamp" x="7" y="2" />
      <use xlink:href="#op-node-annotation-stamp" x="5" y="2" />
    </g>

    <g id="linearGradients"></g>
  </defs>

  <rect fill="white" width="10000" height="10000"></rect>
  <g id="root"></g>
</svg>
<tf-graph-minimap id="minimap"></tf-graph-minimap>
</template>
</dom-module>


text:
package org.algorithmdb.algorithms.sorting;

import static org.junit.Assert.assertArrayEquals;

import org.junit.Test;

public class TestBottomUpMergeSort {

	Integer[] unSortedNumbers = {50,87,5,2,1000,9,23,90,8,32,1,23,18,100,11,980};
	Integer[] expectedSortedNumbers  = {1,2,5,8,9,11,18,23,23,32,50,87,90,100,980,1000};

	String[] unSortedStrings = {"jagan","Arunan","Albert","Vijay","stephen","Jack","Selva","Anbarasan",
	         "Richard","Venkat","Abi","Bharath","bala","Hedbert"};
	String[] expectedSortedStrings = {"Abi","Albert","Anbarasan","Arunan","Bharath","Hedbert","Jack",
			 "Richard","Selva","Venkat","Vijay","bala","jagan","stephen"};
	@Test
	public void testIntegerSorting() {
		new BottomUpMergeSort<Integer>().sort(unSortedNumbers);
		assertArrayEquals(expectedSortedNumbers, unSortedNumbers);
	}

	@Test
	public void testStringSorting() {
		new BottomUpMergeSort<String>().sort(unSortedStrings);
		assertArrayEquals(expectedSortedStrings, unSortedStrings);
	}
}


text:
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="theme-color" content="#000000">

  <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
  <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
  <title>Saq Search</title>

    You need to enable JavaScript to run this app.


text:
import React, {Component} from 'react';
import Tab from 'zs-react/Tab';
import FaIcon from 'zs-react/FaIcon';

/** Tab example */
export default class ExampleTab extends Component {
    componentDidMount() {
    }
    render() {
        return (

            <Tab.Tabs>
                <Tab.TabList>
                    <Tab><FaIcon iconName="fa-plane"/></Tab>
                    <Tab><FaIcon iconName="fa-bed" /></Tab>
                    <Tab><FaIcon iconName="fa-home"/></Tab>
                </Tab.TabList>
                <Tab.TabPanels>
                    <Tab.TabPanel>
                        Tab 1 - Book flight

                            Some more content.

                    </Tab.TabPanel>
                    <Tab.TabPanel>Tab 2</Tab.TabPanel>
                    <Tab.TabPanel>Tab 3</Tab.TabPanel>
                </Tab.TabPanels>
            </Tab.Tabs>

        );
    }
}


text:
<!DOCTYPE HTML>

	<?php include_once ('Templates/header.php');?>

        <?php include_once ('Templates/navigation.php');?>

Autogate Systems

                Our intelligent autogate system built to last for many years.

                Learn more

        <?php include_once ('Templates/navigationBtm.php');?>

Types of gates

						Description of gates...

Swing Gate

								. Lorem ipsum dolore malesuada sollicitudin elit suscipit magna.

								Learn more

Sliding Gate

								 Lorem ipsum dolore malesuada sollicitudin elit suscipit magna.

								Learn more

Swing Gate Features

						Description of features...

Smart Digital Panel

							Settings consistency
Auto Adjust Setting capability
It has intelligence to learn your gate based on
							its weight, condition etc. to auto adjust overall settings without you configuring anything!
							Slower of Faster

Backup Battery

							Our backup battery is capable to run up to 12 hours in the case of electricity unavailable

							It will also recharge itself when electricity comes back

							It lasts 1 year averagely, depending on usage

Big Motor

							Our Autogate system comes with a big motor which lasts longer with awesome features:

							Speed Variations to choose with

							With our big motor, we can withstand any heavy gate but still maintain normal high speed

Triggering Alarm

							This is an optional feature where you choose to install alarm system along with your autogate with us

							This is especially useful when you are asleep during night or midnight, where you may not aware someone is trying to force open your gate

Safe for even with children

								The impact of the gate can be adjusted

								There are people die hit by the gate impact for poorly installed autogate system

Remote Control with 4 Channels

							Our remote control comes with 4 Channels (more than others)

							With more channels, you can choose to add in some automation to your electrical appliances

							On/Off lights

							On/Off air conditioner

							On/Off alarm system ( If you add alarm system to your autogate )

							Panic Button

Key Release

							emergency release - no electricity - problem - In the case of emergency (electricity unavailable,

							Skru or allen key to open

							Actual Key Release - easy to operate

							Ugly appearance - Tidy appearance

							Unique key - so not easily being opened by - prevent thieves

Flexible Joint

							Protect your gate

							Avoiding your gate to be damaged

							Some rigid joint may damage your gate very easily

Weatherproof

								It stays immortal despite bad weather

Self Lubrication

							Auto maintenance

							Lasts at least half year

							Anti-jam

							Saves you at least RM50 for technician to come to your house to service

Arm Gate VS Underground

							Water flood - easily spoil especially after servicing

							grill hole -

							Underground disadvantages

							-PA - Underground problem

Warning on Unclosed Gate

							Whether your gate is stucked or you forget to close your gate,
 our warning sound serves as a reminder for you to close your gate.

Sliding Gate Features

						Description of features...

Inhouse manufactured

high quality control

							Come and visit our factory at [Address*Link]

Exported out to Australia

							High quality manufacturing comes with digital panel

Support heavy gate

							Most others don't support heavy gate, and thus doesn't last long

Alarm separated

							Servicing

Installation Process

				Description of installation process.

Concealed Wiring

								Our alarm system is highly customizable depending on your needs.

								Learn more...

Surface Wiring

								Our autogate system are high in quality & reliability. Check it out !

								Learn more...

Wireless

								Our CCTV system let's you monitor from anywhere while having tons of extra features that can be used.

								Learn more...

Features

						Description of features...

8 zones

								8 zones description. Lorem ipsum dolore malesuada sollicitudin elit suscipit magna.

								Learn more

16 zones

								16 zones description. Lorem ipsum dolore malesuada sollicitudin elit suscipit magna.

								Learn more

Quick Installation

						Description of quick installation...

Quick Installation

								Commodo id natoque malesuada sollicitudin elit suscipit. Curae suspendisse mauris posuere accumsan massa posuere lacus convallis tellus interdum. Amet nullam fringilla nibh nulla convallis ut venenatis purus lobortis. Auctor etiam porttitor phasellus tempus cubilia ultrices tempor sagittis. Nisl fermentum consequat integer interdum integer purus sapien. Nibh eleifend nulla nascetur pharetra commodo mi augue interdum tellus. Ornare cursus augue feugiat sodales velit lorem. Semper elementum ullamcorper lacinia natoque aenean scelerisque vel lacinia mollis quam sodales congue.

								Learn more

Daily Usage

						Description of daily usage

Daily Usage

								Using Photobeam technology, we could prevent especially child from being hit by the autogate when it was closing

								Learn more

Maintenance

						Your autogate needs some service and maintenance, and we are right there for you with our specialized trained technicians

								All our Autogate systems are entitled for Saferity Warranty System, which you need

								Money Back Guarantee

								72 Hours Service Timeframe

								Sparepart Availability

								24 Hours Customer Service

								Learn more

Get a FREE Security Consultation.

							Description of free consultation.

						Get Started

		<?php include_once ('Templates/footer.php'); ?>


text:
package gemma.gsec;

import gemma.gsec.authentication.UserManager;
import gemma.gsec.model.User;
import gemma.gsec.model.UserGroup;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

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

@Component
public class UserManagerImpl implements UserManager {

    @Override
    public String changePasswordForUser( String email, String username, String newPassword ) {
        return null;
    }

    @Override
    public Collection<String> findAllUsers() {
        return null;
    }

    @Override
    public User findbyEmail( String emailAddress ) {
        return null;
    }

    @Override
    public User findByEmail( String emailAddress ) {
        return null;
    }

    @Override
    public User findByUserName( String userName ) throws UsernameNotFoundException {
        return null;
    }

    @Override
    public UserGroup findGroupByName( String name ) {
        return null;
    }

    @Override
    public Collection<String> findGroupsForUser( String username ) throws UsernameNotFoundException {
        return null;
    }

    @Override
    public String generateSignupToken( String username ) throws UsernameNotFoundException {
        return null;
    }

    @Override
    public User getCurrentUser() {
        return null;
    }

    @Override
    public String getCurrentUsername() {
        return null;
    }

    @Override
    public String getRolePrefix() {
        return null;
    }

    @Override
    public boolean groupExists( String name ) {
        return false;
    }

    @Override
    public <T extends User> Collection<T> loadAll() {
        return null;
    }

    @Override
    public boolean loggedIn() {
        return false;
    }

    @Override
    public void reauthenticate( String userName, String password ) {

    }

    @Override
    public boolean userWithEmailExists( String emailAddress ) {
        return false;
    }

    @Override
    public boolean validateSignupToken( String username, String key ) {
        return false;
    }

    @Override
    public List<String> findAllGroups() {
        return null;
    }

    @Override
    public List<String> findUsersInGroup( String s ) {
        return null;
    }

    @Override
    public void createGroup( String s, List<GrantedAuthority> list ) {

    }

    @Override
    public void deleteGroup( String s ) {

    }

    @Override
    public void renameGroup( String s, String s1 ) {

    }

    @Override
    public void addUserToGroup( String s, String s1 ) {

    }

    @Override
    public void removeUserFromGroup( String s, String s1 ) {

    }

    @Override
    public List<GrantedAuthority> findGroupAuthorities( String s ) {
        return null;
    }

    @Override
    public void addGroupAuthority( String s, GrantedAuthority grantedAuthority ) {

    }

    @Override
    public void removeGroupAuthority( String s, GrantedAuthority grantedAuthority ) {

    }

    @Override
    public void createUser( UserDetails userDetails ) {

    }

    @Override
    public void updateUser( UserDetails userDetails ) {

    }

    @Override
    public void deleteUser( String s ) {

    }

    @Override
    public void changePassword( String s, String s1 ) {

    }

    @Override
    public boolean userExists( String s ) {
        return false;
    }

    @Override
    public UserDetails loadUserByUsername( String s ) throws UsernameNotFoundException {
        return null;
    }
}


text:
**Имя бренда**: название компании или сервиса.

**Обзор**: краткий обзор индивидуальности бренда: что делает бренд уникальным?

**Индивидуальность**: образ человека, обладающего теми качествами, которые вы хотели
бы присвоить бренду. Это сделает индивидуальность вашего бренда менее абстрактной.
Выберите человека, знакомого всем в вашей команде. Если у вашего бренда уже есть
символ или лицо, которое включает в себя эту индивидуальность, используйте его.
Опишите его характерные черты.

**Свойства бренда**: перечислите пять-семь свойств, которые лучше всего описывают ваш
бренд, и одно свойство, которого вы хотели бы избежать. Это поможет дизайнерам и
авторам текста создать цельный образ и при этом избежать неверных шагов.
Карта индивидуальности: мы можем поместить разные черты индивидуальности в
систему координат XY. Ось Х сообщает, насколько индивидуальность дружелюбна, а ось
Y позволяет определить степень доминирования или подчинения этой личности.

**Голос**: если бы бренд говорил, как бы он это делал? И что бы он сказал? Он говорил бы с
местечковым акцентом или хорошим литературным языком? Опишите голос вашего
бренда и то, как он меняется в различных ситуациях. Люди используют разный тембр и
манеру говорить в зависимости от ситуации – значит, так должен вести себя и бренд.
Примеры текста: приведите примеры текста, который вы могли бы использовать в своем
интерфейсе. Это поможет авторам понять, как ваш «дизайн-образ» будет
взаимодействовать с аудиторией.

**Визуальный лексикон**: если вы дизайнер и создаете этот документ для себя и/или своей
команды, можете составить визуальный лексикон. Он будет включать цвета, шрифты и
элементы визуального стиля, отражающие индивидуальность бренда. Можно
использовать общую концепцию или создать так называемый mood board[15]
(http://bkaprt.com/de/5).

**Методы связи**: опишите методы эмоционального вовлечения, которые вы, скорее всего,
будете использовать в интерфейсе, чтобы поддержать образ и произвести впечатление. Я
расскажу о них подробнее в следующей главе.
Теперь давайте рассмотрим реальный пример. Как ведущий дизайнер MailChimp, в
помощь разработчикам я создал определенный дизайн-образ. Вот слегка сокращенный
вариант документа, который мы использовали. Он построен так же, как и образец.


text:
<?php declare(strict_types = 1);

namespace PHPStan\Type;

use PHPStan\TrinaryLogic;

class ObjectTypeTest extends \PHPStan\Testing\TestCase
{

	public function dataIsIterable(): array
	{
		return [
			[new ObjectType('ArrayObject'), TrinaryLogic::createYes()],
			[new ObjectType('Traversable'), TrinaryLogic::createYes()],
			[new ObjectType('Unknown'), TrinaryLogic::createMaybe()],
			[new ObjectType('DateTime'), TrinaryLogic::createNo()],
		];
	}

	/**
	 * @dataProvider dataIsIterable
	 * @param ObjectType $type
	 * @param TrinaryLogic $expectedResult
	 */
	public function testIsIterable(ObjectType $type, TrinaryLogic $expectedResult): void
	{
		$this->createBroker();

		$actualResult = $type->isIterable();
		$this->assertSame(
			$expectedResult->describe(),
			$actualResult->describe(),
			sprintf('%s -> isIterable()', $type->describe(VerbosityLevel::value()))
		);
	}

	public function dataIsCallable(): array
	{
		return [
			[new ObjectType('Closure'), TrinaryLogic::createYes()],
			[new ObjectType('Unknown'), TrinaryLogic::createMaybe()],
			[new ObjectType('DateTime'), TrinaryLogic::createMaybe()],
		];
	}

	/**
	 * @dataProvider dataIsCallable
	 * @param ObjectType $type
	 * @param TrinaryLogic $expectedResult
	 */
	public function testIsCallable(ObjectType $type, TrinaryLogic $expectedResult): void
	{
		$this->createBroker();

		$actualResult = $type->isCallable();
		$this->assertSame(
			$expectedResult->describe(),
			$actualResult->describe(),
			sprintf('%s -> isCallable()', $type->describe(VerbosityLevel::value()))
		);
	}

	public function dataIsSuperTypeOf(): array
	{
		return [
			[
				new ObjectType('UnknownClassA'),
				new ObjectType('UnknownClassB'),
				TrinaryLogic::createMaybe(),
			],
			[
				new ObjectType(\ArrayAccess::class),
				new ObjectType(\Traversable::class),
				TrinaryLogic::createMaybe(),
			],
			[
				new ObjectType(\Countable::class),
				new ObjectType(\Countable::class),
				TrinaryLogic::createYes(),
			],
			[
				new ObjectType(\DateTimeImmutable::class),
				new ObjectType(\DateTimeImmutable::class),
				TrinaryLogic::createYes(),
			],
			[
				new ObjectType(\Traversable::class),
				new ObjectType(\ArrayObject::class),
				TrinaryLogic::createYes(),
			],
			[
				new ObjectType(\Traversable::class),
				new ObjectType(\Iterator::class),
				TrinaryLogic::createYes(),
			],
			[
				new ObjectType(\ArrayObject::class),
				new ObjectType(\Traversable::class),
				TrinaryLogic::createMaybe(),
			],
			[
				new ObjectType(\Iterator::class),
				new ObjectType(\Traversable::class),
				TrinaryLogic::createMaybe(),
			],
			[
				new ObjectType(\ArrayObject::class),
				new ObjectType(\DateTimeImmutable::class),
				TrinaryLogic::createNo(),
			],
			[
				new ObjectType(\DateTimeImmutable::class),
				new UnionType([
					new ObjectType(\DateTimeImmutable::class),
					new StringType(),
				]),
				TrinaryLogic::createMaybe(),
			],
			[
				new ObjectType(\DateTimeImmutable::class),
				new UnionType([
					new ObjectType(\ArrayObject::class),
					new StringType(),
				]),
				TrinaryLogic::createNo(),
			],
			[
				new ObjectType(\LogicException::class),
				new ObjectType(\InvalidArgumentException::class),
				TrinaryLogic::createYes(),
			],
			[
				new ObjectType(\InvalidArgumentException::class),
				new ObjectType(\LogicException::class),
				TrinaryLogic::createMaybe(),
			],
			[
				new ObjectType(\ArrayAccess::class),
				new StaticType(\Traversable::class),
				TrinaryLogic::createMaybe(),
			],
			[
				new ObjectType(\Countable::class),
				new StaticType(\Countable::class),
				TrinaryLogic::createYes(),
			],
			[
				new ObjectType(\DateTimeImmutable::class),
				new StaticType(\DateTimeImmutable::class),
				TrinaryLogic::createYes(),
			],
			[
				new ObjectType(\Traversable::class),
				new StaticType(\ArrayObject::class),
				TrinaryLogic::createYes(),
			],
			[
				new ObjectType(\Traversable::class),
				new StaticType(\Iterator::class),
				TrinaryLogic::createYes(),
			],
			[
				new ObjectType(\ArrayObject::class),
				new StaticType(\Traversable::class),
				TrinaryLogic::createMaybe(),
			],
			[
				new ObjectType(\Iterator::class),
				new StaticType(\Traversable::class),
				TrinaryLogic::createMaybe(),
			],
			[
				new ObjectType(\ArrayObject::class),
				new StaticType(\DateTimeImmutable::class),
				TrinaryLogic::createNo(),
			],
			[
				new ObjectType(\DateTimeImmutable::class),
				new UnionType([
					new StaticType(\DateTimeImmutable::class),
					new StringType(),
				]),
				TrinaryLogic::createMaybe(),
			],
			[
				new ObjectType(\DateTimeImmutable::class),
				new UnionType([
					new StaticType(\ArrayObject::class),
					new StringType(),
				]),
				TrinaryLogic::createNo(),
			],
			[
				new ObjectType(\LogicException::class),
				new StaticType(\InvalidArgumentException::class),
				TrinaryLogic::createYes(),
			],
			[
				new ObjectType(\InvalidArgumentException::class),
				new StaticType(\LogicException::class),
				TrinaryLogic::createMaybe(),
			],
			[
				new ObjectType(\stdClass::class),
				new ClosureType([], new MixedType(), false),
				TrinaryLogic::createMaybe(),
			],
			[
				new ObjectType(\Closure::class),
				new ClosureType([], new MixedType(), false),
				TrinaryLogic::createYes(),
			],
		];
	}

	/**
	 * @dataProvider dataIsSuperTypeOf
	 * @param ObjectType $type
	 * @param Type $otherType
	 * @param TrinaryLogic $expectedResult
	 */
	public function testIsSuperTypeOf(ObjectType $type, Type $otherType, TrinaryLogic $expectedResult): void
	{
		$this->createBroker();

		$actualResult = $type->isSuperTypeOf($otherType);
		$this->assertSame(
			$expectedResult->describe(),
			$actualResult->describe(),
			sprintf('%s -> isSuperTypeOf(%s)', $type->describe(VerbosityLevel::value()), $otherType->describe(VerbosityLevel::value()))
		);
	}

}


text:
<?php

namespace UDS\sirescaBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Doctrine\ORM\EntityRepository;
class ConvenioType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder

	    ->add('convNombre','text',array('label'=>'Nombre de Convenio*'))

            ->add('convCostoConvenio','number',array('label'=>'Costo*','invalid_message'=>'Ingrese convenio'))

            ->add('convEstadoConvenio','checkbox',array('label'=>'Activado/Desabilitado*'))

	    ->add('convCodigo','text',array('label'=>'Código de Convenio*'))

            ->add('prog','entity', array(
                                         'class' => 'UDSsirescaBundle:Programa',
                                         'property'=>'progNombre',
                                         'label'=>'Programa al que Pertenecerá*'))

		->add('conv', 'entity', array(
                 'class' => 'UDSsirescaBundle:Convenio',
                 'property'=>'convNombre',
                 'label'=>'Convenio Padre al que Pertenece*',
		 'required' =>false,
                 'query_builder' => function(EntityRepository $er) {return $er->createQueryBuilder('u')
																	    			->where('u.conv is NULL')
																		    			->orderBy('u.convNombre', 'ASC');},));

    }

    public function getName()
    {
        return 'uds_sirescabundle_conveniotype';
    }
}


text:
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

  <title>Projektowanie i implementacja systemów webowych</title>

  <meta name="description" content="Strona startowa">
  <meta name="author" content="Maciej Małecki">

  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <title>reveal.js</title>

  <link rel="stylesheet" href="dist/reset.css">
  <link rel="stylesheet" href="dist/reveal.css">
  <link rel="stylesheet" href="dist/theme/night.css" id="theme">
  <link rel="stylesheet" href="css/custom.css">

  <link rel="stylesheet" href="plugin/highlight/monokai.css" id="highlight-theme">

Projekt i implementacja systemów webowych

- Wykłady -

Wprowadzenie, HTML i CSS

Języki JavaScript i TypeScript

Technologie backendowe

Mapowanie obiektowo-relacyjne

SPA i Angular

Programowanie reaktywne

Cloud computing

Testowanie

Więcej informacji: https://pwr-piisw.github.io/materialy/.


text:
package org.datavec.api.records.reader.impl;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;
import org.datavec.api.conf.Configuration;
import org.datavec.api.records.Record;
import org.datavec.api.records.metadata.RecordMetaData;
import org.datavec.api.records.metadata.RecordMetaDataLine;
import org.datavec.api.records.reader.BaseRecordReader;
import org.datavec.api.split.InputSplit;
import org.datavec.api.split.InputStreamInputSplit;
import org.datavec.api.split.StringSplit;
import org.datavec.api.writable.Text;
import org.datavec.api.writable.Writable;
import org.nd4j.linalg.primitives.Triple;

import java.io.*;
import java.net.URI;
import java.util.*;

/**
 * Reads files line by line
 *
 * @author Adam Gibson
 */
public class LineRecordReader extends BaseRecordReader {

    private Iterator<String> iter;
    protected URI[] locations;
    protected int splitIndex = 0;
    protected int lineIndex = 0; //Line index within the current split
    protected Configuration conf;
    protected InputSplit inputSplit;

    @Override
    public void initialize(InputSplit split) throws IOException, InterruptedException {
        this.inputSplit = split;
        this.iter = getIterator(0);
    }

    @Override
    public void initialize(Configuration conf, InputSplit split) throws IOException, InterruptedException {
        this.conf = conf;
        initialize(split);
    }

    @Override
    public List<Writable> next() {
        List<Writable> ret = new ArrayList<>();

        if (iter.hasNext()) {
            String record = iter.next();
            invokeListeners(record);
            ret.add(new Text(record));
            lineIndex++;
            return ret;
        } else {
            if (!(inputSplit instanceof StringSplit) && splitIndex < locations.length - 1) {
                splitIndex++;
                lineIndex = 0; //New split opened -> reset line index
                try {
                    close();
                    iter = IOUtils.lineIterator(new InputStreamReader(locations[splitIndex].toURL().openStream()));
                    onLocationOpen(locations[splitIndex]);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (iter.hasNext()) {
                    String record = iter.next();
                    invokeListeners(record);
                    ret.add(new Text(record));
                    lineIndex++;
                    return ret;
                }
            }

            throw new NoSuchElementException("No more elements found!");
        }
    }

    @Override
    public boolean hasNext() {
        if (iter != null && iter.hasNext()) {
            return true;
        } else {
            if (locations != null && !(inputSplit instanceof StringSplit) && splitIndex < locations.length - 1) {
                splitIndex++;
                lineIndex = 0; //New split -> reset line count
                try {
                    close();
                    iter = IOUtils.lineIterator(new InputStreamReader(locations[splitIndex].toURL().openStream()));
                    onLocationOpen(locations[splitIndex]);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                return iter.hasNext();
            }

            return false;
        }
    }

    protected void onLocationOpen(URI location) {

    }

    @Override
    public void close() throws IOException {
        if (iter != null) {
            if (iter instanceof LineIterator) {
                LineIterator iter2 = (LineIterator) iter;
                iter2.close();
            }
        }
    }

    @Override
    public void setConf(Configuration conf) {
        this.conf = conf;
    }

    @Override
    public Configuration getConf() {
        return conf;
    }

    @Override
    public List<String> getLabels() {
        return null;
    }

    @Override
    public void reset() {
        if (inputSplit == null)
            throw new UnsupportedOperationException("Cannot reset without first initializing");
        try {
            initialize(inputSplit);
            splitIndex = 0;
        } catch (Exception e) {
            throw new RuntimeException("Error during LineRecordReader reset", e);
        }
        lineIndex = 0;
    }

    @Override
    public List<Writable> record(URI uri, DataInputStream dataInputStream) throws IOException {
        invokeListeners(uri);
        //Here: we are reading a single line from the DataInputStream
        BufferedReader br = new BufferedReader(new InputStreamReader(dataInputStream));
        String line = br.readLine();
        return Collections.singletonList((Writable) new Text(line));
    }

    protected Iterator<String> getIterator(int location) {
        Iterator<String> iterator = null;
        if (inputSplit instanceof StringSplit) {
            StringSplit stringSplit = (StringSplit) inputSplit;
            iterator = Collections.singletonList(stringSplit.getData()).listIterator();
        } else if (inputSplit instanceof InputStreamInputSplit) {
            InputStream is = ((InputStreamInputSplit) inputSplit).getIs();
            if (is != null) {
                iterator = IOUtils.lineIterator(new InputStreamReader(is));
            }
        } else {
            this.locations = inputSplit.locations();
            if (locations != null && locations.length > 0) {
                InputStream inputStream;
                try {
                    inputStream = locations[location].toURL().openStream();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                iterator = IOUtils.lineIterator(new InputStreamReader(inputStream));
            }
        }
        if (iterator == null)
            throw new UnsupportedOperationException("Unknown input split: " + inputSplit);
        return iterator;
    }

    protected void closeIfRequired(Iterator<String> iterator) {
        if (iterator instanceof LineIterator) {
            LineIterator iter = (LineIterator) iterator;
            iter.close();
        }
    }

    @Override
    public Record nextRecord() {
        List<Writable> next = next();
        URI uri = (locations == null || locations.length < 1 ? null : locations[splitIndex]);
        RecordMetaData meta = new RecordMetaDataLine(this.lineIndex - 1, uri, LineRecordReader.class); //-1 as line number has been incremented already...
        return new org.datavec.api.records.impl.Record(next, meta);
    }

    @Override
    public Record loadFromMetaData(RecordMetaData recordMetaData) throws IOException {
        return null;
    }

    @Override
    public List<Record> loadFromMetaData(List<RecordMetaData> recordMetaDatas) throws IOException {
        //First: create a sorted list of the RecordMetaData
        List<Triple<Integer, RecordMetaDataLine, List<Writable>>> list = new ArrayList<>();
        Set<URI> uris = new HashSet<>();
        Iterator<RecordMetaData> iter = recordMetaDatas.iterator();
        int count = 0;
        while (iter.hasNext()) {
            RecordMetaData rmd = iter.next();
            if (!(rmd instanceof RecordMetaDataLine)) {
                throw new IllegalArgumentException(
                                "Invalid metadata; expected RecordMetaDataLine instance; got: " + rmd);
            }
            list.add(new Triple<>(count++, (RecordMetaDataLine) rmd, (List<Writable>) null));
            if (rmd.getURI() != null)
                uris.add(rmd.getURI());
        }
        List<URI> sortedURIs = null;
        if (uris.size() > 0) {
            sortedURIs = new ArrayList<>(uris);
            Collections.sort(sortedURIs);
        }

        //Sort by URI first (if possible - don't always have URIs though, for String split etc), then sort by line number:
        Collections.sort(list, new Comparator<Triple<Integer, RecordMetaDataLine, List<Writable>>>() {
            @Override
            public int compare(Triple<Integer, RecordMetaDataLine, List<Writable>> o1,
                            Triple<Integer, RecordMetaDataLine, List<Writable>> o2) {
                if (o1.getSecond().getURI() != null) {
                    if (!o1.getSecond().getURI().equals(o2.getSecond().getURI())) {
                        return o1.getSecond().getURI().compareTo(o2.getSecond().getURI());
                    }
                }
                return Integer.compare(o1.getSecond().getLineNumber(), o2.getSecond().getLineNumber());
            }
        });

        if (uris.size() > 0 && sortedURIs != null) {
            //URIs case - possibly with multiple URIs
            Iterator<Triple<Integer, RecordMetaDataLine, List<Writable>>> metaIter = list.iterator(); //Currently sorted by URI, then line number

            URI currentURI = sortedURIs.get(0);
            Iterator<String> currentUriIter =
                            IOUtils.lineIterator(new InputStreamReader(currentURI.toURL().openStream()));
            int currentURIIdx = 0; //Index of URI
            int currentLineIdx = 0; //Index of the line for the current URI
            String line = currentUriIter.next();
            while (metaIter.hasNext()) {
                Triple<Integer, RecordMetaDataLine, List<Writable>> t = metaIter.next();
                URI thisURI = t.getSecond().getURI();
                int nextLineIdx = t.getSecond().getLineNumber();

                //First: find the right URI for this record...
                while (!currentURI.equals(thisURI)) {
                    //Iterate to the next URI
                    currentURIIdx++;
                    if (currentURIIdx >= sortedURIs.size()) {
                        //Should never happen
                        throw new IllegalStateException(
                                        "Count not find URI " + thisURI + " in URIs list: " + sortedURIs);
                    }
                    currentURI = sortedURIs.get(currentURIIdx);
                    currentLineIdx = 0;
                    if (currentURI.equals(thisURI)) {
                        //Found the correct URI for this MetaData instance
                        closeIfRequired(currentUriIter);
                        currentUriIter = IOUtils.lineIterator(new InputStreamReader(currentURI.toURL().openStream()));
                        line = currentUriIter.next();
                    }
                }

                //Have the correct URI/iter open -> scan to the required line
                while (currentLineIdx < nextLineIdx && currentUriIter.hasNext()) {
                    line = currentUriIter.next();
                    currentLineIdx++;
                }
                if (currentLineIdx < nextLineIdx && !currentUriIter.hasNext()) {
                    throw new IllegalStateException("Could not get line " + nextLineIdx + " from URI " + currentURI
                                    + ": has only " + currentLineIdx + " lines");
                }
                t.setThird(Collections.<Writable>singletonList(new Text(line)));
            }
        } else {
            //Not URI based: String split, etc
            Iterator<String> iterator = getIterator(0);
            Iterator<Triple<Integer, RecordMetaDataLine, List<Writable>>> metaIter = list.iterator();
            int currentLineIdx = 0;
            String line = iterator.next();
            while (metaIter.hasNext()) {
                Triple<Integer, RecordMetaDataLine, List<Writable>> t = metaIter.next();
                int nextLineIdx = t.getSecond().getLineNumber();
                while (currentLineIdx < nextLineIdx && iterator.hasNext()) {
                    line = iterator.next();
                    currentLineIdx++;
                }
                t.setThird(Collections.<Writable>singletonList(new Text(line)));
            }
            closeIfRequired(iterator);
        }

        //Now, sort by the original (request) order:
        Collections.sort(list, new Comparator<Triple<Integer, RecordMetaDataLine, List<Writable>>>() {
            @Override
            public int compare(Triple<Integer, RecordMetaDataLine, List<Writable>> o1,
                            Triple<Integer, RecordMetaDataLine, List<Writable>> o2) {
                return Integer.compare(o1.getFirst(), o2.getFirst());
            }
        });

        //And return...
        List<Record> out = new ArrayList<>();
        for (Triple<Integer, RecordMetaDataLine, List<Writable>> t : list) {
            out.add(new org.datavec.api.records.impl.Record(t.getThird(), t.getSecond()));
        }
        return out;
    }
}


text:
/**
 * Spring Framework configuration files.
 */
package io.smalldata.ohmageomh.config;


text:
import abc

class Decision(object):
    __metaclass__ = abc.ABCMeta

    def __init__(self, next_node=None, lucida_response=''):
        self.next_node = next_node
        self.lucdia_repsonse = lucida_response

    @abc.abstractmethod
    def logic_method(self, response_data, service_graph, dcm_node):
        """
        Decision logic method.

        Arg:
            response_data: response text/image from previous services
            service_graph: current workflow
            dcm_node: current DCM node in workflow

        Return:
            lucida_response: response to send back to user
            next_node: next node to go to in workflow
        """

        return