text:
function [newT,newIndexchannel]=removeNeuronsWithoutPrompt(t,indexchannel,varargin);
%function [newT,newIndexchannel]=RemoveNeuronsWithoutPrompt(t,indexchannel,varargin);
% a function that removes neurons  from indexchannel.
%example:  [newT,newIndexchannel]=RemoveNeurons(t,indexchannel,[2;1],[2;3],[2;4]) -
%deletes neurons [2;3] and [2;4] and [2;1] in indexchannel.

for i=1:length(varargin)
    x(:,i)=varargin{i};
end

if isempty(varargin),
    error('not enough inputs');
end
%if ~isempty(find(x(1,:)>size(indexchannel,2))),
%    error('channel does not exist');
%end
if size(x,2)>length(indexchannel),
    error('too many inputs');
end

emptychannel=0;
for i=1:size(x,2),
    if isempty(find(indexchannel(1,:)==x(1,i) & indexchannel(2,:)==x(2,i)));
        fprintf(['[' num2str(x(1,i)) ';' num2str(x(2,i)) '], ']);
        emptychannel=1;
    end
end
if emptychannel==1,
    fprintf(' does not exist!');
    error('there are channels that do not exist!');
end

for i=1:size(x,2),
%    fprintf('removing neuron [%d;%d]\n',x(1,i),x(2,i));
    index=find(indexchannel(1,:)==x(1,i) & indexchannel(2,:)==x(2,i));
    %cut out a peace of t:
    cutT=t(indexchannel(3,index):indexchannel(4,index));
    if indexchannel(3,index)~=1,
        tBefore=t(1:indexchannel(3,index)-1);
    else
        tBefore=[];
    end
    if indexchannel(4,index)~=length(t),
        tAfter=t(indexchannel(4,index)+1:end);
    else
        tAfter=[];
    end
    t=[tBefore,tAfter];
    %update indexes:
    indexchannel(3,find(indexchannel(3,:)>indexchannel(3,index)))=indexchannel(3,find(indexchannel(3,:)>indexchannel(3,index)))-length(cutT);
    indexchannel(4,find(indexchannel(4,:)>indexchannel(4,index)))=indexchannel(4,find(indexchannel(4,:)>indexchannel(4,index)))-length(cutT);
end
%remove channels:
for i=1:size(x,2),
    indexes(i)=find(indexchannel(1,:)==x(1,i) & indexchannel(2,:)==x(2,i));
end
indexchannel(:,indexes)=[];

newT=t;
newIndexchannel=indexchannel;


text:
package utils.headers;

import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.IOException;
import java.math.BigInteger;

import giraudsa.marshall.exception.UnmarshallExeption;
import utils.BiHashMap;

public class HeaderTypeNonDevinable extends Header {
	private static final BiHashMap<Integer, Integer, HeaderTypeNonDevinable> encodageSmallIdEtSmallIdTypeToHeader = new BiHashMap<>();

	protected static Header getHeader(final int smallId, final short smallIdType) {
		final int toBeConsideredForNextBytes = smallId > HeaderVerySmallId.getMaxVerySmallId()
				? smallId - HeaderVerySmallId.getMaxVerySmallId()
				: smallId;
		int encodageSmallId = 0;
		int encodageSmallIdType = 0;
		encodageSmallId = ByteHelper.getMinimumEncodage(toBeConsideredForNextBytes);
		encodageSmallIdType = ByteHelper.getMinimumEncodage(smallIdType);
		return encodageSmallIdEtSmallIdTypeToHeader.get(encodageSmallId, encodageSmallIdType);
	}

	protected static void init() {
		new HeaderTypeNonDevinable(1, 1);
		new HeaderTypeNonDevinable(2, 1);
		new HeaderTypeNonDevinable(3, 1);
		new HeaderTypeNonDevinable(4, 1);
		new HeaderTypeNonDevinable(1, 2);
		new HeaderTypeNonDevinable(2, 2);
		new HeaderTypeNonDevinable(3, 2);
		new HeaderTypeNonDevinable(4, 2);
	}

	private final int encodageSmallId;
	private final int encodageSmallIdType;

	public HeaderTypeNonDevinable(final int encodageSmallId, final int encodageSmallIdType) {
		super();
		this.encodageSmallId = encodageSmallId;
		this.encodageSmallIdType = encodageSmallIdType;
		encodageSmallIdEtSmallIdTypeToHeader.put(encodageSmallId, encodageSmallIdType, this);
	}

	@Override
	public short getSmallIdType(final DataInputStream input) throws IOException, UnmarshallExeption {
		final byte[] tmp = new byte[encodageSmallIdType];
		input.readFully(tmp);
		final BigInteger bi = new BigInteger(tmp);
		return bi.shortValue();
	}

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

	@Override
	public int readSmallId(final DataInputStream input, final int maxId) throws IOException, UnmarshallExeption {
		final byte[] tmp = new byte[encodageSmallId];
		input.readFully(tmp);
		final BigInteger bi = new BigInteger(tmp);
		return maxId >= HeaderVerySmallId.getMaxVerySmallId() ? bi.intValue() + HeaderVerySmallId.getMaxVerySmallId()
				: bi.intValue();
	}

	@Override
	public void write(final DataOutput output, final int smallId, final short smallIdType, final boolean isDejaVuType,
			final Class<?> type) throws IOException {
		output.writeByte(headerByte);
		final int toBeConsideredForNextBytes = smallId > HeaderVerySmallId.getMaxVerySmallId()
				? smallId - HeaderVerySmallId.getMaxVerySmallId()
				: smallId;
		output.write(BigInteger.valueOf(toBeConsideredForNextBytes).toByteArray());
		output.write(BigInteger.valueOf(smallIdType).toByteArray());
		if (!isDejaVuType)
			output.writeUTF(type.getName());

	}

}

redpajama_set_name: RedPajamaGithub


text:
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/)

Integrator-extension-samples provides non-managed, pre-built integrations that can easily be installed into any [integrator.io](http://www.celigo.com/ipaas-integration-platform/) account, and can be used as starter kits to help users jump start building their own custom DIY integrations. It includes all the components needed to integrate two or more applications, including connections, exports, imports, flows, data mappings, etc. You can modify it in any way you see fit for your own custom integration requirements.

_**Note**: In order to use these integrations, the user should know how to [create a data flow on integrator.io](http://support.celigo.com/hc/en-us/articles/216377808-Create-Data-Flows-in-Integrator-io) and the use of [integrator-extension](https://github.com/celigo/integrator-extension)._

Currently we have below integrations available for user reference:

* [MySQL](#mysql)
* [Netsuite](#netsuite)
* [Salesforce](#salesforce)

## MySQL

The MySQL integration enables a user to import/export data between a MySQL application and third party through  [integrator.io](http://www.celigo.com/ipaas-integration-platform/). The integration has two components.

#### Export
Other then the standard configuration options provided in the export UI, the user can also make use of configuration box to set/create the fields as per requirements. The existing integration has support for below options.

```sh
{
  "table": "TABLE_NAME",
  "size": 2
}
```
* **_table_**: Name of the SQL table from which data needs to be exported.
* **_size_**: Number of rows to be exported at a time.

#### Import
Along with the standard import options provided by [integrator.io](http://www.celigo.com/ipaas-integration-platform/), below options are available to the user to set as per the requirements. The user can expand the functionality by creating new fields.
```sh
{
  "importType": "add",
  "table": "TABLE_NAME",
  "ignoreExistingRecords": "false",
  "ignoreMissingRecords": "false",
  "existingRecCondition": {
    "condition": " COL_A = ? and COL_B = ? ",
    "colField": ["COL_C","COL_D"]
  }
}
```
* _**importType**_: Supported operations are add/update/addUpdate.
* _**table**_: Table name for importing data.
* _**ignoreExistingRecords**_: (For ADD) When set to false will try to insert the rows without checking the existing records.
* _**ignoreMissingRecords**_: (For UPDATE) When set to false will not throw any error when the record to be updated is missing.
* _**existingRecCondition**_: A MySQL where condition to check if the record already exists. It should be configured for all kind of operations except that of pure INSERT i.e. importType is "ADD" and ignoreExistingRecords is "true".
* _**condition**_: It is used for checking existing records and updating records. The condition needs to be written in MySQL syntax where COL_A, COL_B represent table columns of import table.
* _**colField**_: COL_C, COL_D are the table columns against which COL_A, COL_B needs to be checked.

_**Note**: Make sure that for all the operations of type ADD, UPDATE and ADDUPDATE, the EXTERNAL_ID of source table is mapped to the auto_increment key field of destination table._

## Netsuite

Netsuite integration enables a user to import/export the attachments along with the record. This is done using the hooks functionality provided by [integrator.io](http://www.celigo.com/ipaas-integration-platform/) and netsuite nlapi's.

#### Export

In order to export attachment along with the record, a blob key needs to be generated for the attachment. This key is then sent along with the record. A sample blob key generation request looks like below.

```sh
{
  "url" : "https://api.integrator.io/v1/connections/" + _connectionId + "/export",
  "method" : "POST",
  "headers" : {
    "content-Type" : "application/json"
  },
  "auth" : {
    "bearer" : bearerToken
  },
  "json" : {
    "export" : {
      "type" : "blob",
      "netsuite" : {
        "internalId" : internalId
      }
    }
  }
}
```
* **__connectionId_**: netsuite connectionId used for the export.
* **_bearerToken_**: one time token provided in the hook options.
* **_internalId_**: attachment internalId in netsuite.

Upon successful completion the response should contain blob key and other netsuite data.

```sh
{
  "blobKey" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "netsuite" : {...}
}
```
The blob key received in the response could then be used to import the file on other systems.

#### Import

In order to import the attachment on netsuite the record should contain the blob key for the attachment. Below is the sample request to import the data.

```sh
{
  "url" : "https://api.integrator.io/v1/connections/" + _connectionId + "/import",
  "method" : "POST",
  "headers" : {
    "content-Type" : "application/json"
  },
  "auth" : {
    "bearer" : bearerToken
  },
  "json" : {
    "import" : {
      "blobKey" : blobKey,
      "netsuite" : {
        "operation" : operation,
        "file" : {
          "name" : fileName,
          "fileType" : "_PLAINTEXT",
          "folder" : folderInternalId,
          "internalId" : fileInternalId
        }
      }
    },
    "data" : {}
  }
}
```
* **__connectionId_**: netsuite connectionId used for the import.
* **_bearerToken_**: one time token provided in the hook options.
* **_operation_**: add,update or addupdate. "addupdate" is just a convenience based on whether internalId is present.
* **_name_**: file name, including extension name(usually .pdf).
* **_fileType_**: all NS file types from wsdl, optional, recommended to unset when "name" includes extension name.
* **_folder_**: internalId for the folder.
* **_internalId_**: internalId for the file, should not be used with operation "add", required with "update", optional with "addupdate".

Upon successful import on netsuite the response should be in below format

```sh
{
  "netsuite" : {
    "isSuccess" : true,
    "id" : attachmentInternalId
  }
}
```

## Salesforce

Salesforce integration enables user to export/import record along with the attachment.

#### Export

In order to export attachment along with the record, a blob key needs to be generated for the attachment. This key is then sent along with the record. A sample blob key generation request looks like below.

```sh
{
  "url" : "https://api.integrator.io/v1/connections/" + _connectionId + "/export",
  "method" : "POST",
  "headers" : {
    "content-Type" : "application/json"
  },
  "auth" : {
    "bearer" : bearerToken
  },
  "json" : {
    "export" : {
      "type" : "blob",
      "salesforce" : {
        "sObjectType" : "Attachment",
        "id" : attachmentId
      }
    }
  }
}

```
* **__connectionId_**: salesforce connectionId used for the export.
* **_bearerToken_**: one time token provided in the hook options.
* **id**: attachment id in salesforce.

Upon successful completion the response should contain blob key and other salesforce data.

```sh
{
  "blobKey" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "salesforce" : {...}
}
```
The blob key received in the response could then be used to import the file on other systems.

#### Import

In order to import the attachment on salesforce the record should contain the blob key for the attachment. Below is the sample request to import the data.

```sh
{
  "url" : "https://api.integrator.io/v1/connections/" + _connectionId + "/import",
  "method" : "POST",
  "headers" : {
    "content-Type" : "application/json"
  },
  "auth" : {
    "bearer" : bearerToken
  },
  "json" : {
    "import" : {
      "blobKey" : blobKey,
      "salesforce" : {
        "operation" : operation,
        "sObjectType" : "attachment",
        "attachment" : {
          "id" : salesforceId,
          "name" : name,
          "parentId" : parentId,
          "contentType" : "application/pdf",
          "isprivate" : true,
          "description" : description
        }
      }
    },
    "data" : {}
  }
}
```
* **__connectionId_**: salesforce connectionId used for the import.
* **_bearerToken_**: one time token provided in the hook options.
* **_operation_**: insert, update.
* **_id_**: salesforce id of file. Required only for update.
* **_name_**: file name, including extension name(usually .pdf). Required only for insert.
* **_parentId_**: salesforce id of the parent record. Required only for insert.
* **_contentType_**: MIME types, optional.
* **_isprivate_**: boolean value, optional.
* **_description_**: optional description.

Upon successful import on salesforce the response should be in below format

```sh
{
  "salesforce" : {
    "success" : true,
    "id" : attachmentId
  }
}
```

## Contact
_If you need the sample integrations or any assistance please drop a mail to celigo-labs@celigo.com._


text:
package fr.polytech.ihm.controller;

import fr.polytech.ihm.CreateGridPane;
import fr.polytech.ihm.CreatePagination;
import fr.polytech.ihm.model.Product;
import fr.polytech.ihm.model.Products;
import javafx.fxml.FXML;
import javafx.scene.control.Pagination;
import javafx.scene.layout.GridPane;

import java.util.Arrays;
import java.util.List;

/**
 * Created by Quentin on 11/03/2017.
 */
public class CenterDVDController {

    @FXML
    private Pagination pagination;

    @FXML
    private GridPane flagshipProduct;

    @FXML
    public void initialize() throws Exception {

        List<Product> product = Arrays.asList(new Product("/images/dvd/promo.jpg",10),
                new Product("/images/dvd/dvd-coffret-transformers.jpg",10),
                new Product("/images/dvd/filmDocteurFrankeisten.jpg",10));

        Products products = new Products(product);

        List<Product> productFlagship = Arrays.asList(new Product("/images/dvd/dvd-coffret-transformers.jpg",10),
                new Product("/images/dvd/dvd-coffret-transformers.jpg",10),
                new Product("/images/dvd/dvd-coffret-transformers.jpg",10),
                new Product("/images/dvd/filmDocteurFrankeisten.jpg",10),
                new Product("/images/dvd/filmDocteurFrankeisten.jpg",10),
                new Product("/images/dvd/filmDocteurFrankeisten.jpg",10));

        Products productsFlagship = new Products(productFlagship);

        CreatePagination createPagination = new CreatePagination();
        CreateGridPane gridPane = new CreateGridPane();

        pagination.setPageCount(products.getProducts().size());
        pagination.setPageFactory((Integer pageIndex) -> createPagination.createPage(pageIndex, products));
        flagshipProduct = gridPane.create(productsFlagship, flagshipProduct);

    }

}


text:
package com.facebook.buck.go;

import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.step.AbstractTestStep;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.nio.file.Path;
import java.util.Optional;

/** Run a go test command and stream the output to a file. */
public class GoTestStep extends AbstractTestStep {

  private static final String NAME = "go test";

  public GoTestStep(
      ProjectFilesystem filesystem,
      Path workingDirectory,
      ImmutableList<String> command,
      ImmutableMap<String, String> env,
      Path exitCode,
      Optional<Long> testRuleTimeoutMs,
      Path output) {
    super(
        NAME,
        filesystem,
        Optional.of(workingDirectory),
        command,
        Optional.of(env),
        exitCode,
        testRuleTimeoutMs,
        output);
  }

  @Override
  public boolean equals(Object o) {
    return (o instanceof GoTestStep) && super.equals(o);
  }

  @Override
  public int hashCode() {
    return super.hashCode();
  }
}


text:
BuildFire plugin to view Google Forms in your app.

### How to run test cases
- npm install
- karma start


text:
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.api.ads.admanager.jaxws.v202202;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *             Gets a {@link CreativeWrapperPage} of {@link CreativeWrapper}
 *             objects that satisfy the given {@link Statement#query}. The following
 *             fields are supported for filtering:
 *
 *

 *

 *             PQL Property	 Object Property
 *

 *

 *             {@code id}
 *             {@link CreativeWrapper#id}
 *

 *

 *             {@code labelId}
 *             {@link CreativeWrapper#labelId}
 *

 *

 *             {@code status}
 *             {@link CreativeWrapper#status}
 *

 *

 *             {@code ordering}
 *             {@link CreativeWrapper#ordering}
 *

 *

 *
 *
 *
Java class for getCreativeWrappersByStatement element declaration.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <element name="getCreativeWrappersByStatement">
 *   <complexType>
 *     <complexContent>
 *       <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *         <sequence>
 *           <element name="filterStatement" type="{https://www.google.com/apis/ads/publisher/v202202}Statement" minOccurs="0"/>
 *         </sequence>
 *       </restriction>
 *     </complexContent>
 *   </complexType>
 * </element>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "filterStatement"
})
@XmlRootElement(name = "getCreativeWrappersByStatement")
public class CreativeWrapperServiceInterfacegetCreativeWrappersByStatement {

    protected Statement filterStatement;

    /**
     * Gets the value of the filterStatement property.
     *
     * @return
     *     possible object is
     *     {@link Statement }
     *
     */
    public Statement getFilterStatement() {
        return filterStatement;
    }

    /**
     * Sets the value of the filterStatement property.
     *
     * @param value
     *     allowed object is
     *     {@link Statement }
     *
     */
    public void setFilterStatement(Statement value) {
        this.filterStatement = value;
    }

}


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

<title>PayPal Adaptive Payments SDK - API Calls sample</title>
<link href="Common/style.css" rel="stylesheet" type="text/css" />

				API Calls Sample - Home

		<?php
		include 'Common/menu.html';
		?>


text:
#ifndef BABYLON_SHADERS_SHADERS_INCLUDE_REFLECTION_FUNCTION_FX_H
#define BABYLON_SHADERS_SHADERS_INCLUDE_REFLECTION_FUNCTION_FX_H

namespace BABYLON {

extern const char* reflectionFunction;

const char* reflectionFunction
  = R"ShaderCode(

vec3 parallaxCorrectNormal( vec3 vertexPos, vec3 origVec, vec3 cubeSize, vec3 cubePos ) {
    // Find the ray intersection with box plane
    vec3 invOrigVec = vec3(1.0,1.0,1.0) / origVec;
    vec3 halfSize = cubeSize * 0.5;
    vec3 intersecAtMaxPlane = (cubePos + halfSize - vertexPos) * invOrigVec;
    vec3 intersecAtMinPlane = (cubePos - halfSize - vertexPos) * invOrigVec;
    // Get the largest intersection values (we are not intersted in negative values)
    vec3 largestIntersec = max(intersecAtMaxPlane, intersecAtMinPlane);
    // Get the closest of all solutions
    float distance = min(min(largestIntersec.x, largestIntersec.y), largestIntersec.z);
    // Get the intersection position
    vec3 intersectPositionWS = vertexPos + origVec * distance;
    // Get corrected vector
    return intersectPositionWS - cubePos;
}

vec3 computeFixedEquirectangularCoords(vec4 worldPos, vec3 worldNormal, vec3 direction)
{
    float lon = atan(direction.z, direction.x);
    float lat = acos(direction.y);
    vec2 sphereCoords = vec2(lon, lat) * RECIPROCAL_PI2 * 2.0;
    float s = sphereCoords.x * 0.5 + 0.5;
    float t = sphereCoords.y;

    return vec3(s, t, 0);
}

vec3 computeMirroredFixedEquirectangularCoords(vec4 worldPos, vec3 worldNormal, vec3 direction)
{
    float lon = atan(direction.z, direction.x);
    float lat = acos(direction.y);
    vec2 sphereCoords = vec2(lon, lat) * RECIPROCAL_PI2 * 2.0;
    float s = sphereCoords.x * 0.5 + 0.5;
    float t = sphereCoords.y;

    return vec3(1.0 - s, t, 0);
}

vec3 computeEquirectangularCoords(vec4 worldPos, vec3 worldNormal, vec3 eyePosition, mat4 reflectionMatrix)
{
    vec3 cameraToVertex = normalize(worldPos.xyz - eyePosition);
    vec3 r = normalize(reflect(cameraToVertex, worldNormal));
    r = vec3(reflectionMatrix * vec4(r, 0));
    float lon = atan(r.z, r.x);
    float lat = acos(r.y);
    vec2 sphereCoords = vec2(lon, lat) * RECIPROCAL_PI2 * 2.0;
    float s = sphereCoords.x * 0.5 + 0.5;
    float t = sphereCoords.y;

    return vec3(s, t, 0);
}

vec3 computeSphericalCoords(vec4 worldPos, vec3 worldNormal, mat4 view, mat4 reflectionMatrix)
{
    vec3 viewDir = normalize(vec3(view * worldPos));
    vec3 viewNormal = normalize(vec3(view * vec4(worldNormal, 0.0)));

    vec3 r = reflect(viewDir, viewNormal);
    r = vec3(reflectionMatrix * vec4(r, 0));
    r.z = r.z - 1.0;

    float m = 2.0 * length(r);

    return vec3(r.x / m + 0.5, 1.0 - r.y / m - 0.5, 0);
}

vec3 computePlanarCoords(vec4 worldPos, vec3 worldNormal, vec3 eyePosition, mat4 reflectionMatrix)
{
    vec3 viewDir = worldPos.xyz - eyePosition;
    vec3 coords = normalize(reflect(viewDir, worldNormal));

    return vec3(reflectionMatrix * vec4(coords, 1));
}

vec3 computeCubicCoords(vec4 worldPos, vec3 worldNormal, vec3 eyePosition, mat4 reflectionMatrix)
{
    vec3 viewDir = normalize(worldPos.xyz - eyePosition);

    // worldNormal has already been normalized.
    vec3 coords = reflect(viewDir, worldNormal);

    coords = vec3(reflectionMatrix * vec4(coords, 0));

    #ifdef INVERTCUBICMAP
        coords.y *= -1.0;
    #endif

    return coords;
}

vec3 computeCubicLocalCoords(vec4 worldPos, vec3 worldNormal, vec3 eyePosition, mat4 reflectionMatrix, vec3 reflectionSize, vec3 reflectionPosition)
{
    vec3 viewDir = normalize(worldPos.xyz - eyePosition);

    // worldNormal has already been normalized.
    vec3 coords = reflect(viewDir, worldNormal);

    coords = parallaxCorrectNormal(worldPos.xyz, coords, reflectionSize, reflectionPosition);

    coords = vec3(reflectionMatrix * vec4(coords, 0));

    #ifdef INVERTCUBICMAP
        coords.y *= -1.0;
    #endif

    return coords;
}

vec3 computeProjectionCoords(vec4 worldPos, mat4 view, mat4 reflectionMatrix)
{
    return vec3(reflectionMatrix * (view * worldPos));
}

vec3 computeSkyBoxCoords(vec3 positionW, mat4 reflectionMatrix)
{
    return vec3(reflectionMatrix * vec4(positionW, 1.));
}

#ifdef REFLECTION
vec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)
{
#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED
    vec3 direction = normalize(vDirectionW);
    return computeMirroredFixedEquirectangularCoords(worldPos, worldNormal, direction);
#endif

#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED
    vec3 direction = normalize(vDirectionW);
    return computeFixedEquirectangularCoords(worldPos, worldNormal, direction);
#endif

#ifdef REFLECTIONMAP_EQUIRECTANGULAR
    return computeEquirectangularCoords(worldPos, worldNormal, vEyePosition.xyz, reflectionMatrix);
#endif

#ifdef REFLECTIONMAP_SPHERICAL
    return computeSphericalCoords(worldPos, worldNormal, view, reflectionMatrix);
#endif

#ifdef REFLECTIONMAP_PLANAR
    return computePlanarCoords(worldPos, worldNormal, vEyePosition.xyz, reflectionMatrix);
#endif

#ifdef REFLECTIONMAP_CUBIC
    #ifdef USE_LOCAL_REFLECTIONMAP_CUBIC
        return computeCubicLocalCoords(worldPos, worldNormal, vEyePosition.xyz, reflectionMatrix, vReflectionSize, vReflectionPosition);
    #else
        return computeCubicCoords(worldPos, worldNormal, vEyePosition.xyz, reflectionMatrix);
    #endif
#endif

#ifdef REFLECTIONMAP_PROJECTION
    return computeProjectionCoords(worldPos, view, reflectionMatrix);
#endif

#ifdef REFLECTIONMAP_SKYBOX
    return computeSkyBoxCoords(vPositionUVW, reflectionMatrix);
#endif

#ifdef REFLECTIONMAP_EXPLICIT
    return vec3(0, 0, 0);
#endif
}
#endif

)ShaderCode";

} // end of namespace BABYLON

#endif // end of BABYLON_SHADERS_SHADERS_INCLUDE_REFLECTION_FUNCTION_FX_H


text:
package com.qrcode.reader.camera;

import android.Manifest;
import android.content.Context;
import android.content.res.Configuration;
import android.support.annotation.RequiresPermission;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.ViewGroup;

import com.google.android.gms.common.images.Size;

import java.io.IOException;

public class CameraSourcePreview extends ViewGroup {
    private static final String TAG = CameraSourcePreview.class.getSimpleName();

    private Context mContext;
    private SurfaceView mSurfaceView;
    private boolean mStartRequested;
    private boolean mSurfaceAvailable;
    private CameraSource mCameraSource;

    public CameraSourcePreview(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        mStartRequested = false;
        mSurfaceAvailable = false;

        mSurfaceView = new SurfaceView(context);
        mSurfaceView.getHolder().addCallback(new SurfaceCallback());
        addView(mSurfaceView);
    }

    @RequiresPermission(Manifest.permission.CAMERA)
    public void start(CameraSource cameraSource) throws IOException, SecurityException {
        if (cameraSource == null) {
            stop();
        }

        mCameraSource = cameraSource;

        if (mCameraSource != null) {
            mStartRequested = true;
            startIfReady();
        }
    }

    public void stop() {
        if (mCameraSource != null) {
            mCameraSource.stop();
        }
    }

    public void release() {
        if (mCameraSource != null) {
            mCameraSource.release();
            mCameraSource = null;
        }
    }

    @RequiresPermission(Manifest.permission.CAMERA)
    private void startIfReady() throws IOException, SecurityException {
        if (mStartRequested && mSurfaceAvailable) {
            mCameraSource.start(mSurfaceView.getHolder());
            mStartRequested = false;
        }
    }

    private class SurfaceCallback implements SurfaceHolder.Callback {
        @Override
        public void surfaceCreated(SurfaceHolder surface) {
            mSurfaceAvailable = true;
            try {
                startIfReady();
            } catch (SecurityException se) {
                Log.e(TAG,"Do not have permission to start the camera", se);
            } catch (IOException e) {
                Log.e(TAG, "Could not start camera source.", e);
            }
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder surface) {
            mSurfaceAvailable = false;
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        }
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        int previewWidth = 320;
        int previewHeight = 240;
        if (mCameraSource != null) {
            Size size = mCameraSource.getPreviewSize();
            if (size != null) {
                previewWidth = size.getWidth();
                previewHeight = size.getHeight();
            }
        }

        // Swap width and height sizes when in portrait, since it will be rotated 90 degrees
        if (isPortraitMode()) {
            int tmp = previewWidth;
            previewWidth = previewHeight;
            previewHeight = tmp;
        }

        final int viewWidth = right - left;
        final int viewHeight = bottom - top;

        int childWidth;
        int childHeight;
        int childXOffset = 0;
        int childYOffset = 0;
        float widthRatio = (float) viewWidth / (float) previewWidth;
        float heightRatio = (float) viewHeight / (float) previewHeight;
        if (widthRatio > heightRatio) {
            childWidth = viewWidth;
            childHeight = (int) ((float) previewHeight * widthRatio);
            childYOffset = (childHeight - viewHeight) / 2;
        } else {
            childWidth = (int) ((float) previewWidth * heightRatio);
            childHeight = viewHeight;
            childXOffset = (childWidth - viewWidth) / 2;
        }

        for (int i = 0; i < getChildCount(); ++i) {
            getChildAt(i).layout(
                    -1 * childXOffset, -1 * childYOffset,
                    childWidth - childXOffset, childHeight - childYOffset);
        }

        try {
            startIfReady();
        } catch (IOException e) {
            Log.e(TAG, "Could not start camera source.", e);
        } catch (SecurityException se) {
            Log.e(TAG, "Does not have permission to start the camera.", se);
        }
    }

    private boolean isPortraitMode() {
        int orientation = mContext.getResources().getConfiguration().orientation;
        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            return false;
        }
        if (orientation == Configuration.ORIENTATION_PORTRAIT) {
            return true;
        }

        Log.d(TAG, "isPortraitMode returning false by default");
        return false;
    }
}


text:
/*
 * GeomteyTypeChecker.java
 *
 * Created on September 29, 2003, 9:01 PM
 */

package wts.GIS.utils;

/**
 *
 * @author  wstockha
 */

import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.Polygon;

import com.vividsolutions.jts.geom.MultiLineString;
import com.vividsolutions.jts.geom.MultiPoint;
import com.vividsolutions.jts.geom.MultiPolygon;

public class GeometryTypeChecker {

    private static Class lineStringClass = LineString.class;
    private static Class pointClass = Point.class;
    private static Class polygonClass = Polygon.class;

    private static Class multiLineStringClass = MultiLineString.class;
    private static Class multiPointClass = MultiPoint.class;
    private static Class multiPolygonClass = MultiPolygon.class;

    /** Creates a new instance of GeomteyTypeChecker */
    public GeometryTypeChecker() {
    }

    public static boolean isLineString(Object obj) {
        return lineStringClass.isInstance(obj);
    }

    public static boolean isLineString(Class clz) {
        return lineStringClass.equals(clz);
    }

    public static boolean isPoint(Object obj) {
        return pointClass.isInstance(obj);
    }

    public static boolean isPoint(Class clz) {
        return pointClass.equals(clz);
    }

    public static boolean isPolygon(Object obj) {
        return polygonClass.isInstance(obj);
    }

    public static boolean isPolygon(Class clz) {
        return polygonClass.equals(clz);
    }

    public static boolean isMultiLineString(Object obj) {
        return multiLineStringClass.isInstance(obj);
    }

    public static boolean isMultiLineString(Class clz) {
        return multiLineStringClass.equals(clz);
    }

    public static boolean isMultiPoint(Object obj) {
        return multiPointClass.isInstance(obj);
    }

    public static boolean isMultiPoint(Class clz) {
        return multiPointClass.equals(clz);
    }

    public static boolean isMultiPolygon(Object obj) {
        return multiPolygonClass.isInstance(obj);
    }

    public static boolean isMultiPolygon(Class clz) {
        return multiPolygonClass.equals(clz);
    }

}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.devtools.j2objc.ast;

import com.google.common.base.Preconditions;

import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;

import java.util.List;

/**
 * Method invocation node type.
 */
public class MethodInvocation extends Expression {

  private IMethodBinding methodBinding = null;
  private ChildLink<Expression> expression = ChildLink.create(Expression.class, this);
  private ChildLink<SimpleName> name = ChildLink.create(SimpleName.class, this);
  private ChildList<Expression> arguments = ChildList.create(Expression.class, this);

  public MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation jdtNode) {
    super(jdtNode);
    methodBinding = jdtNode.resolveMethodBinding();
    expression.set((Expression) TreeConverter.convert(jdtNode.getExpression()));
    name.set((SimpleName) TreeConverter.convert(jdtNode.getName()));
    for (Object argument : jdtNode.arguments()) {
      arguments.add((Expression) TreeConverter.convert(argument));
    }
  }

  public MethodInvocation(MethodInvocation other) {
    super(other);
    methodBinding = other.getMethodBinding();
    expression.copyFrom(other.getExpression());
    name.copyFrom(other.getName());
    arguments.copyFrom(other.getArguments());
  }

  public MethodInvocation(IMethodBinding binding, Expression expression) {
    methodBinding = binding;
    this.expression.set(expression);
    name.set(new SimpleName(binding));
  }

  @Override
  public Kind getKind() {
    return Kind.METHOD_INVOCATION;
  }

  public IMethodBinding getMethodBinding() {
    return methodBinding;
  }

  public void setMethodBinding(IMethodBinding newMethodBinding) {
    methodBinding = newMethodBinding;
  }

  @Override
  public ITypeBinding getTypeBinding() {
    return methodBinding != null ? methodBinding.getReturnType() : null;
  }

  public Expression getExpression() {
    return expression.get();
  }

  public void setExpression(Expression newExpression) {
    expression.set(newExpression);
  }

  public SimpleName getName() {
    return name.get();
  }

  public void setName(SimpleName newName) {
    name.set(newName);
  }

  public List<Expression> getArguments() {
    return arguments;
  }

  @Override
  protected void acceptInner(TreeVisitor visitor) {
    if (visitor.visit(this)) {
      expression.accept(visitor);
      name.accept(visitor);
      arguments.accept(visitor);
    }
    visitor.endVisit(this);
  }

  @Override
  public MethodInvocation copy() {
    return new MethodInvocation(this);
  }

  @Override
  public void validateInner() {
    super.validateInner();
    Preconditions.checkNotNull(methodBinding);
    Preconditions.checkNotNull(name.get());
  }
}


text:
program main
  ! Default
  implicit none

  ! Parameters
  integer(4), parameter :: max_int = 1999999

  ! Variables
  integer(8) :: i,sum

  ! Do work
  sum = 0
  do i=2,max_int
     if (is_prime(i)) then
        sum = sum + i
     endif
  enddo

  ! Write out result
  write(*,*) "Sum of primes less than ",max_int,": ",sum

contains

  pure function is_prime(targ)
    ! Default
    implicit none

    ! Function arguments
    integer(8), intent(in) :: targ
    logical                :: is_prime

    ! Local variables
    integer(8) :: i,max_try

    ! Find the max we should try
    max_try = int(sqrt(1D0*targ))

    do i=2,max_try
       if (mod(targ,i)==0) then
          is_prime = .false.
          return
       endif
    enddo

    is_prime = .true.
    return
  end function is_prime

end program main


text:
<?php

/**
 * Output directory and file prefix specificity regression tests
 *
 * @package DBSteward
 * @license http://www.opensource.org/licenses/bsd-license.php Simplified BSD License
 * @author Nicholas J Kiraly <kiraly.nicholas@gmail.com>
 */

require_once __DIR__ . '/../dbstewardUnitTestBase.php';

class OutputFileSpecificityTest extends dbstewardUnitTestBase {

  public function setUp() {
    parent::setUp();
  }

  protected function setup_definition_xml(&$base_xml, &$strict_overlay_xml, &$new_table_xml) {
    $base_xml = <<<XML
<dbsteward>
  <database>
    <role>
      <application>app_application</application>
      <owner>postgres</owner>
      <replication>app_slony</replication>
      <readonly>app_readonly</readonly>
    </role>
  </database>
  <schema name="app" owner="ROLE_OWNER">

      <column name="action" type="character varying(16)" null="false" />
      <column name="description" type="character varying(200)"/>
      <rows columns="action, description">
        <row>
          <col>ACTION1</col>
          <col>Action 1</col>
        </row>
        <row>
          <col>ACTION2</col>
          <col>Action 2 Description</col>
        </row>
        <row>
          <col>ACTION3</col>
          <col/>
        </row>
        <row>
          <col>ACTION4</col>
          <col/>
        </row>
        <row>
          <col>ACTION99</col>
          <col>Action 99 Reserved</col>
        </row>
      </rows>

  </schema>
</dbsteward>
XML;
    $strict_overlay_xml = <<<XML
<dbsteward>
  <schema name="app" owner="ROLE_OWNER">

      <column name="description" type="character varying(200)" null="false" />
      <rows columns="action, description">
        <row>
          <col>ACTION1</col>
          <col>Action 1 Alternate Description</col>
        </row>
        <row>
          <col>ACTION3</col>
          <col>Action 3 Custom Action</col>
        </row>
        <row>
          <col>ACTION4</col>
          <col>Action 4 Custom Action</col>
        </row>
        <row>
          <col>ACTION99</col>
          <col>Action 99 Override</col>
        </row>
      </rows>

  </schema>
</dbsteward>
XML;
    $new_table_xml = <<<XML
<dbsteward>
  <schema name="app" owner="ROLE_OWNER">

      <column name="resolution" type="character varying(16)" null="false" />
      <column name="points" type="int" />
      <rows columns="resolution, points">
        <row>
          <col>RESOLUTION1</col>
          <col>5</col>
        </row>
        <row>
          <col>RESOLUTION2</col>
          <col>2</col>
        </row>
        <row>
          <col>RESOLUTION3</col>
          <col/>
        </row>
        <row>
          <col>RESOLUTION4</col>
          <col/>
        </row>
        <row>
          <col>RESOLUTION99</col>
          <col>99</col>
        </row>
      </rows>

  </schema>
</dbsteward>
XML;
  }

  protected function setup_pgsql8($output_file_dir, $output_file_prefix) {
    $base_xml = '';
    $strict_overlay_xml = '';
    $new_table_xml = '';
    $this->setup_definition_xml($base_xml, $strict_overlay_xml, $new_table_xml);

    $this->xml_file_a = dirname(__FILE__) . '/../testdata/pgsql8_unit_test_xml_a.xml';
    $this->xml_file_b = dirname(__FILE__) . '/../testdata/pgsql8_unit_test_xml_b.xml';
    $this->xml_file_c = dirname(__FILE__) . '/../testdata/pgsql8_unit_test_xml_c.xml';

    $this->set_xml_content_a($base_xml);
    $this->set_xml_content_b($strict_overlay_xml);
    $this->set_xml_content_c($new_table_xml);

    dbsteward::$quote_column_names = TRUE;
    dbsteward::$single_stage_upgrade = TRUE;
    dbsteward::$generate_slonik = FALSE;

    $this->setup_output_options('pgsql8', $output_file_dir, $output_file_prefix);
  }

  protected function setup_mysql5($output_file_dir, $output_file_prefix) {
    $base_xml = '';
    $strict_overlay_xml = '';
    $new_table_xml = '';
    $this->setup_definition_xml($base_xml, $strict_overlay_xml, $new_table_xml);

    $this->xml_file_a = dirname(__FILE__) . '/../testdata/mysql5_unit_test_xml_a.xml';
    $this->xml_file_b = dirname(__FILE__) . '/../testdata/mysql5_unit_test_xml_b.xml';
    $this->xml_file_c = dirname(__FILE__) . '/../testdata/mysql5_unit_test_xml_c.xml';

    $this->set_xml_content_a($base_xml);
    $this->set_xml_content_b($strict_overlay_xml);
    $this->set_xml_content_c($new_table_xml);

    dbsteward::$quote_column_names = TRUE;
    dbsteward::$single_stage_upgrade = TRUE;

    $this->setup_output_options('mysql5', $output_file_dir, $output_file_prefix);
  }

  public function output_variance_provider() {
    $output_dir1 = dirname(__FILE__) . '/../testdata_outputdir_dir_' . date("His");
    if (!is_dir($output_dir1)) {
      mkdir($output_dir1);
    }
    $output_dir2 = dirname(__FILE__) . '/../testdata_outputdir_fileprefix_' . date("His");
    if (!is_dir($output_dir2)) {
      mkdir($output_dir2);
    }

    return array(
      array(FALSE, FALSE),
      array($output_dir1, FALSE),
      array($output_dir2, 'gloopy_glop'),
      array(FALSE, 'solo_nobo'),
    );
  }

  protected function setup_output_options($setup_file_prefix, $output_file_dir, $output_file_prefix) {
    dbsteward::$file_output_directory = FALSE;
    dbsteward::$file_output_prefix = FALSE;

    if ($output_file_dir === FALSE) {
      $this->output_prefix = dirname(__FILE__) . '/../testdata';
    } else {
      $this->output_prefix = $output_file_dir;
      // match dbsteward specification
      dbsteward::$file_output_directory = $output_file_dir;
    }

    if ($output_file_prefix === FALSE) {
      $this->output_prefix .= '/' . $setup_file_prefix . '_test_column_nulls';
    } else {
      $this->output_prefix .= '/' . $setup_file_prefix . '_' . $output_file_prefix;
      // match dbsteward specification
      dbsteward::$file_output_prefix = $setup_file_prefix . '_' . $output_file_prefix;
    }
  }

  /**
   * @group pgsql8
   * @dataProvider output_variance_provider
   */
  public function testUpgradeIdenticalDDLPgsql8($output_file_dir, $output_file_prefix) {
    $this->apply_options_pgsql8();
    $this->setup_pgsql8($output_file_dir, $output_file_prefix);

    $base_db_doc = xml_parser::xml_composite(array($this->xml_file_a));
    $upgrade_db_doc = xml_parser::xml_composite(array($this->xml_file_a, $this->xml_file_a));
    pgsql8::build_upgrade('', 'column_nulls_identical_test_pgsql8_old', $base_db_doc, array(), $this->output_prefix, 'column_nulls_identical_test_pgsql8_new', $upgrade_db_doc, array());

    $text = file_get_contents($this->output_prefix . '_upgrade_single_stage.sql');
    $this->assertNotRegExp('/ALTER\s+/', $text, 'Diff SQL output contains ALTER statements');
    $this->assertNotRegExp('/UPDATE\s+/', $text, 'Diff SQL output contains UPDATE statements');
    $this->assertNotRegExp('/INSERT\s+/', $text, 'Diff SQL output contains INSERT statements');
    $this->assertNotRegExp('/DELETE\s+/', $text, 'Diff SQL output contains DELETE statements');

    // and do identical comparison with strict definitions on top
    $base_db_doc = xml_parser::xml_composite(array($this->xml_file_a, $this->xml_file_b));
    $upgrade_db_doc = xml_parser::xml_composite(array($this->xml_file_a, $this->xml_file_b));
    pgsql8::build_upgrade('', 'column_nulls_identical_strict_pgsql8_old', $base_db_doc, array(), $this->output_prefix, 'column_nulls_identical_strict_pgsql8_new', $upgrade_db_doc, array());

    $text = file_get_contents($this->output_prefix . '_upgrade_single_stage.sql');
    $this->assertNotRegExp('/ALTER\s+/', $text, 'Diff SQL output contains ALTER statements');
    $this->assertNotRegExp('/UPDATE\s+/', $text, 'Diff SQL output contains UPDATE statements');
    $this->assertNotRegExp('/INSERT\s+/', $text, 'Diff SQL output contains INSERT statements');
    $this->assertNotRegExp('/DELETE\s+/', $text, 'Diff SQL output contains DELETE statements');
  }

  /**
   * @group mysql5
   * @dataProvider output_variance_provider
   */
  public function testUpgradeIdenticalDDLMysql5($output_file_dir, $output_file_prefix) {
    $this->apply_options_mysql5();
    $this->setup_mysql5($output_file_dir, $output_file_prefix);

    $base_db_doc = xml_parser::xml_composite(array($this->xml_file_a));
    $upgrade_db_doc = xml_parser::xml_composite(array($this->xml_file_a, $this->xml_file_a));
    mysql5::build_upgrade('', 'column_nulls_identical_test_mysql5_old', $base_db_doc, array(), $this->output_prefix, 'column_nulls_identical_test_mysql5_new', $upgrade_db_doc, array());

    $text = file_get_contents($this->output_prefix . '_upgrade_single_stage.sql');

    $this->assertNotRegExp('/ALTER\s+/', $text, 'Diff SQL output contains ALTER statements');
    $this->assertNotRegExp('/UPDATE\s+/', $text, 'Diff SQL output contains UPDATE statements');
    $this->assertNotRegExp('/INSERT\s+/', $text, 'Diff SQL output contains INSERT statements');
    $this->assertNotRegExp('/DELETE\s+/', $text, 'Diff SQL output contains DELETE statements');

    // and do identical comparison with strict definitions on top
    $base_db_doc = xml_parser::xml_composite(array($this->xml_file_a, $this->xml_file_b));
    $upgrade_db_doc = xml_parser::xml_composite(array($this->xml_file_a, $this->xml_file_b));
    mysql5::build_upgrade('', 'column_nulls_identical_strict_mysql5_old', $base_db_doc, array(), $this->output_prefix, 'column_nulls_identical_strict_mysql5_new', $upgrade_db_doc, array());

    $text = file_get_contents($this->output_prefix . '_upgrade_single_stage.sql');

    $this->assertNotRegExp('/ALTER\s+/', $text, 'Diff SQL output contains ALTER statements');
    $this->assertNotRegExp('/UPDATE\s+/', $text, 'Diff SQL output contains UPDATE statements');
    $this->assertNotRegExp('/INSERT\s+/', $text, 'Diff SQL output contains INSERT statements');
    $this->assertNotRegExp('/DELETE\s+/', $text, 'Diff SQL output contains DELETE statements');
  }

  /**
   * @group pgsql8
   * @dataProvider output_variance_provider
   */
  public function testFullBuildPgsql8($output_file_dir, $output_file_prefix) {
    $this->apply_options_pgsql8();
    $this->setup_pgsql8($output_file_dir, $output_file_prefix);

    // build base full, check contents
    $base_db_doc = xml_parser::xml_composite(array($this->xml_file_a, $this->xml_file_a));
    pgsql8::build($this->output_prefix, $base_db_doc);
    $text = file_get_contents($this->output_prefix . '_build.sql');
    // make sure SET NOT NULL is specified for action column
    $this->assertContains('ALTER COLUMN "action" SET NOT NULL', $text);
    // make sure SET NOT NULL is NOT specified for description column
    $this->assertNotContains('ALTER COLUMN "description" SET NOT NULL', $text);

    // build base + strict, check contents
    $strict_db_doc = xml_parser::xml_composite(array($this->xml_file_a, $this->xml_file_b));
    pgsql8::build($this->output_prefix, $strict_db_doc);
    $text = file_get_contents($this->output_prefix . '_build.sql');
    // make sure SET NOT NULL is specified for action column
    $this->assertContains('ALTER COLUMN "action" SET NOT NULL', $text);
    // make sure SET NOT NULL is specified for description column
    $this->assertContains('ALTER COLUMN "description" SET NOT NULL', $text);

    // build base + strict + new table, check contents
    $addtable_db_doc = xml_parser::xml_composite(array($this->xml_file_a, $this->xml_file_b, $this->xml_file_c));
    pgsql8::build($this->output_prefix, $addtable_db_doc);
    $text = file_get_contents($this->output_prefix . '_build.sql');
    // make sure NOT NULL is specified for resolution column
    $this->assertContains('ALTER COLUMN "resolution" SET NOT NULL', $text);
    // make sure NOT NULL is NOT specified for points column
    $this->assertNotContains('ALTER COLUMN "points" SET NOT NULL', $text);
  }

  /**
   * @group mysql5
   * @dataProvider output_variance_provider
   */
  public function testFullBuildMysql5($output_file_dir, $output_file_prefix) {
    $this->apply_options_mysql5();
    $this->setup_mysql5($output_file_dir, $output_file_prefix);

    // build base full, check contents
    $base_db_doc = xml_parser::xml_composite(array($this->xml_file_a, $this->xml_file_a));
    mysql5::build($this->output_prefix, $base_db_doc);
    $text = file_get_contents($this->output_prefix . '_build.sql');
    // make sure NOT NULL is specified for action column
    $this->assertContains('`action` character varying(16) NOT NULL', $text);
    // make sure NOT NULL is NOT specified for description column
    $this->assertNotContains('`description` character varying(200) NOT NULL', $text);

    // build base + strict, check contents
    $strict_db_doc = xml_parser::xml_composite(array($this->xml_file_a, $this->xml_file_b));
    mysql5::build($this->output_prefix, $strict_db_doc);
    $text = file_get_contents($this->output_prefix . '_build.sql');
    // make sure NOT NULL is specified for action column
    $this->assertContains('`action` character varying(16) NOT NULL', $text);
    // make sure NOT NULL is specified for description column
    $this->assertContains('`description` character varying(200) NOT NULL', $text);

    // build base + strict + new table, check contents
    $addtable_db_doc = xml_parser::xml_composite(array($this->xml_file_a, $this->xml_file_b, $this->xml_file_c));
    mysql5::build($this->output_prefix, $addtable_db_doc);
    $text = file_get_contents($this->output_prefix . '_build.sql');
    // make sure NOT NULL is specified for resolution column
    $this->assertContains('`resolution` character varying(16) NOT NULL', $text);
    // make sure NOT NULL is NOT specified for points column
    $this->assertNotContains('`points` int NOT NULL', $text);
  }

  /**
   * @group pgsql8
   * @dataProvider output_variance_provider
   */
  public function testUpgradeNewTablePgsql8($output_file_dir, $output_file_prefix) {
    $this->apply_options_pgsql8();
    $this->setup_pgsql8($output_file_dir, $output_file_prefix);

    // upgrade from base
    // to base + strict action table + new resolution table
    // check null specificity
    $base_db_doc = xml_parser::xml_composite(array($this->xml_file_a));
    $newtable_db_doc = xml_parser::xml_composite(array($this->xml_file_a, $this->xml_file_b, $this->xml_file_c));
    pgsql8::build_upgrade('', 'newtable_upgrade_test_pgsql8_base', $base_db_doc, array(), $this->output_prefix, 'newtable_upgrade_test_pgsql8_newtable', $newtable_db_doc, array());
    $text = file_get_contents($this->output_prefix . '_upgrade_single_stage.sql');
    // make sure NOT NULL is specified for description column
    $this->assertContains('ALTER COLUMN "description" SET NOT NULL', $text);
    // make sure NOT NULL is specified for resolution column
    $this->assertContains('ALTER COLUMN "resolution" SET NOT NULL', $text);
    // make sure NOT NULL is NOT specified for points column
    $this->assertNotContains('ALTER COLUMN "points" SET NOT NULL', $text);
  }

  /**
   * @group mysql5
   * @dataProvider output_variance_provider
   */
  public function testUpgradeNewTableMysql5($output_file_dir, $output_file_prefix) {
    $this->apply_options_mysql5();
    $this->setup_mysql5($output_file_dir, $output_file_prefix);

    // upgrade from base
    // to base + strict action table + new resolution table
    // check null specificity
    $base_db_doc = xml_parser::xml_composite(array($this->xml_file_a));
    $newtable_db_doc = xml_parser::xml_composite(array($this->xml_file_a, $this->xml_file_b, $this->xml_file_c));
    mysql5::build_upgrade('', 'newtable_upgrade_test_pgsql8_base', $base_db_doc, array(), $this->output_prefix, 'newtable_upgrade_test_pgsql8_newtable', $newtable_db_doc, array());
    $text = file_get_contents($this->output_prefix . '_upgrade_single_stage.sql');
    // make sure NOT NULL is specified for description column
    $this->assertContains('`description` character varying(200) NOT NULL', $text);
    // make sure NOT NULL is specified for resolution column
    $this->assertContains('`resolution` character varying(16) NOT NULL', $text);
    // make sure NOT NULL is NOT specified for points column
    $this->assertNotContains('`points` int NOT NULL', $text);
  }

}


text:
var cluster = require('cluster');
var net = require('net');

module.exports = function clusterize(num, callback) {
    var server;

    // `num` argument is optional
    if (typeof num !== 'number') {
        callback = num;
        num = require('os').cpus().length;
    }

    // Master will spawn `num` workers
    if (cluster.isMaster) {
        var workers = [];
        for (var i = 0; i < num; i++) {
            !function spawn(i) {
                workers[i] = cluster.fork();
                // Restart worker on exit
                workers[i].on('exit', function () {
                    console.error('clusterize-session: worker died');
                    spawn(i);
                });
            } (i);
        }

        server = { listen: function () { } }

        //server = net.createServer(function(c) {
        //  var worker;

        //  // Pass connection to random worker
        //  worker = workers[Math.floor(Math.random() * num)];
        //  worker.send('sticky-session:connection', c);
        //});
    } else {
        server = typeof callback === 'function' ? callback() : callback;

        //  // Worker process
        //process.on('message', function(msg, socket) {
        //  if (msg !== 'sticky-session:connection') return;

        //  server.emit('connection', socket);
        //});

        if (!server) throw new Error('Worker hasn\'t created server!');

        // Monkey patch server to do not bind to port
        //var oldListen = server.listen;
        //server.listen = function listen() {
        //    var lastArg = arguments[arguments.length - 1];

        //    if (typeof lastArg === 'function') lastArg();

        //    return oldListen.call(this, null);
        //};
    }

    return server;
};


text:
using System;
using System.IO;
using FluentAssertions;
using NUnit.Framework;

namespace PdfFileInterrogation.Tests.PdfInterrogatorTests
{
    public class given_nonexisting_pdf
    {
        private PdfInterrogator _subject;

        [SetUp]
        public void SetUp()
        {
            var filePath = Path.Combine(Environment.CurrentDirectory, "Bogus.pdf");
            _subject = new PdfInterrogator(filePath);
        }

        [Test]
        public void when_checking_if_file_exists_should_be_false()
        {
            _subject.Exists().Should().BeFalse();
        }

        [Test]
        public void when_checking_for_pdf_should_be_false()
        {
            _subject.IsPdf().Should().BeFalse();
        }

        [Test]
        public void when_checking_for_pdf_with_version_should_be_false()
        {
            _subject.IsPdf(1.0).Should().BeFalse();
        }

        [Test]
        public void when_checking_for_number_of_pages_shoudld_be_false()
        {
            _subject.Has(1).Pages.Should().BeFalse();
        }

        [Test]
        public void when_checking_if_page_contains_text_should_be_false()
        {
            _subject.Page(1).Contains("MONGE").Should().BeFalse();
        }

        [Test]
        public void when_checking_if_page_contains_integer_should_be_False()
        {
            _subject.Page(1).Contains(48).Should().BeFalse();
        }

        [Test]
        public void when_checking_if_page_contains_double_should_be_false()
        {
            _subject.Page(1).Contains(48.05).Should().BeFalse();
        }
    }
}


text:
package com.huawei.esdk.sms.utils;

import java.util.Locale;
import java.util.Map;

import com.huawei.esdk.platform.common.utils.StringUtils;

public abstract class SMSUtils
{
    /**
     * 将号码前缀与用户号码连接为完整的源号码
     *
     * @param prefix 号码前缀
     * @param userNumber 用户号码
     * @return 返回完整的号码
     */
    public static String encodeNumberPrefix(String prefix, String number)
    {
        if (StringUtils.isEmpty(prefix))
        {
            return number;
        }

        if (number.toLowerCase(Locale.getDefault()).indexOf(prefix) == 0)
        {
            return number;
        }

        return prefix.concat(number);
    }

    /**
     * 从完整号码中获取用户号码
     *
     * @param spNumber SP接入号
     * @param fullNumber 完整号码
     * @return 用户号码
     */
    public static String decodeNumberPrefix(String prefix, String number)
    {
        if (StringUtils.isEmpty(prefix) || StringUtils.isEmpty(number))
        {
            return number;
        }

        if (number.toLowerCase(Locale.getDefault()).indexOf(prefix.toLowerCase(Locale.getDefault())) == 0)
        {
            return number.substring(prefix.length());
        }

        return number;
    }

    /**
     * 将SP接入号与用户号码连接为完整的源号码
     *
     * @param spNumber SP接入号
     * @param userNumber 用户号码
     * @return 返回完整的号码
     */
    public static String encodeSPNumber(String spNumber, String userNumber)
    {
        if (!StringUtils.isEmpty(spNumber) && !StringUtils.isEmpty(userNumber))
        {
            return spNumber.concat(userNumber);
        }
        else
        {
            if (!StringUtils.isEmpty(userNumber))
            {
                return userNumber;
            }
            else
            {
                return spNumber;
            }
        }
    }

    /**
     * 从完整号码中获取用户号码
     *
     * @param spNumber SP接入号
     * @param fullNumber 完整号码
     * @return 用户号码
     */
    public static String decodeSPNumber(String spNumber, String fullNumber)
    {
        if (StringUtils.isEmpty(fullNumber) || StringUtils.isEmpty(spNumber))
        {
            return fullNumber;
        }
        else
        {
            if (fullNumber.indexOf(spNumber) == 0)
            {
                return fullNumber.substring(spNumber.length());
            }
            return fullNumber;
        }
    }

    public static String parserHexByte2Str(byte[] byteContent, int start, int end)
    {
        String hexStr = byte2HexStr(byteContent, start, end);
        String[] hexStrArray = hexStr.split(" ");
        StringBuilder result = new StringBuilder();
        for (String str : hexStrArray)
        {
            result.append(str.substring(2));
        }

        return result.toString();
    }

    //From TypeConvertTools
    public static String byte2HexStr(byte buffer[], int sPos, int ePos)
    {
        StringBuffer sb = new StringBuffer(((ePos - sPos) + 1) * 4);
        int mm = 0;
        for (int pos = sPos; pos <= ePos; pos++)
        {
            mm = buffer[pos] & 255;
            sb.append("0x");
            if (mm < 15)
                sb.append("0");
            sb.append(Integer.toHexString(mm));
            sb.append(" ");
        }

        return sb.toString();
    }

    public static byte[] hexStr2Byte(String buffer)
    {
        String arrs[] = buffer.trim().split(" ");
        byte mm = 0;
        byte ret[] = new byte[arrs.length];
        for (int index = 0; index < arrs.length; index++)
        {
            arrs[index] = arrs[index].trim();
            if ((arrs[index].charAt(1) < '0' || arrs[index].charAt(1) > '9') && arrs[index].length() > 2)
                arrs[index] = arrs[index].substring(2);
            mm = (byte)Integer.parseInt(arrs[index], 16);
            ret[index] = mm;
        }

        return ret;
    }

    public static Map<String, String> getDataCodingCharsetMapping(String mappingStr)
    {
        Map<String, String> mapping = StringUtils.parseString(mappingStr, "\\|", ":");
        return mapping;
    }
}


text:
<?php

namespace App\Lib\DsManager\Models;

use App\Lib\DsManager\Helpers\Randomizer;
use App\Lib\DsManager\Models\Common\DsManagerModel;

/**
 * Class Match
 * @package App\Lib\DsManager\Models
 */
class Match extends DsManagerModel
{
    /**
     * @var Team
     */
    private $homeTeam;
    /**
     * @var Team
     */
    private $awayTeam;

    /**
     * Match constructor.
     * @param Team $home
     * @param Team $away
     */
    public function __construct(Team $home, Team $away)
    {
        $this->homeTeam = $home;
        $this->awayTeam = $away;
    }

    /**
     * @return MatchResult
     */
    public function simulate()
    {
        $homePoints = $this->homeTeam->getAvgSkill();
        $awayPoints = $this->awayTeam->getAvgSkill();

        $homePoints += $this->malusModule(
            $this->homeTeam->coach->favouriteModule,
            $this->homeTeam->playersPerRoleArray()
        );
        $awayPoints += $this->malusModule(
            $this->awayTeam->coach->favouriteModule,
            $this->awayTeam->playersPerRoleArray()
        );

        $goalHome = 0;
        $goalAway = 0;

        if (Randomizer::boolOnPercentage(80)) {
            if (($homePoints - $awayPoints) < 0) {
                $goalAway = ($awayPoints - $homePoints) % 6;
                $goalHome += $this->chance();
                $goalAway += $this->chance();
                $goalHome += $this->bonusHome();
            } else {
                $goalHome = ($homePoints - $awayPoints) % 6;
                $goalAway += $this->chance();
                $goalHome += $this->bonusHome();
            }
        } else {
            $goalHome += $this->chance();
            $goalAway += $this->chance();
            $goalHome += $this->bonusHome();
        }
        $goalHome += $this->bonusAge($this->homeTeam);
        $goalAway += $this->bonusAge($this->awayTeam);

        //Bonus on Good GoalKeeper
        $goalies = $this->homeTeam->getBestPlayerForRole("GK");
        $goalAway -= $this->bonusGoalKeeper($goalies);
        $goalies = $this->awayTeam->getBestPlayerForRole("GK");
        $goalHome -= $this->bonusGoalKeeper($goalies);
        //
        $homeModule = new Module($this->homeTeam->coach->favouriteModule);
        $awayModule = new Module($this->awayTeam->coach->favouriteModule);
        if ($homeModule->isOffensive()) {
            $goalHome += Randomizer::boolOnPercentage(50) ? rand(1, 2) : 0;
            $goalAway += Randomizer::boolOnPercentage(20) ? 1 : 0;
        }
        if ($awayModule->isOffensive()) {
            $goalAway += Randomizer::boolOnPercentage(50) ? rand(1, 2) : 0;
            $goalHome += Randomizer::boolOnPercentage(20) ? 1 : 0;
        }
        if ($awayModule->isDefensive()) {
            $goalHome -= Randomizer::boolOnPercentage(50) ? 1 : 0;
        }
        if ($homeModule->isDefensive()) {
            $goalAway -= Randomizer::boolOnPercentage(50) ? 1 : 0;
        }
        $goalHome = $goalHome < 0 ? 0 : $goalHome;
        $goalAway = $goalAway < 0 ? 0 : $goalAway;
        return new MatchResult($goalHome, $goalAway, $this->homeTeam, $this->awayTeam);
    }

    /**
     * @param Team $team
     * @return int
     */
    private function bonusAge(Team $team)
    {
        if ($team->getAvgAge() > 29 || $team->getAvgAge() < 24) {
            return $this->chance();
        }
        return 0;
    }

    /**
     * @param $goalkeeper
     * @return int
     */
    private function bonusGoalKeeper($goalkeeper)
    {
        $skillGoalkeeper = empty($goalkeeper) ? 1 : $goalkeeper->skillAvg;
        return (Randomizer::boolOnPercentage($skillGoalkeeper) ? 1 : 0);
    }

    /**
     * @return int
     */
    private function chance()
    {
        return rand(0, 3);
    }

    /**
     * @return int
     */
    private function bonusHome()
    {
        return Randomizer::boolOnPercentage(66) ? 1 : 0;
    }

    /**
     * @param $moduleString
     * @param $playersRoleArray
     * @return int
     */
    private function malusModule($moduleString, $playersRoleArray)
    {
        $module = new Module($moduleString);
        if ($module->isApplicableToArray($playersRoleArray)) {
            return rand(1, 10);
        } else {
            return (-1) * rand(1, 10);
        }
    }

    /**
     * @param array $ormMatchArray
     * @return Match
     */
    public static function fromArray($ormMatchArray = [])
    {
        $homeTeam = Team::fromArray($ormMatchArray['home_team']);
        $awayTeam = Team::fromArray($ormMatchArray['away_team']);
        return new Match($homeTeam, $awayTeam);
    }

    /**
     * @return mixed
     */
    function toArray()
    {
        $result = [];
        $result['home_team_id'] = $this->homeTeam->id;
        $result['away_team_id'] = $this->awayTeam->id;
        return $result;
    }
}


text:
import { TestBed, inject } from '@angular/core/testing';

import { SocketService } from './socket.service';

describe('SocketService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [SocketService]
    });
  });

  it('should be created', inject([SocketService], (service: SocketService) => {
    expect(service).toBeTruthy();
  }));
});


text:
layout: post
title: "LINQ with Index"
published: true
---

Let's say you have a function that returns list of entities with logs. One entity may have 0 or more logs.

{% highlight csharp %}
private IEnumerable<Entity> GetDetails(IEnumerable<int> ids)
{
    IEnumerable<Entity> entities = _entityRepository.GetByIds(ids);
    foreach (var entity in entities)
    {
        IEnumerable<Log> logs = _logRepository.GetByEntityId(entity.Id);
        entity.Logs = logs;
    }
}
{% endhighlight %}

This code is likely slow, since you call LogRepository on each entity. In most situation (depends on your data profile), it is faster to get entire records with one call, and filter locally.

{% highlight csharp %}
private IEnumerable<Entity> GetDetailsFaster(IEnumerable<int> ids)
{
    IEnumerable<Entity> entities = _entityRepository.GetByIds(ids);
    IEnumerable<Log> allLogs = _logRepository.GetByEntityIds(ids);
    foreach (var entity in entities)
    {
        IEnumerable<Log> logs = allLogs.Where(x => x.EntityId == entity.Id).ToList();
        entity.Logs = logs;
    }
}
{% endhighlight %}

If you have many entity records, this is still slow, especially on `allLogs.Where(x => x.EntityId == entity.Id)` area. It is because you are going through entire logs for every entity.

We can make this faster by introducing new LINQ extension method IndexBy(). This is how you would use:

{% highlight csharp %}
private IEnumerable<Entity> GetDetailsFaster(IEnumerable<int> ids)
{
    IEnumerable<Entity> entities = _entityRepository.GetByIds(ids);
    IEnumerable<Log> allLogs = _logRepository.GetByEntityIds(ids);
    Dictionary<int, IEnumerable<Log>> indexedLogs = allLogs.IndexBy(x => x.EntityId);

    foreach (var entity in entities)
    {
        if (indexedLogs.ContainsKey(entity.Id))
        {
            IEnumerable<Log> logs = indexedLogs[entity.Id];
            entity.Logs = logs;
        }
    }
}
{% endhighlight %}

Source code for IndexBy():

{% highlight csharp %}
public static class EnumerableExtensions
{
    public static Dictionary<TKey, IEnumerable<TValue>> IndexBy<TKey, TValue>(
        this IEnumerable<TValue> list,
        Func<TValue, TKey> keyFilter)
    {
        var result = list.GroupBy(keyFilter).Where(x => x.Any());

        return result.ToDictionary(x => x.Key, x => x.Select(y => y));
    }
}
{% endhighlight %}

You can use IndexBy() for any combination of properties.


text:
package net.ljcomputing.ecsr.domain.person;

import org.neo4j.ogm.annotation.RelationshipEntity;

/**
 * Organizational team domain.
 *
 * @author James G. Willmore
 *
 */
@RelationshipEntity(type = "ORGANIZATIONAL_TEAM")
public class OrganizationalTeam extends AbstractMembership<Team, Organization>
    implements Membership<Team, Organization> {

  /** The Constant serialVersionUID. */
  private static final long serialVersionUID = 7732591005710335588L;
}


text:
package com.urucas.popcorntimerc.interfaces;

import org.json.JSONObject;

/**
 * Created by Urucas on 9/20/14.
 */
public interface SocketFoundCallback {

    public void onSuccess(String host);

}


text:
www.teamfortress.com

[![Join the chat at https://gitter.im/IndieKA/Team-Fortress-2](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/IndieKA/Team-Fortress-2?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

<img src = "https://images-na.ssl-images-amazon.com/images/G/01/videogames/detail-page/tf2_1_lg.jpg" width="700" height="400"/>

Team Fortress 2 is a team based FPS game created by Valve Corporation and downloadable on [Steam] (https://store.steampowered.com/apps/440). It is the continuation of Team Fortress, an original FPS from 1996. The game has gotten more than 300,000 ratings on Steam itself and was rated 4.5/5 from Metacritic. It still continues to be a great multiplayer game today.

I (IndieKA) am creating a replica of Team Fortress 2 on Khan Academy, the same site in which I will be creating my Garry's Mod KA Project w/Fenrier. Want to check it out? Go to this link: https://www.khanacademy.org/computer-programming/team-fortress-2/6360667559428096. This is an open source project, so feedback and helpful discussion is always welcome. If you would love to contribute, head over to the Contributing section.

**Creators**:
-
Fenrier:
* https://github.com/IndieKA (shares brother's account)

IndieKA
* https://github.com/IndieKA (shares w/brother)

You might be up here too, if you contribute a lot! =)

## Table of Contents
* [About] (#about)
* [Contributing] (#contributing)
* [Credits] (#credits)

## About
Team Fortress 2 is a team-based, first person shooter developed by VALVe (Valve Corporation) and is found on Steam to download. It is the sequel to the 1996 mod Team Fortress and its 1999 remake. It was originally released for the video game compilation _The Orange Box_ on October 10th, 2007, and it was only till April 8th, 2008 that the game would become a standalone title for Windows. Eventually, it was downloadable on Linux and OS X, making the game available for more players.

In _Team Fortress 2_, players are selected to join one of two teams (red vs. blue) choosing nine different character classes, each having a special ability and trait. The game has multiple game modes and maps, such as Capture the Flag and King of the Hill. Team Fortress 2 is also featured in the 3D classic sandbox _Garry's Mod_ and is powered by VALVe's _Source_ engine. The game received much attraction from YouTubers such as Tobuscus (Toby Turner) and PewDiePie (Felix Arvid Ulf Kjellberg) for its art, humor, and efficient gameplay. VALVe continues to update Team Fortress 2, releasing new content and new maps either according to the time of year or just a usual update.

**Game modes:**
The objective of the mode depends on what it is, so let's find out.
* In CTF (Capture The Flag) maps, the main objective for both teams is to obtain a briefcase, containing "secrets" about the other team's plans, and returning it to their base to receive a point for their team, eventually leading up to see which team has the most points of them all. A match lasts till one team gets a higher score or time runs out.
* Control Point mode is where a team stays near a "control point" for a short amount of time to get a point. However, if you leave a point out in the open, the other team has a chance to claim it. The team with the most points at the end of the round wins.
* King of the Hill mode is where there is a single control point out in the open, at the center of the designated map. Teams will fight over it, and if one team reaches the point first, a countdown is made until the round. If the opposing team intercepts it, their countdown starts, breaking the other team's launch procedure. The winning team is judged by which team can stay the longest till their countdown is over.
* Arena is a team deathmatch mode, where you have to either support or fight till the end for your team; there is no respawning at all. Dying inside the game will immediately make you a spectator, watching over how your other teammates do. A team wins the round by either capturing the control point or eliminating all of the other team members.
* Mann vs Machine is a six player co-op mode where the mercs have to defend a structure from waves of robots. Players have the ability to buy upgrades and improvements between rounds using in-game money earned during previous waves.

**Characters:**
Team Fortress 2 features nine different characters categorized into offense, defense, and support roles. Each class has strengths and weaknesses; and must work with other players of different classes to have their team win.
(information from _Wikipedia_ [Team Fortress 2])

**Offense:**
* **The Scout:** is a baseball fan and street runner. He is a fast, agile character, armed with a scattergun, a pistol and an aluminum baseball bat. The Scout can double-jump and captures control points and pushes payloads twice as fast as other classes, but has the lowest health.
* **The Soldier:**  is more durable, but slower. The Soldier is armed with a rocket launcher, shotgun, and a folding shovel. The Soldier can use his rocket launcher to rocket jump to higher positions at the cost of some health.
* **The Pyro:** is a mentally unstable maniac of unknown gender who is armed with a with a flamethrower, fire axe, and a shotgun.

**Defense:**
* **The Demoman:** is a one eyed, heavy-drinking person armed with a glass bottle and some grenades with sticky bombs.
* **The Heavyman:** (voiced by the same person as _The Demoman_) is a large Russian who, although is the slowest class, can deal immense amounts of damage to players using a enormous minigun labeled "Sasha".
* **The Engineer:** is a character which can build sentry turrets and other objects to help his team, and is armed with a shotgun and a wrench tool that fixes things on hit.

**Support:**
* **The Medic:** is a doctor armed with a "Medi Gun" which heals teammates and gradually builds a power that gives effect to the Medic. He keeps doves as pets, sometimes bloody.
* **The Sniper:** is of course, a sniper armed with a kukri (for close combat) and a long range sniper for helping take out enemies. Players usually find other snipers on towers and high positions.
* **The Spy:** is an agent with tools like a "butterfly" knife and a device used to sabotage Engineer's buildings. His "butterfly" knife can take out any character (only if it is a backstab)

## How does KAPJS work?
You may know what ProcessingJS and how it works (processingjs.org), but Khan Academy's version of PJS is rather different. Observe:
**Normal PJS Code:**
```
void setup(){
  size(200, 200);
  frameRate(10);
}

void draw(){
  background(#ffffff);
  ellipse(100, 100, random(50), random(50);
}
```

**Khan Academy's PJS Code:**
```
draw = function(){
  size(200, 200);
  frameRate(10);
  background(255, 255, 255);
  ellipse(100, 100, random(50), random(50);
};
```

Notice how there is minor changes like `void draw()` would be `draw = function()` and the `background` system in Khan Academy uses the RGB filter. Their system was mainly designed like this for beginner programmers under the age of 13, (even though Fenrier and I are over 13) we will still be developing Team Fortress 2 on Khan Academy.

## Contributing
Yes, there is a guideline for contributing to this repository. Please read it over before you solve any issues/errors with the global program. Don't forget to either check out the LICENSE to see where it is licensed from, or see Fenrier's profile for proof work on the contributions. (http://www.khanacademy.org/profile/Fenrier)

THIS COPYRIGHT LICENSE was written all by me and Fenrier. PLEASE DO NOT take this into your repositories, even with credit. It is something that took us a while to type up, and this part of the README.md is not open-source.

### Helpful contributions
---
**IMPORTANT**: Before contributing to this repository, read the following BEFORE the margin.
"You" or "Your" (group) shall accept the following terms and conditions for your contributions to this project. You(r) name will be Featured on the Credits list, with a link attached to your GitHub profile, and/or Khan Academy/Travis/any other collaborating site. By accepting this passage you agree to having the GitHub user @IndieKA sponsoring you and your contributions.

Contribution in this group shall mean work that is original. Please provide the source name (if) needed, including minor modifications and add-ons, and credit your origins wisely. You are contributing on behalf the following project WILL and most possibly USE your provided code. (WE) the users (WILL) use your code on note that we may add improvement/changes to the syntax. IF you are not satisfied WITH what we have done w/your code, you have all means to revoke your code request and leave the collaboration. YOUR code MUST be of Khan Academy's JavaScript or normal JavaScript, otherwise WE have all rights to reject your pull request. You do Agree, on all circumstances, to notify the Team Fortress 2 project WHEN you have made a modification to your code.

Subject to this agreement, you AGREE to not abuse or in any way, DISCRIMINATE against another user who has followed the Agreement listed. Rude or argumentative behavior WILL NOT be tolerated, and creators/contributors WILL be banned from further contributions. IF we find YOUR code is not original, there is a possibility you can be KICKED from the repository. The license(s) provided by MIT and GitHub to user @IndieKA are of his and theirs copyright, giving each right to grant and authorize any system to any user who agrees this copyright. You represent, your(self), that your creation is YOUR OWN. You provide Your Contributions to This Group on Agreement it MAY be used by a third party group IN THE CONCLUSION they WILL give proper credit to not only you BUT the Following Group.

REMEMBER that YOUR CODE can be sold, imported, and transfered to another company/organization ON BEHALF they will give credit to US AS WELL (and you). You CANNOT do anything AFTER a PIECE has been sold rather than US give the link to the other franchise/company/organization.

IF you FAIL to meet the needs of (this) repository you MAY be kicked, or banned, from the following REPOSITORY, and may never be able to contribute again. YOU ARE BEING WATCHED.

Thank you for taking the time to read this Agreement. Copyright @ IndieKA 2015 (this is not for use in any of your Repos)

### Syntax & Code

If you would like to contribute, instead of pointing out simple mistakes you can either try to do the following:
* **Try to fix bugs**: Just above this mini section is a small, yet reasonable list of bugs in the program. See if you can try to fix them! Report to @Fenrier or @Indie on Khan Academy if you have done so, and include the code w/it in case it is fixing a long part of the script.
* **Report any disruptive behavior or any problems with the interface**: Although these might not be _so_ important, they can lead to later problems regarding users/code.

### Code Style
* -  No line indentations.
* -  Clean code (w/spaces between commas and indented code when needed) [IF you cannot clean your code well use http://jsbeautifier.org)
* -  camelCase with variables.
* -  80 character line length. Then you must indent.
* -  New changes cannot extend the original more than 700 lines of code (unless it is something VERY important)
In general, try to make your syntax blend in w/the actual code.

### Pull Requests
* Link to the original w/the new added code/syntax.
* Before merging state changes
* Large pull requests should be separated into new folders

### Screenshotting
Before we add a user's change, we require a screenshot of what they have done. IF YOU ARE UNABLE to provide us w/that, your changes MAY NOT be accepted! Please, if you suggest a big change in the code, include a screenshot showing what you are going to change. Most screenshots will be taken on Khan Academy.

How our screenshot system works:
- Only focus on editor/picture
- Do not display any other tabs (or put your screen onto Fullscreen mode)
- If there are no visible changes, WE MAY possibly accept it, considering it might just be a minor bug fix or so.

### CODE ADDING
The most important out of all of them. In fact, this really should go first...

Most of our basic things are handled in the "`basics`" folder, where all the details and components of the game last. If you try to merge your new code INTO another folder besides `basics`, YOU MUST have it to do w/something else rather than the actual `basics`.

Please inform us in our Gitter chat where you are going to add your code. (https://gitter.im/IndieKA/Team-Fortress-2)

## Credits
* License: MIT (see LICENSE file)
* Original Author (Fenrier)
* Repository: https://github.com/IndieKA/Team-Fortress-2 (created by IndieKA for Fenrier)
* Original program: https://www.khanacademy.org/cs/-/6360667559428096

### Copyright and license

Code and documentation created by IndieKA and Fenrier. Code released under the [MIT License] (https://github.com/twbs/bootstrap/blob/master/LICENSE). All rights reserved.


text:
(function(window){
	var doc = window.document,
			nav = window.navigator,
			URL = window.URL || window.webkitURL;

	var dropZone = doc.querySelector('#dropZone'),
			uploadBtn = doc.querySelector('#upload'),
			preview = doc.querySelector('#preview');

	dropZone.ondragenter = dropZone.ondragover = function(e){
		e.stopPropagation();
		e.preventDefault();
	};

	dropZone.ondrop = function(e){
		e.stopPropagation();
		e.preventDefault();

		var files = e.dataTransfer.files;
		generatePreview(files);
	};

	uploadBtn.addEventListener('click', function(e){
		var imgs = doc.querySelectorAll('.images');

		for(var i = 0; i < imgs.length; i++){
			var img = imgs[i];
			//var file = img.getAttribute('data-file');
			sendFile(img.file);
			//new FileUpload(img, file); // send as binary data using filereader api
		};
	}, false);

	function generatePreview(files){
		if(!files.length){
			preview.innerHTML = "
No files selected
";
		} else {
			var list = doc.createElement('ul');
			for(var i = 0; i < files.length; i++){
				var li = doc.createElement('li');
				list.appendChild(li);

				var img = new Image();
				img.classList.add('images');
				//img.setAttribute('data-file', files[i]);
				img.file = files[i];
				li.appendChild(img);

				/** Object URL method **
				img.src = URL.createObjectURL(files[i]);
				img.onload = function(e){
					URL.revokeObjectURL(this.src);
				};
				// End of Object url method
				*/

				/** FileReader Method **/
				var reader = new FileReader();
				reader.onload = (function(img){
					return function(e){
						img.src = e.target.result;
					};
				}(img));
				reader.readAsDataURL(files[i]);
				/** End of file reader method */

				var info = doc.createElement('div');
				info.classList.add('info');
				info.innerHTML = '' + files[i].name + ": " + files[i].type + ", " + files[i].size + '';
				li.appendChild(info);
			}

			preview.replaceChild(list, preview.querySelector('p'));
		}
	}

	/** Send as formdata **/
	function sendFile(file){
		var url = 'upload.php',
				xhr = new XMLHttpRequest(),
				formData = new FormData();

		xhr.open("POST", url, true);
		xhr.onreadystatechange = function(e){
			if(xhr.readyState == 4 && xhr.status == 200){
				console.log(xhr.response);
				//preview.appendChild();
			}
		};

		formData.append("myFile", file);
		xhr.send(formData);
	}

	/** Send file as binary ***/
	function FileUpload(img, file){
		var reader = new FileReader();
		this.ctrl = createThrobber(img);
		xhr = new XMLHttpRequest();
		this.xhr = xhr;

		var self = this;
		this,xhr.upload.addEventListener('progress', function(e){
			if(e.lengthComputable){
				var percent = Math.round((e.loaded * 100) / e.total);
				self.ctrl.update(percent);
			}
		}, false);

		xhr.upload.addEventListener('load', function(e){
			self.ctrl.update(100);
			var canvas = self.ctrl.ctx.canvas;
			canvas.parentNode.removeChild(canvas);
		}, false);

		xhr.open("POST", "/upload.php");
		xhr.overrideMimeType('text/plain; charset=x-user-defined-binary');
		reader.onload = function(e){
			xhr.sendAsBinary(e.target.result);
		};
		reader.readAsBinaryString(file);
	}

}(this));


text:
/**
 * \file wasmtime/store.h
 *
 * Wasmtime definition of a "store".
 */

#ifndef WASMTIME_STORE_H
#define WASMTIME_STORE_H

#include <wasm.h>
#include <wasi.h>
#include <wasmtime/error.h>

#ifdef __cplusplus
extern "C" {
#endif

/**
 * \typedef wasmtime_store_t
 * \brief Convenience alias for #wasmtime_store_t
 *
 * \struct wasmtime_store
 * \brief Storage of WebAssembly objects
 *
 * A store is the unit of isolation between WebAssembly instances in an
 * embedding of Wasmtime. Values in one #wasmtime_store_t cannot flow into
 * another #wasmtime_store_t. Stores are cheap to create and cheap to dispose.
 * It's expected that one-off stores are common in embeddings.
 *
 * Objects stored within a #wasmtime_store_t are referenced with integer handles
 * rather than interior pointers. This means that most APIs require that the
 * store be explicitly passed in, which is done via #wasmtime_context_t. It is
 * safe to move a #wasmtime_store_t to any thread at any time. A store generally
 * cannot be concurrently used, however.
 */
typedef struct wasmtime_store wasmtime_store_t;

/**
 * \typedef wasmtime_context_t
 * \brief Convenience alias for #wasmtime_context
 *
 * \struct wasmtime_context
 * \brief An interior pointer into a #wasmtime_store_t which is used as
 * "context" for many functions.
 *
 * This context pointer is used pervasively throught Wasmtime's API. This can be
 * acquired from #wasmtime_store_context or #wasmtime_caller_context. The
 * context pointer for a store is the same for the entire lifetime of a store,
 * so it can safely be stored adjacent to a #wasmtime_store_t itself.
 *
 * Usage of a #wasmtime_context_t must not outlive the original
 * #wasmtime_store_t. Additionally #wasmtime_context_t can only be used in
 * situations where it has explicitly been granted access to doing so. For
 * example finalizers cannot use #wasmtime_context_t because they are not given
 * access to it.
 */
typedef struct wasmtime_context wasmtime_context_t;

/**
 * \brief Creates a new store within the specified engine.
 *
 * \param engine the compilation environment with configuration this store is
 * connected to
 * \param data user-provided data to store, can later be acquired with
 * #wasmtime_context_get_data.
 * \param finalizer an optional finalizer for `data`
 *
 * This function creates a fresh store with the provided configuration settings.
 * The returned store must be deleted with #wasmtime_store_delete.
 */
WASM_API_EXTERN wasmtime_store_t *wasmtime_store_new(
    wasm_engine_t *engine,
    void *data,
    void (*finalizer)(void*)
);

/**
 * \brief Returns the interior #wasmtime_context_t pointer to this store
 */
WASM_API_EXTERN wasmtime_context_t *wasmtime_store_context(wasmtime_store_t *store);

/**
 * \brief Deletes a store.
 */
WASM_API_EXTERN void wasmtime_store_delete(wasmtime_store_t *store);

/**
 * \brief Returns the user-specified data associated with the specified store
 */
WASM_API_EXTERN void *wasmtime_context_get_data(const wasmtime_context_t* context);

/**
 * \brief Overwrites the user-specified data associated with this store.
 *
 * Note that this does not execute the original finalizer for the provided data,
 * and the original finalizer will be executed for the provided data when the
 * store is deleted.
 */
WASM_API_EXTERN void wasmtime_context_set_data(wasmtime_context_t* context, void *data);

/**
 * \brief Perform garbage collection within the given context.
 *
 * Garbage collects `externref`s that are used within this store. Any
 * `externref`s that are discovered to be unreachable by other code or objects
 * will have their finalizers run.
 *
 * The `context` argument must not be NULL.
 */
WASM_API_EXTERN void wasmtime_context_gc(wasmtime_context_t* context);

/**
 * \brief Adds fuel to this context's store for wasm to consume while executing.
 *
 * For this method to work fuel consumption must be enabled via
 * #wasmtime_config_consume_fuel_set. By default a store starts with 0 fuel
 * for wasm to execute with (meaning it will immediately trap).
 * This function must be called for the store to have
 * some fuel to allow WebAssembly to execute.
 *
 * Note that at this time when fuel is entirely consumed it will cause
 * wasm to trap. More usages of fuel are planned for the future.
 *
 * If fuel is not enabled within this store then an error is returned. If fuel
 * is successfully added then NULL is returned.
 */
WASM_API_EXTERN wasmtime_error_t *wasmtime_context_add_fuel(wasmtime_context_t *store, uint64_t fuel);

/**
 * \brief Returns the amount of fuel consumed by this context's store execution
 * so far.
 *
 * If fuel consumption is not enabled via #wasmtime_config_consume_fuel_set
 * then this function will return false. Otherwise true is returned and the
 * fuel parameter is filled in with fuel consuemd so far.
 *
 * Also note that fuel, if enabled, must be originally configured via
 * #wasmtime_context_add_fuel.
 */
WASM_API_EXTERN bool wasmtime_context_fuel_consumed(const wasmtime_context_t *context, uint64_t *fuel);

/**
 * \brief Attempt to manually consume fuel from the store.
 *
 * If fuel consumption is not enabled via #wasmtime_config_consume_fuel_set then
 * this function will return an error. Otherwise this will attempt to consume
 * the specified amount of `fuel` from the store. If successful the remaining
 * amount of fuel is stored into `remaining`. If `fuel` couldn't be consumed
 * then an error is returned.
 *
 * Also note that fuel, if enabled, must be originally configured via
 * #wasmtime_context_add_fuel.
 */
WASM_API_EXTERN wasmtime_error_t *wasmtime_context_consume_fuel(wasmtime_context_t *context, uint64_t fuel, uint64_t *remaining);

/**
 * \brief Configures WASI state within the specified store.
 *
 * This function is required if #wasmtime_linker_define_wasi is called. This
 * will configure the WASI state for instances defined within this store to the
 * configuration specified.
 *
 * This function does not take ownership of `context` but it does take ownership
 * of `wasi`. The caller should no longer use `wasi` after calling this function
 * (even if an error is returned).
 */
WASM_API_EXTERN wasmtime_error_t *wasmtime_context_set_wasi(wasmtime_context_t *context, wasi_config_t *wasi);

/**
 * \brief Configures the relative deadline at which point WebAssembly code will
 * trap.
 *
 * This function configures the store-local epoch deadline after which point
 * WebAssembly code will trap.
 *
 * See also #wasmtime_config_epoch_interruption_set.
 */
WASM_API_EXTERN void wasmtime_context_set_epoch_deadline(wasmtime_context_t *context, uint64_t ticks_beyond_current);

#ifdef __cplusplus
}  // extern "C"
#endif

#endif // WASMTIME_STORE_H