text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.jrtc27</groupId>
  <artifactId>CraftMail</artifactId>
  <version>0.1-SNAPSHOT</version>
  <name>CraftMail</name>
  <prerequisites>
    <maven>3.0</maven>
  </prerequisites>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  </properties>
  <repositories>
    <repository>
      <id>bukkit-repo</id>
      <url>http://repo.bukkit.org/content/groups/public</url>
    </repository>
    <repository>
      <id>java.net</id>
      <url>https://maven.java.net/content/repositories/releases</url>
    </repository>
  </repositories>

  <scm>
    <connection>scm:git:git://github.com/jrtc27/CraftMail.git</connection>
    <url>https://github.com/jrtc27/CraftMail</url>
    <developerConnection>scm:git:git@github.com:jrtc27/CraftMail.git</developerConnection>
    <tag>HEAD</tag>
  </scm>

  <ciManagement>
    <system>jenkins</system>
    <url>https://ci.jrtc27.com/</url>
  </ciManagement>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.5.1</version>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>2.0</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <artifactSet>
                <excludes>
                  <exclude>org.bukkit:*</exclude>
                </excludes>
              </artifactSet>
              <createDependencyReducedPom>false</createDependencyReducedPom>
              <!-- Don't minimize jar - breaks JavaMail's reflection -->
              <!-- <minimizeJar>true</minimizeJar> -->
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-enforcer-plugin</artifactId>
        <version>1.1.1</version>
        <executions>
          <execution>
            <id>enforce-no-snapshots</id>
            <goals>
              <goal>enforce</goal>
            </goals>
            <configuration>
              <rules>
                <requireReleaseDeps>
                  <message>Dependencies must not be snapshots!</message>
                  <onlyWhenRelease>true</onlyWhenRelease>
                </requireReleaseDeps>
              </rules>
              <fail>true</fail>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-release-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
          <preparationGoals>clean verify</preparationGoals>
          <goals>clean verify</goals>
          <tagNameFormat>@{project.version}</tagNameFormat>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>2.9</version>
        <configuration>
          <skip>true</skip>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-source-plugin</artifactId>
        <version>2.2.1</version>
        <configuration>
          <attach>true</attach>
          <forceCreation>true</forceCreation>
        </configuration>
        <executions>
          <execution>
            <id>attach-sources</id>
            <phase>package</phase>
            <goals>
              <goal>jar-no-fork</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
      <groupId>org.bukkit</groupId>
      <artifactId>bukkit</artifactId>
      <version>1.4.2-R0.2</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.sun.mail</groupId>
      <artifactId>javax.mail</artifactId>
      <version>1.4.5</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>
  </dependencies>
</project>


text:
package com.alejandrorm.util.data_structures.stack;

import java.util.EmptyStackException;

/**
 * The Stack class represents a last-in-first-out (LIFO) stack of objects.
 * Implementation using an array.
 *
 * @author Alejandro Ramírez Muñoz [alejandror45@gmail.com]
 *
 * @param <E>  the type of elements in this list
 */
@SuppressWarnings("unchecked")
public class SimpleStack<E> implements Stack<E>{
	private static int DEFAULT_CAPACITY = 64;
	private E[] elements;
	private int top;
	private int capacity;

	public SimpleStack() {
		elements = (E[]) new Object[DEFAULT_CAPACITY];
		capacity = DEFAULT_CAPACITY;
		top = -1;
	}
	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean empty(){
		return top<0;
	}

	private void grows(){
		capacity = capacity*2;
		E[] copy = (E[]) new Object[capacity];
		System.arraycopy(elements, 0, copy, 0, elements.length);
		elements = copy;
	}

	private boolean isFull(){
		return top>=capacity-1;
	}
	/**
	 * {@inheritDoc}
	 */
	@Override
	public E peek() throws EmptyStackException{
		if(empty()){
			throw new EmptyStackException();
		}
		return elements[top];
	}
	/**
	 * {@inheritDoc}
	 */
	@Override
	public E pop() throws EmptyStackException{
		if(empty()){
			throw new EmptyStackException();
		}
		return elements[top--];
	}
	/**
	 * {@inheritDoc}
	 */
	@Override
	public void push(E item){
		if(isFull()){
			grows();
		}
		elements[++top]=item;
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("[");
		if(!empty()){
			for(int i=0; i<=top; i++){
				sb.append(elements[i] + ", ");
			}
			sb.setLength(sb.length()-2);
		}
		sb.append("]");

		return sb.toString();
	}

}

redpajama_set_name: RedPajamaGithub


text:
<!--L
  Copyright Moxie Informatics.

  Distributed under the OSI-approved BSD 3-Clause License.
  See http://ncip.github.com/calims/LICENSE.txt for details.
L-->

<classloading xmlns="urn:jboss:classloading:1.0"
              name="calims2-webapp.war"
              domain="calims2-webapp.war_domain">

              parent-domain="Ignored"

              export-all="NON_EMPTY"
              import-all="true">
</classloading>


text:
package org.apache.nifi.processors.aws.s3;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.amazonaws.services.s3.model.StorageClass;
import com.amazonaws.services.s3.model.Tag;
import org.apache.commons.lang3.StringUtils;
import org.apache.nifi.components.AllowableValue;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.flowfile.attributes.CoreAttributes;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.ListMultipartUploadsRequest;
import com.amazonaws.services.s3.model.MultipartUploadListing;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.PutObjectResult;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;

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

public class TestPutS3Object {

    private TestRunner runner;
    private PutS3Object putS3Object;
    private AmazonS3Client mockS3Client;

    @Before
    public void setUp() {
        mockS3Client = Mockito.mock(AmazonS3Client.class);
        putS3Object = new PutS3Object() {
            @Override
            protected AmazonS3Client getClient() {
                return mockS3Client;
            }
        };
        runner = TestRunners.newTestRunner(putS3Object);

        // MockPropertyValue does not evaluate system properties, set it in a variable with the same name
        runner.setVariable("java.io.tmpdir", System.getProperty("java.io.tmpdir"));
    }

    @Test
    public void testPutSinglePart() {
        runner.setProperty("x-custom-prop", "hello");
        prepareTest();

        runner.run(1);

        ArgumentCaptor<PutObjectRequest> captureRequest = ArgumentCaptor.forClass(PutObjectRequest.class);
        Mockito.verify(mockS3Client, Mockito.times(1)).putObject(captureRequest.capture());
        PutObjectRequest request = captureRequest.getValue();
        assertEquals("test-bucket", request.getBucketName());

        runner.assertAllFlowFilesTransferred(PutS3Object.REL_SUCCESS, 1);

        List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(PutS3Object.REL_SUCCESS);
        MockFlowFile ff0 = flowFiles.get(0);

        ff0.assertAttributeEquals(CoreAttributes.FILENAME.key(), "testfile.txt");
        ff0.assertAttributeEquals(PutS3Object.S3_ETAG_ATTR_KEY, "test-etag");
        ff0.assertAttributeEquals(PutS3Object.S3_VERSION_ATTR_KEY, "test-version");
    }

    @Test
    public void testPutSinglePartException() {
        prepareTest();

        Mockito.when(mockS3Client.putObject(Mockito.any(PutObjectRequest.class))).thenThrow(new AmazonS3Exception("TestFail"));

        runner.run(1);

        runner.assertAllFlowFilesTransferred(PutS3Object.REL_FAILURE, 1);
    }

    @Test
    public void testSignerOverrideOptions() {
        final AWSCredentialsProvider credentialsProvider = new DefaultAWSCredentialsProviderChain();
        final ClientConfiguration config = new ClientConfiguration();
        final PutS3Object processor = new PutS3Object();
        final TestRunner runner = TestRunners.newTestRunner(processor);

        final List<AllowableValue> allowableSignerValues = PutS3Object.SIGNER_OVERRIDE.getAllowableValues();
        final String defaultSignerValue = PutS3Object.SIGNER_OVERRIDE.getDefaultValue();

        for (AllowableValue allowableSignerValue : allowableSignerValues) {
            String signerType = allowableSignerValue.getValue();
            if (!signerType.equals(defaultSignerValue)) {
                runner.setProperty(PutS3Object.SIGNER_OVERRIDE, signerType);
                ProcessContext context = runner.getProcessContext();
                try {
                    processor.createClient(context, credentialsProvider, config);
                } catch (IllegalArgumentException argEx) {
                    Assert.fail(argEx.getMessage());
                }
            }
        }
    }

    @Test
    public void testObjectTags() {
        runner.setProperty(PutS3Object.OBJECT_TAGS_PREFIX, "tagS3");
        runner.setProperty(PutS3Object.REMOVE_TAG_PREFIX, "false");
        prepareTest();

        runner.run(1);

        ArgumentCaptor<PutObjectRequest> captureRequest = ArgumentCaptor.forClass(PutObjectRequest.class);
        Mockito.verify(mockS3Client, Mockito.times(1)).putObject(captureRequest.capture());
        PutObjectRequest request = captureRequest.getValue();

        List<Tag> tagSet = request.getTagging().getTagSet();

        assertEquals(1, tagSet.size());
        assertEquals("tagS3PII", tagSet.get(0).getKey());
        assertEquals("true", tagSet.get(0).getValue());
    }

    @Test
    public void testStorageClasses() {
        for (StorageClass storageClass : StorageClass.values()) {
            runner.setProperty(PutS3Object.STORAGE_CLASS, storageClass.name());
            prepareTest();

            runner.run(1);

            ArgumentCaptor<PutObjectRequest> captureRequest = ArgumentCaptor.forClass(PutObjectRequest.class);
            Mockito.verify(mockS3Client, Mockito.times(1)).putObject(captureRequest.capture());
            PutObjectRequest request = captureRequest.getValue();

            assertEquals(storageClass.toString(), request.getStorageClass());

            Mockito.reset(mockS3Client);
        }
    }

    @Test
    public void testFilenameWithNationalCharacters() throws UnsupportedEncodingException {
        prepareTest("Iñtërnâtiônàližætiøn.txt");

        runner.run(1);

        ArgumentCaptor<PutObjectRequest> captureRequest = ArgumentCaptor.forClass(PutObjectRequest.class);
        Mockito.verify(mockS3Client, Mockito.times(1)).putObject(captureRequest.capture());
        PutObjectRequest request = captureRequest.getValue();

        ObjectMetadata objectMetadata = request.getMetadata();
        assertEquals(URLEncoder.encode("Iñtërnâtiônàližætiøn.txt", "UTF-8"), objectMetadata.getContentDisposition());
    }

    private void prepareTest() {
        prepareTest("testfile.txt");
    }

    private void prepareTest(String filename) {
        runner.setProperty(PutS3Object.REGION, "ap-northeast-1");
        runner.setProperty(PutS3Object.BUCKET, "test-bucket");
        runner.assertValid();

        Map<String, String> ffAttributes = new HashMap<>();
        ffAttributes.put("filename", filename);
        ffAttributes.put("tagS3PII", "true");
        runner.enqueue("Test Content", ffAttributes);

        PutObjectResult putObjectResult = new PutObjectResult();
        putObjectResult.setExpirationTime(new Date());
        putObjectResult.setMetadata(new ObjectMetadata());
        putObjectResult.setVersionId("test-version");
        putObjectResult.setETag("test-etag");

        Mockito.when(mockS3Client.putObject(Mockito.any(PutObjectRequest.class))).thenReturn(putObjectResult);

        MultipartUploadListing uploadListing = new MultipartUploadListing();
        Mockito.when(mockS3Client.listMultipartUploads(Mockito.any(ListMultipartUploadsRequest.class))).thenReturn(uploadListing);
    }

    @Test
    public void testPersistenceFileLocationWithDefaultTempDir() {
        String dir = System.getProperty("java.io.tmpdir");

        executePersistenceFileLocationTest(StringUtils.appendIfMissing(dir, File.separator) + putS3Object.getIdentifier());
    }

    @Test
    public void testPersistenceFileLocationWithUserDefinedDirWithEndingSeparator() {
        String dir = StringUtils.appendIfMissing(new File("target").getAbsolutePath(), File.separator);
        runner.setProperty(PutS3Object.MULTIPART_TEMP_DIR, dir);

        executePersistenceFileLocationTest(dir + putS3Object.getIdentifier());
    }

    @Test
    public void testPersistenceFileLocationWithUserDefinedDirWithoutEndingSeparator() {
        String dir = StringUtils.removeEnd(new File("target").getAbsolutePath(), File.separator);
        runner.setProperty(PutS3Object.MULTIPART_TEMP_DIR, dir);

        executePersistenceFileLocationTest(dir + File.separator + putS3Object.getIdentifier());
    }

    private void executePersistenceFileLocationTest(String expectedPath) {
        prepareTest();

        runner.run(1);
        File file = putS3Object.getPersistenceFile();

        assertEquals(expectedPath, file.getAbsolutePath());
    }

    @Test
    public void testGetPropertyDescriptors() {
        PutS3Object processor = new PutS3Object();
        List<PropertyDescriptor> pd = processor.getSupportedPropertyDescriptors();
        assertEquals("size should be eq", 39, pd.size());
        assertTrue(pd.contains(PutS3Object.ACCESS_KEY));
        assertTrue(pd.contains(PutS3Object.AWS_CREDENTIALS_PROVIDER_SERVICE));
        assertTrue(pd.contains(PutS3Object.BUCKET));
        assertTrue(pd.contains(PutS3Object.CANNED_ACL));
        assertTrue(pd.contains(PutS3Object.CREDENTIALS_FILE));
        assertTrue(pd.contains(PutS3Object.ENDPOINT_OVERRIDE));
        assertTrue(pd.contains(PutS3Object.FULL_CONTROL_USER_LIST));
        assertTrue(pd.contains(PutS3Object.KEY));
        assertTrue(pd.contains(PutS3Object.OWNER));
        assertTrue(pd.contains(PutS3Object.READ_ACL_LIST));
        assertTrue(pd.contains(PutS3Object.READ_USER_LIST));
        assertTrue(pd.contains(PutS3Object.REGION));
        assertTrue(pd.contains(PutS3Object.SECRET_KEY));
        assertTrue(pd.contains(PutS3Object.SIGNER_OVERRIDE));
        assertTrue(pd.contains(PutS3Object.SSL_CONTEXT_SERVICE));
        assertTrue(pd.contains(PutS3Object.TIMEOUT));
        assertTrue(pd.contains(PutS3Object.EXPIRATION_RULE_ID));
        assertTrue(pd.contains(PutS3Object.STORAGE_CLASS));
        assertTrue(pd.contains(PutS3Object.WRITE_ACL_LIST));
        assertTrue(pd.contains(PutS3Object.WRITE_USER_LIST));
        assertTrue(pd.contains(PutS3Object.SERVER_SIDE_ENCRYPTION));
        assertTrue(pd.contains(PutS3Object.ENCRYPTION_SERVICE));
        assertTrue(pd.contains(PutS3Object.USE_CHUNKED_ENCODING));
        assertTrue(pd.contains(PutS3Object.USE_PATH_STYLE_ACCESS));
        assertTrue(pd.contains(PutS3Object.PROXY_CONFIGURATION_SERVICE));
        assertTrue(pd.contains(PutS3Object.PROXY_HOST));
        assertTrue(pd.contains(PutS3Object.PROXY_HOST_PORT));
        assertTrue(pd.contains(PutS3Object.PROXY_USERNAME));
        assertTrue(pd.contains(PutS3Object.PROXY_PASSWORD));
        assertTrue(pd.contains(PutS3Object.OBJECT_TAGS_PREFIX));
        assertTrue(pd.contains(PutS3Object.REMOVE_TAG_PREFIX));
        assertTrue(pd.contains(PutS3Object.CONTENT_TYPE));
        assertTrue(pd.contains(PutS3Object.CONTENT_DISPOSITION));
        assertTrue(pd.contains(PutS3Object.CACHE_CONTROL));
        assertTrue(pd.contains(PutS3Object.MULTIPART_THRESHOLD));
        assertTrue(pd.contains(PutS3Object.MULTIPART_PART_SIZE));
        assertTrue(pd.contains(PutS3Object.MULTIPART_S3_AGEOFF_INTERVAL));
        assertTrue(pd.contains(PutS3Object.MULTIPART_S3_MAX_AGE));
        assertTrue(pd.contains(PutS3Object.MULTIPART_TEMP_DIR));
    }
}


text:
"""
Twin Delayed DDPG (TD3)
------------------------
DDPG suffers from problems like overestimate of Q-values and sensitivity to hyper-parameters.
Twin Delayed DDPG (TD3) is a variant of DDPG with several tricks:
* Trick One: Clipped Double-Q Learning. TD3 learns two Q-functions instead of one (hence "twin"),
and uses the smaller of the two Q-values to form the targets in the Bellman error loss functions.

* Trick Two: "Delayed" Policy Updates. TD3 updates the policy (and target networks) less frequently
than the Q-function.

* Trick Three: Target Policy Smoothing. TD3 adds noise to the target action, to make it harder for
the policy to exploit Q-function errors by smoothing out Q along changes in action.

The implementation of TD3 includes 6 networks: 2 Q-net, 2 target Q-net, 1 policy net, 1 target policy net
Actor policy in TD3 is deterministic, with Gaussian exploration noise.

Reference
---------
original paper: https://arxiv.org/pdf/1802.09477.pdf

Environment
---
Openai Gym Pendulum-v0, continuous action space
https://gym.openai.com/envs/Pendulum-v0/

Prerequisites
---
tensorflow >=2.0.0a0
tensorflow-probability 0.6.0
tensorlayer >=2.0.0

&&
pip install box2d box2d-kengz --user

To run
-------
python tutorial_TD3.py --train/test

"""

import argparse
import os
import random
import time

import gym
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf

import tensorflow_probability as tfp
import tensorlayer as tl
from tensorlayer.layers import Dense
from tensorlayer.models import Model

Normal = tfp.distributions.Normal
tl.logging.set_verbosity(tl.logging.DEBUG)

# add arguments in command  --train/test
parser = argparse.ArgumentParser(description='Train or test neural net motor controller.')
parser.add_argument('--train', dest='train', action='store_true', default=False)
parser.add_argument('--test', dest='test', action='store_true', default=True)
args = parser.parse_args()

#####################  hyper parameters  ####################
# choose env
ENV_ID = 'Pendulum-v0'  # environment id
RANDOM_SEED = 2  # random seed
RENDER = False  # render while training

# RL training
ALG_NAME = 'TD3'
TRAIN_EPISODES = 100  # total number of episodes for training
TEST_EPISODES = 10  # total number of episodes for training
MAX_STEPS = 200  # maximum number of steps for one episode
BATCH_SIZE = 64  # update batch size
EXPLORE_STEPS = 500  # 500 for random action sampling in the beginning of training

HIDDEN_DIM = 64  # size of hidden layers for networks
UPDATE_ITR = 3  # repeated updates for single step
Q_LR = 3e-4  # q_net learning rate
POLICY_LR = 3e-4  # policy_net learning rate
POLICY_TARGET_UPDATE_INTERVAL = 3  # delayed steps for updating the policy network and target networks
EXPLORE_NOISE_SCALE = 1.0  # range of action noise for exploration
EVAL_NOISE_SCALE = 0.5  # range of action noise for evaluation of action value
REWARD_SCALE = 1.  # value range of reward
REPLAY_BUFFER_SIZE = 5e5  # size of replay buffer

###############################  TD3  ####################################

class ReplayBuffer:
    """
    a ring buffer for storing transitions and sampling for training
    :state: (state_dim,)
    :action: (action_dim,)
    :reward: (,), scalar
    :next_state: (state_dim,)
    :done: (,), scalar (0 and 1) or bool (True and False)
    """

    def __init__(self, capacity):
        self.capacity = capacity
        self.buffer = []
        self.position = 0

    def push(self, state, action, reward, next_state, done):
        if len(self.buffer) < self.capacity:
            self.buffer.append(None)
        self.buffer[self.position] = (state, action, reward, next_state, done)
        self.position = int((self.position + 1) % self.capacity)  # as a ring buffer

    def sample(self, batch_size):
        batch = random.sample(self.buffer, batch_size)
        state, action, reward, next_state, done = map(np.stack, zip(*batch))  # stack for each element
        """
        the * serves as unpack: sum(a,b) <=> batch=(a,b), sum(*batch) ;
        zip: a=[1,2], b=[2,3], zip(a,b) => [(1, 2), (2, 3)] ;
        the map serves as mapping the function on each list element: map(square, [2,3]) => [4,9] ;
        np.stack((1,2)) => array([1, 2])
        """
        return state, action, reward, next_state, done

    def __len__(self):
        return len(self.buffer)

class QNetwork(Model):
    """ the network for evaluate values of state-action pairs: Q(s,a) """

    def __init__(self, num_inputs, num_actions, hidden_dim, init_w=3e-3):
        super(QNetwork, self).__init__()
        input_dim = num_inputs + num_actions
        # w_init = tf.keras.initializers.glorot_normal(seed=None)
        w_init = tf.random_uniform_initializer(-init_w, init_w)

        self.linear1 = Dense(n_units=hidden_dim, act=tf.nn.relu, W_init=w_init, in_channels=input_dim, name='q1')
        self.linear2 = Dense(n_units=hidden_dim, act=tf.nn.relu, W_init=w_init, in_channels=hidden_dim, name='q2')
        self.linear3 = Dense(n_units=1, W_init=w_init, in_channels=hidden_dim, name='q3')

    def forward(self, input):
        x = self.linear1(input)
        x = self.linear2(x)
        x = self.linear3(x)
        return x

class PolicyNetwork(Model):
    """ the network for generating non-deterministic (Gaussian distributed) action from the state input """

    def __init__(self, num_inputs, num_actions, hidden_dim, action_range=1., init_w=3e-3):
        super(PolicyNetwork, self).__init__()
        w_init = tf.random_uniform_initializer(-init_w, init_w)

        self.linear1 = Dense(n_units=hidden_dim, act=tf.nn.relu, W_init=w_init, in_channels=num_inputs, name='policy1')
        self.linear2 = Dense(n_units=hidden_dim, act=tf.nn.relu, W_init=w_init, in_channels=hidden_dim, name='policy2')
        self.linear3 = Dense(n_units=hidden_dim, act=tf.nn.relu, W_init=w_init, in_channels=hidden_dim, name='policy3')
        self.output_linear = Dense(
            n_units=num_actions, W_init=w_init, b_init=tf.random_uniform_initializer(-init_w, init_w),
            in_channels=hidden_dim, name='policy_output'
        )
        self.action_range = action_range
        self.num_actions = num_actions

    def forward(self, state):
        x = self.linear1(state)
        x = self.linear2(x)
        x = self.linear3(x)
        output = tf.nn.tanh(self.output_linear(x))  # unit range output [-1, 1]
        return output

    def evaluate(self, state, eval_noise_scale):
        """
        generate action with state for calculating gradients;
        eval_noise_scale: as the trick of target policy smoothing, for generating noisy actions.
        """
        state = state.astype(np.float32)
        action = self.forward(state)

        action = self.action_range * action

        # add noise
        normal = Normal(0, 1)
        eval_noise_clip = 2 * eval_noise_scale
        noise = normal.sample(action.shape) * eval_noise_scale
        noise = tf.clip_by_value(noise, -eval_noise_clip, eval_noise_clip)
        action = action + noise
        return action

    def get_action(self, state, explore_noise_scale, greedy=False):
        """ generate action with state for interaction with envronment """
        action = self.forward([state])
        action = self.action_range * action.numpy()[0]
        if greedy:
            return action
        # add noise
        normal = Normal(0, 1)
        noise = normal.sample(action.shape) * explore_noise_scale
        action += noise
        return action.numpy()

    def sample_action(self):
        """ generate random actions for exploration """
        a = tf.random.uniform([self.num_actions], -1, 1)
        return self.action_range * a.numpy()

class TD3:

    def __init__(
            self, state_dim, action_dim, action_range, hidden_dim, replay_buffer, policy_target_update_interval=1,
            q_lr=3e-4, policy_lr=3e-4
    ):
        self.replay_buffer = replay_buffer

        # initialize all networks
        self.q_net1 = QNetwork(state_dim, action_dim, hidden_dim)
        self.q_net2 = QNetwork(state_dim, action_dim, hidden_dim)
        self.target_q_net1 = QNetwork(state_dim, action_dim, hidden_dim)
        self.target_q_net2 = QNetwork(state_dim, action_dim, hidden_dim)
        self.policy_net = PolicyNetwork(state_dim, action_dim, hidden_dim, action_range)
        self.target_policy_net = PolicyNetwork(state_dim, action_dim, hidden_dim, action_range)
        print('Q Network (1,2): ', self.q_net1)
        print('Policy Network: ', self.policy_net)

        # initialize weights of target networks
        self.target_q_net1 = self.target_ini(self.q_net1, self.target_q_net1)
        self.target_q_net2 = self.target_ini(self.q_net2, self.target_q_net2)
        self.target_policy_net = self.target_ini(self.policy_net, self.target_policy_net)

        # set train mode
        self.q_net1.train()
        self.q_net2.train()
        self.target_q_net1.eval()
        self.target_q_net2.eval()
        self.policy_net.train()
        self.target_policy_net.eval()

        self.update_cnt = 0
        self.policy_target_update_interval = policy_target_update_interval

        self.q_optimizer1 = tf.optimizers.Adam(q_lr)
        self.q_optimizer2 = tf.optimizers.Adam(q_lr)
        self.policy_optimizer = tf.optimizers.Adam(policy_lr)

    def target_ini(self, net, target_net):
        """ hard-copy update for initializing target networks """
        for target_param, param in zip(target_net.trainable_weights, net.trainable_weights):
            target_param.assign(param)
        return target_net

    def target_soft_update(self, net, target_net, soft_tau):
        """ soft update the target net with Polyak averaging """
        for target_param, param in zip(target_net.trainable_weights, net.trainable_weights):
            target_param.assign(  # copy weight value into target parameters
                target_param * (1.0 - soft_tau) + param * soft_tau
            )
        return target_net

    def update(self, batch_size, eval_noise_scale, reward_scale=10., gamma=0.9, soft_tau=1e-2):
        """ update all networks in TD3 """
        self.update_cnt += 1
        state, action, reward, next_state, done = self.replay_buffer.sample(batch_size)

        reward = reward[:, np.newaxis]  # expand dim
        done = done[:, np.newaxis]

        new_next_action = self.target_policy_net.evaluate(
            next_state, eval_noise_scale=eval_noise_scale
        )  # clipped normal noise
        reward = reward_scale * (reward - np.mean(reward, axis=0)) / (
            np.std(reward, axis=0) + 1e-6
        )  # normalize with batch mean and std; plus a small number to prevent numerical problem

        # Training Q Function
        target_q_input = tf.concat([next_state, new_next_action], 1)  # the dim 0 is number of samples
        target_q_min = tf.minimum(self.target_q_net1(target_q_input), self.target_q_net2(target_q_input))

        target_q_value = reward + (1 - done) * gamma * target_q_min  # if done==1, only reward
        q_input = tf.concat([state, action], 1)  # input of q_net

        with tf.GradientTape() as q1_tape:
            predicted_q_value1 = self.q_net1(q_input)
            q_value_loss1 = tf.reduce_mean(tf.square(predicted_q_value1 - target_q_value))
        q1_grad = q1_tape.gradient(q_value_loss1, self.q_net1.trainable_weights)
        self.q_optimizer1.apply_gradients(zip(q1_grad, self.q_net1.trainable_weights))

        with tf.GradientTape() as q2_tape:
            predicted_q_value2 = self.q_net2(q_input)
            q_value_loss2 = tf.reduce_mean(tf.square(predicted_q_value2 - target_q_value))
        q2_grad = q2_tape.gradient(q_value_loss2, self.q_net2.trainable_weights)
        self.q_optimizer2.apply_gradients(zip(q2_grad, self.q_net2.trainable_weights))

        # Training Policy Function
        if self.update_cnt % self.policy_target_update_interval == 0:
            with tf.GradientTape() as p_tape:
                new_action = self.policy_net.evaluate(
                    state, eval_noise_scale=0.0
                )  # no noise, deterministic policy gradients
                new_q_input = tf.concat([state, new_action], 1)
                # """ implementation 1 """
                # predicted_new_q_value = tf.minimum(self.q_net1(new_q_input),self.q_net2(new_q_input))
                """ implementation 2 """
                predicted_new_q_value = self.q_net1(new_q_input)
                policy_loss = -tf.reduce_mean(predicted_new_q_value)
            p_grad = p_tape.gradient(policy_loss, self.policy_net.trainable_weights)
            self.policy_optimizer.apply_gradients(zip(p_grad, self.policy_net.trainable_weights))

            # Soft update the target nets
            self.target_q_net1 = self.target_soft_update(self.q_net1, self.target_q_net1, soft_tau)
            self.target_q_net2 = self.target_soft_update(self.q_net2, self.target_q_net2, soft_tau)
            self.target_policy_net = self.target_soft_update(self.policy_net, self.target_policy_net, soft_tau)

    def save(self):  # save trained weights
        path = os.path.join('model', '_'.join([ALG_NAME, ENV_ID]))
        if not os.path.exists(path):
            os.makedirs(path)
        extend_path = lambda s: os.path.join(path, s)
        tl.files.save_npz(self.q_net1.trainable_weights, extend_path('model_q_net1.npz'))
        tl.files.save_npz(self.q_net2.trainable_weights, extend_path('model_q_net2.npz'))
        tl.files.save_npz(self.target_q_net1.trainable_weights, extend_path('model_target_q_net1.npz'))
        tl.files.save_npz(self.target_q_net2.trainable_weights, extend_path('model_target_q_net2.npz'))
        tl.files.save_npz(self.policy_net.trainable_weights, extend_path('model_policy_net.npz'))
        tl.files.save_npz(self.target_policy_net.trainable_weights, extend_path('model_target_policy_net.npz'))

    def load(self):  # load trained weights
        path = os.path.join('model', '_'.join([ALG_NAME, ENV_ID]))
        extend_path = lambda s: os.path.join(path, s)
        tl.files.load_and_assign_npz(extend_path('model_q_net1.npz'), self.q_net1)
        tl.files.load_and_assign_npz(extend_path('model_q_net2.npz'), self.q_net2)
        tl.files.load_and_assign_npz(extend_path('model_target_q_net1.npz'), self.target_q_net1)
        tl.files.load_and_assign_npz(extend_path('model_target_q_net2.npz'), self.target_q_net2)
        tl.files.load_and_assign_npz(extend_path('model_policy_net.npz'), self.policy_net)
        tl.files.load_and_assign_npz(extend_path('model_target_policy_net.npz'), self.target_policy_net)

if __name__ == '__main__':
    # initialization of env
    env = gym.make(ENV_ID).unwrapped
    state_dim = env.observation_space.shape[0]
    action_dim = env.action_space.shape[0]
    action_range = env.action_space.high  # scale action, [-action_range, action_range]

    # reproducible
    env.seed(RANDOM_SEED)
    random.seed(RANDOM_SEED)
    np.random.seed(RANDOM_SEED)
    tf.random.set_seed(RANDOM_SEED)

    # initialization of buffer
    replay_buffer = ReplayBuffer(REPLAY_BUFFER_SIZE)
    # initialization of trainer
    agent = TD3(
        state_dim, action_dim, action_range, HIDDEN_DIM, replay_buffer, POLICY_TARGET_UPDATE_INTERVAL, Q_LR, POLICY_LR
    )
    t0 = time.time()

    # training loop
    if args.train:
        frame_idx = 0
        all_episode_reward = []

        # need an extra call here to make inside functions be able to use model.forward
        state = env.reset().astype(np.float32)
        agent.policy_net([state])
        agent.target_policy_net([state])

        for episode in range(TRAIN_EPISODES):
            state = env.reset().astype(np.float32)
            episode_reward = 0

            for step in range(MAX_STEPS):
                if RENDER:
                    env.render()
                if frame_idx > EXPLORE_STEPS:
                    action = agent.policy_net.get_action(state, EXPLORE_NOISE_SCALE)
                else:
                    action = agent.policy_net.sample_action()

                next_state, reward, done, _ = env.step(action)
                next_state = next_state.astype(np.float32)
                done = 1 if done is True else 0

                replay_buffer.push(state, action, reward, next_state, done)
                state = next_state
                episode_reward += reward
                frame_idx += 1

                if len(replay_buffer) > BATCH_SIZE:
                    for i in range(UPDATE_ITR):
                        agent.update(BATCH_SIZE, EVAL_NOISE_SCALE, REWARD_SCALE)

                if done:
                    break
            if episode == 0:
                all_episode_reward.append(episode_reward)
            else:
                all_episode_reward.append(all_episode_reward[-1] * 0.9 + episode_reward * 0.1)
            print(
                'Training  | Episode: {}/{}  | Episode Reward: {:.4f}  | Running Time: {:.4f}'.format(
                    episode + 1, TRAIN_EPISODES, episode_reward,
                    time.time() - t0
                )
            )
        agent.save()
        plt.plot(all_episode_reward)
        if not os.path.exists('image'):
            os.makedirs('image')
        plt.savefig(os.path.join('image', '_'.join([ALG_NAME, ENV_ID])))

    if args.test:
        agent.load()

        # need an extra call here to make inside functions be able to use model.forward
        state = env.reset().astype(np.float32)
        agent.policy_net([state])

        for episode in range(TEST_EPISODES):
            state = env.reset().astype(np.float32)
            episode_reward = 0
            for step in range(MAX_STEPS):
                env.render()
                action = agent.policy_net.get_action(state, EXPLORE_NOISE_SCALE, greedy=True)
                state, reward, done, info = env.step(action)
                state = state.astype(np.float32)
                episode_reward += reward
                if done:
                    break
            print(
                'Testing  | Episode: {}/{}  | Episode Reward: {:.4f}  | Running Time: {:.4f}'.format(
                    episode + 1, TEST_EPISODES, episode_reward,
                    time.time() - t0
                )
            )


text:
package org.apache.camel.component.xmpp;

import java.io.InputStream;
import java.net.InetAddress;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.Arrays;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

import org.apache.camel.impl.JndiRegistry;
import org.apache.camel.test.AvailablePortFinder;
import org.apache.camel.util.ObjectHelper;
import org.apache.vysper.mina.TCPEndpoint;
import org.apache.vysper.storage.StorageProviderRegistry;
import org.apache.vysper.storage.inmemory.MemoryStorageProviderRegistry;
import org.apache.vysper.xmpp.addressing.Entity;
import org.apache.vysper.xmpp.addressing.EntityImpl;
import org.apache.vysper.xmpp.authorization.AccountManagement;
import org.apache.vysper.xmpp.authorization.Anonymous;
import org.apache.vysper.xmpp.authorization.SASLMechanism;
import org.apache.vysper.xmpp.modules.extension.xep0045_muc.MUCModule;
import org.apache.vysper.xmpp.modules.extension.xep0045_muc.model.Conference;
import org.apache.vysper.xmpp.modules.extension.xep0045_muc.model.RoomType;
import org.apache.vysper.xmpp.server.XMPPServer;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jxmpp.jid.impl.JidCreate;

public final class EmbeddedXmppTestServer {

    private static EmbeddedXmppTestServer instance;

    private XMPPServer xmppServer;
    private TCPEndpoint endpoint;
    private int port;

    // restricted to singleton
    private EmbeddedXmppTestServer()  { }

    public static EmbeddedXmppTestServer instance()  {
        if (instance == null) {
            instance = new EmbeddedXmppTestServer();
            instance.initializeXmppServer();
        }
        return instance;
    }

    private void initializeXmppServer() {
        try {
            if (xmppServer == null) {
                xmppServer = new XMPPServer("apache.camel");

                StorageProviderRegistry providerRegistry = new MemoryStorageProviderRegistry();
                AccountManagement accountManagement = (AccountManagement) providerRegistry.retrieve(AccountManagement.class);

                Entity user = EntityImpl.parseUnchecked("camel_consumer@apache.camel");
                accountManagement.addUser(user, "secret");

                Entity user2 = EntityImpl.parseUnchecked("camel_producer@apache.camel");
                accountManagement.addUser(user2, "secret");

                Entity user3 = EntityImpl.parseUnchecked("camel_producer1@apache.camel");
                accountManagement.addUser(user3, "secret");

                xmppServer.setStorageProviderRegistry(providerRegistry);

                if (endpoint == null) {
                    endpoint = new TCPEndpoint();
                    this.port = AvailablePortFinder.getNextAvailable(5222);
                    endpoint.setPort(port);
                }

                xmppServer.addEndpoint(endpoint);

                InputStream stream = ObjectHelper.loadResourceAsStream("xmppServer.jks");
                xmppServer.setTLSCertificateInfo(stream, "secret");

                // allow anonymous logins
                xmppServer.setSASLMechanisms(Arrays.asList(new SASLMechanism[]{new Anonymous()}));

                xmppServer.start();

                // add the multi-user chat module and create a few test rooms
                Conference conference = new Conference("test conference");
                conference.createRoom(EntityImpl.parseUnchecked("camel-anon@apache.camel"), "camel-anon", RoomType.FullyAnonymous);
                conference.createRoom(EntityImpl.parseUnchecked("camel-test@apache.camel"), "camel-test", RoomType.Public);
                xmppServer.addModule(new MUCModule("conference", conference));
            }
        } catch (Exception e) {
            throw new RuntimeException("An error occurred when initializing the XMPP Test Server.", e);
        }
    }

    public void startXmppEndpoint() throws Exception {
        endpoint.start();
    }

    public void stopXmppEndpoint() {
        endpoint.stop();
    }

    public int getXmppPort() {
        return port;
    }

    public void bindSSLContextTo(JndiRegistry registry) throws Exception {
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(ObjectHelper.loadResourceAsStream("xmppServer.jks"), "secret".toCharArray());

        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());

        ConnectionConfiguration connectionConfig = XMPPTCPConnectionConfiguration.builder()
                .setXmppDomain(JidCreate.domainBareFrom("apache.camel"))
                .setHostAddress(InetAddress.getLocalHost())
                .setPort(getXmppPort())
                .setCustomSSLContext(sslContext)
                .setHostnameVerifier((hostname, session) -> true)
                .build();

        registry.bind("customConnectionConfig", connectionConfig);
    }
}


text:
function [hlist, lengthwidth] = coordframesheetlet(title,typeName,upperLeft)

button.Units = 'pixels';
button.BackgroundColor = [0.8 0.8 0.8];
button.HorizontalAlignment = 'center';
button.Callback = ['sheetlet_callback(''coordframesheetlet_process'',''' typeName ''');'];

txt.Units = 'pixels'; txt.BackgroundColor = [0.8 0.8 0.8];
txt.fontsize = 10; txt.fontweight = 'normal';
txt.HorizontalAlignment = 'center';txt.Style='text';

edit = txt; edit.BackgroundColor = [ 1 1 1]; edit.Style = 'Edit';

popup = txt; popup.style = 'popupmenu';popup.Callback = ['sheetlet_callback(''coordframesheetlet_process'',''' typeName ''');'];

cb = txt; cb.Style = 'Checkbox'; cb.Callback = ['sheetlet_callback(''coordframesheetlet_process'',''' typeName ''');'];
cb.fontsize = 12;

list=button;list.style='list';

hlist = [];

h = uicontrol(txt,'position',[upperLeft(1)+10 upperLeft(2)-7 200 20],'string','Coordinate frames',...
		'Tag',[typeName 'CFtxt'], 'fontweight', 'bold', 'horizontalalignment', 'left');
hlist = [hlist h];

h = uicontrol(txt,'position',[upperLeft(1)+10 upperLeft(2)-50-20-5 30 20],'string','Add',...
		'Tag',[typeName 'Addtxt'], 'horizontalalignment', 'left');

hlist = [hlist h];

h = uicontrol(popup,'position',[upperLeft(1)+40 upperLeft(2)-50-20 70 20],'string',coordframe_types,...
		'Tag',[typeName 'AddPop']);
hlist = [hlist h];

h = uicontrol(button,'position',[upperLeft(1)+60+50+5 upperLeft(2)-50-20 50 20],'string','Delete',...
		'Tag',[typeName 'DeleteBt']);
hlist = [hlist h];

h = uicontrol(list,'position',[upperLeft(1)+10 upperLeft(2)-50 150 50],'Tag',[typeName 'CFList']);
hlist = [hlist h];

h=uicontrol(button,'position',[0 0 1 1],'String','RestoreVars','visible','off','Tag',[typeName 'RestoreVarsBt']);
hlist = [hlist h];

h=uicontrol(button,'position',[0 0 1 1],'String','SaveVars','visible','off','Tag',[typeName 'SaveVarsBt']);
hlist = [hlist h];

lengthwidth = [200 100];


text:
#import "SMBinaryDataConversion.h"
#import <CommonCrypto/CommonHMAC.h>
#import "Base64EncodedStringFromData.h"
#import "SMError.h"

@implementation SMBinaryDataConversion

+ (NSString *)stringForBinaryData:(NSData *)data name:(NSString *)name contentType:(NSString *)contentType
{

    return [NSString stringWithFormat:@"Content-Type: %@\n"
            "Content-Disposition: attachment; filename=%@\n"
            "Content-Transfer-Encoding: %@\n\n"
            "%@",
            contentType,
            name,
            @"base64",
            Base64EncodedStringFromData(data)];
}

+ (NSData *)dataForString:(NSString *)string
{
    NSArray *components = [string componentsSeparatedByString:@"base64"];
    if ([components count] != 2) {
        [NSException raise:SMExceptionIncompatibleObject format:@"String to be converted to data is not in the correct form.  Make sure this method is only called on attributes which map to binary fields on StackMob and have not yet been saved."];
    }

    NSString *stringToDecode = components[1];
    NSData *dataToReturn = Base64DecodedDataFromString(stringToDecode);

    return dataToReturn;

}

+ (BOOL)stringContainsURL:(NSString *)value
{
    NSRange range = [value rangeOfString:@"Content-Type"];
    return range.location == NSNotFound;
}

@end


text:
/**
 * A Lisp-inspired trick to enable an open-ended number of type variables.
 *

 * This package offers two main classes: {@link org.sbrubbles.genericcons.C C}, which builds the type list like Lisp's
 * cons, and {@link org.sbrubbles.genericcons.Types Types}, which
 * provides methods for extracting type information.
 *

 * Basic usage:
 *

 * A<?, ?> f = new A<Integer, C<String, C<String, String>>>() {
 *   public Integer execute(Object... objects) {
 *     List<? extends Type> types = Types.fromSuperclass(this.getClass(), 1);
 *
 *     if(! Types.check(types, Arrays.asList(objects))) {
 *       return -1;
 *     }
 *
 *     String a = (String) objects[0];
 *     String b = (String) objects[1];
 *     String c = (String) objects[2];
 *
 *     return Math.max(a.length(), b.length(), c.length());
 *   }
 * };
 *

 *
 * @author Humberto Anjos
 */
package org.sbrubbles.genericcons;


text:
<button style="margin-bottom: 20px" ng-click="vm.createGame()" class="btn btn-info center-block">Create game</button>

            #
            Created by
            Second Player
            Game State

            {{$index + 1}}
            {{game.FirstPlayerName}}
            {{game.SecondPlayerName}}
            {{game | stateFilter}}
            Join


text:
get '/edits/teachers' do
  @title = "Peer Editing"
  if ["admin", "editor-in-chief"].include?(session[:role])
  	@teachers = Teacher.all
  elsif session[:role] == "teacher"
  	@teachers = Teacher.excludes(id: session[:teacher_id])
  end
  haml :"edits/teachers", :layout => :teacher_layout
end

get "/edits/:teacher_id" do
	teacher_id =  params[:teacher_id]
	@teacher  = Teacher.find_by(:id => params[:teacher_id])

	language_arts_students_skill_tracks  = SkillTrack.where(:grading_period => GradingPeriodPersist.all[0].grading_period.id.to_s, :language_arts_teacher  => teacher_id)
	math_students_skill_tracks           = SkillTrack.where(:grading_period => GradingPeriodPersist.all[0].grading_period.id.to_s, :math_teacher           => teacher_id)
	social_studies_students_skill_tracks = SkillTrack.where(:grading_period => GradingPeriodPersist.all[0].grading_period.id.to_s, :social_studies_teacher => teacher_id)
	science_students_skill_tracks        = SkillTrack.where(:grading_period => GradingPeriodPersist.all[0].grading_period.id.to_s, :science_teacher        => teacher_id)
	art_students_skill_tracks            = SkillTrack.where(:grading_period => GradingPeriodPersist.all[0].grading_period.id.to_s, :art_teacher            => teacher_id)
	ict_students_skill_tracks            = SkillTrack.where(:grading_period => GradingPeriodPersist.all[0].grading_period.id.to_s, :ict_teacher            => teacher_id)
	music_students_skill_tracks          = SkillTrack.where(:grading_period => GradingPeriodPersist.all[0].grading_period.id.to_s, :music_teacher          => teacher_id)
	thai_students_skill_tracks           = SkillTrack.where(:grading_period => GradingPeriodPersist.all[0].grading_period.id.to_s, :thai_teacher           => teacher_id)
	pe_students_skill_tracks             = SkillTrack.where(:grading_period => GradingPeriodPersist.all[0].grading_period.id.to_s, :pe_teacher             => teacher_id)
	work_study_students_skill_tracks     = SkillTrack.where(:grading_period => GradingPeriodPersist.all[0].grading_period.id.to_s, :work_study_teacher     => teacher_id)
	citizenship_students_skill_tracks    = SkillTrack.where(:grading_period => GradingPeriodPersist.all[0].grading_period.id.to_s, :citizenship_teacher    => teacher_id)

	#begin
		language_arts_id = Subject.find_by(:subject_id => "language_arts").id.to_s
		language_arts_outcome_sets = language_arts_students_skill_tracks.collect { |skill_track| skill_track.outcome_sets.find_by(:subject_id => language_arts_id) }

		language_arts_students = []
		language_arts_outcome_sets.each do |set|
			language_arts_component = {}
			language_arts_component[:skill_track] = set.skill_track
			language_arts_component[:language_arts_level] = set.skill_track.language_arts_level
			language_arts_component[:student_name] = Student.find("#{set.skill_track.student_id}").name
			language_arts_component[:student_id] = set.skill_track.student_id
			language_arts_component[:comment_object] = set.commentos
			language_arts_component[:latest_comment] = set.commentos[-1]
# Need to set language_arts_component[:editor]
		language_arts_students << language_arts_component
		end
		@language_arts = language_arts_students

		math_id = Subject.find_by(:subject_id => "math").id.to_s
		math_outcome_sets = math_students_skill_tracks.collect { |skill_track| skill_track.outcome_sets.find_by(:subject_id => math_id) }

		math_students = []
		math_outcome_sets.each do |set|
			math_component = {}
			math_component[:skill_track] = set.skill_track
			math_component[:math_level] = set.skill_track.math_level
			math_component[:student_name] = Student.find("#{set.skill_track.student_id}").name
			math_component[:student_id] = set.skill_track.student_id
			math_component[:comment_object] = set.commentos
			math_component[:latest_comment] = set.commentos[-1]

		math_students << math_component
		end
		@math = math_students
		haml :"edits/teacher_subjects", :layout => :teacher_layout
	#rescue
	#	pp params
	#	haml :"edits/fail", :layout => :teacher_layout
	#end

end
#/edit/submit/language_arts/#{Student.find_by(name: la[:student_name]).id}/#{la[:skill_track].id/#{@teacher.id}
post "/edit/submit/:subject_id/:student_id/:skill_track_id/:teacher_id" do
	form = params[:comment_form]

	student = Student.find_by(:id => params[:student_id])
	skill_track = student.skill_tracks.find_by(:id => params[:skill_track_id])

unless form["language_arts_comment"].nil?
	language_arts_outcome_set = skill_track.outcome_sets.find_by(:subject_id => Subject.find_by(:subject_id => "language_arts"))
	#language_arts_outcome_set.commentos.create!(:texto => form["language_arts_comment"])
	raw_comment = form["language_arts_comment"]
	processed_comment = raw_comment.paragraph_prep
	doub = doublespacer(processed_comment)
	doub.paragraph_reinsertion
	language_arts_outcome_set.commentos.create!(:texto => doub, :editor => form["editor"])
	language_arts_outcome_set.save
end

unless form["math_comment_comment"].nil?
	math_outcome_set = skill_track.outcome_sets.find_by(:subject_id => Subject.find_by(:subject_id => "math"))
	raw_comment = form["math_comment"]
	processed_comment = raw_comment.paragraph_prep
	doub = doublespacer(processed_comment)
	doub.paragraph_reinsertion
	math_outcome_set.commentos.create!(:texto => doub, :editor => form["editor"])
	math_outcome_set.save
end

unless form["social_studies_comment_comment"].nil?
	social_studies_outcome_set = skill_track.outcome_sets.find_by(:subject_id => Subject.find_by(:subject_id => "social_studies"))
	raw_comment = form["social_studies_comment"]
	processed_comment = raw_comment.paragraph_prep
	doub = doublespacer(processed_comment)
	doub.paragraph_reinsertion
	social_studies_outcome_set.commentos.create!(:texto => doub, :editor => form["editor"])
	social_studies_outcome_set.save
end

unless form["science_comment_comment"].nil?
	science_outcome_set = skill_track.outcome_sets.find_by(:subject_id => Subject.find_by(:subject_id => "science"))
	raw_comment = form["science_comment"]
	processed_comment = raw_comment.paragraph_prep
	doub = doublespacer(processed_comment)
	doub.paragraph_reinsertion
	science_outcome_set.commentos.create!(:texto => doub, :editor => form["editor"])
	science_outcome_set.save
end

unless form["work_study_comment_comment"].nil?
	work_study_outcome_set = skill_track.outcome_sets.find_by(:subject_id => Subject.find_by(:subject_id => "work_study"))
	raw_comment = form["work_study_comment"]
	processed_comment = raw_comment.paragraph_prep
	doub = doublespacer(processed_comment)
	doub.paragraph_reinsertion
	work_study_outcome_set.commentos.create!(:texto => doub, :editor => form["editor"])
	work_study_outcome_set.save
end

unless form["citizenship_comment_comment"].nil?
	citizenship_outcome_set = skill_track.outcome_sets.find_by(:subject_id => Subject.find_by(:subject_id => "citizenship"))
	raw_comment = form["citizenship_comment"]
	processed_comment = raw_comment.paragraph_prep
	doub = doublespacer(processed_comment)
	doub.paragraph_reinsertion
	citizenship_outcome_set.commentos.create!(:texto => doub, :editor => form["editor"])
	citizenship_outcome_set.save
end

unless form["art_comment_comment"].nil?
	art_outcome_set = skill_track.outcome_sets.find_by(:subject_id => Subject.find_by(:subject_id => "art"))
	raw_comment = form["art_comment"]
	processed_comment = raw_comment.paragraph_prep
	doub = doublespacer(processed_comment)
	doub.paragraph_reinsertion
	art_outcome_set.commentos.create!(:texto => doub, :editor => form["editor"])
	art_outcome_set.save
end

unless form["ict_comment_comment"].nil?
	ict_outcome_set = skill_track.outcome_sets.find_by(:subject_id => Subject.find_by(:subject_id => "ict"))
	raw_comment = form["ict_comment"]
	processed_comment = raw_comment.paragraph_prep
	doub = doublespacer(processed_comment)
	doub.paragraph_reinsertion
	ict_outcome_set.commentos.create!(:texto => doub, :editor => form["editor"])
	ict_outcome_set.save
end

unless form["music_comment_comment"].nil?
	music_outcome_set = skill_track.outcome_sets.find_by(:subject_id => Subject.find_by(:subject_id => "music"))
	raw_comment = form["music_comment"]
	processed_comment = raw_comment.paragraph_prep
	doub = doublespacer(processed_comment)
	doub.paragraph_reinsertion
	music_outcome_set.commentos.create!(:texto => doub, :editor => form["editor"])
	music_outcome_set.save
end

unless form["pe_comment_comment"].nil?
	pe_outcome_set = skill_track.outcome_sets.find_by(:subject_id => Subject.find_by(:subject_id => "pe"))
	raw_comment = form["pe_comment"]
	processed_comment = raw_comment.paragraph_prep
	doub = doublespacer(processed_comment)
	doub.paragraph_reinsertion
	pe_outcome_set.commentos.create!(:texto => doub, :editor => form["editor"])
	pe_outcome_set.save
end

unless form["thai_comment_comment"].nil?
	thai_outcome_set = skill_track.outcome_sets.find_by(:subject_id => Subject.find_by(:subject_id => "thai"))
	raw_comment = form["thai_comment"]
	processed_comment = raw_comment.paragraph_prep
	doub = doublespacer(processed_comment)
	doub.paragraph_reinsertion
	thai_outcome_set.commentos.create!(:texto => doub, :editor => form["editor"])
	thai_outcome_set.save
end

	redirect to("/edits/#{params[:teacher_id]}##{params[:subject_id]}_#{params[:student_id]}")
end


text:
#include "cvector_void.h"

#if defined(CVEC_MALLOC) && defined(CVEC_FREE) && defined(CVEC_REALLOC)
/* ok */
#elif !defined(CVEC_MALLOC) && !defined(CVEC_FREE) && !defined(CVEC_REALLOC)
/* ok */
#else
#error "Must define all or none of CVEC_MALLOC, CVEC_FREE, and CVEC_REALLOC."
#endif

#ifndef CVEC_MALLOC
#define CVEC_MALLOC(sz)      malloc(sz)
#define CVEC_REALLOC(p, sz)  realloc(p, sz)
#define CVEC_FREE(p)         free(p)
#endif

#ifndef CVEC_MEMMOVE
#include <string.h>
#define CVEC_MEMMOVE(dst, src, sz)  memmove(dst, src, sz)
#endif

#ifndef CVEC_ASSERT
#include <assert.h>
#define CVEC_ASSERT(x)       assert(x)
#endif

size_t CVEC_VOID_START_SZ = 20;

#define CVEC_VOID_ALLOCATOR(x) ((x+1) * 2)

/**
 * Creates a new vector on the heap.
 * Vector size set to (size > 0) ? size : 0;
 * Capacity to (capacity > vec->size || (vec->size && capacity == vec->size)) ? capacity : vec->size + CVEC_VOID_START_SZ
 * in other words capacity has to be at least 1 and >= to vec->size of course.
 * elem_sz is the size of the type you want to store ( ie sizeof(T) where T is your type ).
 * You can pass in an optional function, elem_free, to be called on every element before it is erased
 * from the vector to free any dynamically allocated memory.  Likewise you can pass in elem_init to be
 * as a sort of copy constructor for any insertions if you needed some kind of deep copy/allocations.
 *
 * For example if you passed in sizeof(char*) for elem_sz, and wrappers around the standard free(void*)
 * function for elem_free and CVEC_STRDUP for elem_init you could
 * make vector work *almost* exactly like cvector_str.  The main difference is cvector_str does not
 * check for failure of CVEC_STRDUP while cvector_void does check for failure of elem_init.  The other
 * minor differences are popm and replacem are macros in cvector_str (and the latter returns the result
 * rather than using a double pointer return parameter) and depending on how you defined elem_init
 * and whether you're using the 'move' functions, you have to pass in char**'s instead of char*'s
 * because cvector_void has to use memmove rather than straight assignment.
 *
 * Pass in NULL, to not use the function parameters.
 *
 * The function remove and the 'move' functions (with the m suffix) do not call elem_init or elem_free
 * even if they are set.  This gives you some flexibility and performance when you already have things
 * allocated or want to keep things after removing them from the vector but only some of the time (otherwise
 * you wouldn't have defined elem_free/elem_init in the first place).
 *
 * See the other functions and the tests for more behavioral/usage details.
 */
cvector_void* cvec_void_heap(size_t size, size_t capacity, size_t elem_sz, void(*elem_free)(void*), int(*elem_init)(void*, void*))
{
	cvector_void* vec;
	if (!(vec = (cvector_void*)CVEC_MALLOC(sizeof(cvector_void)))) {
		CVEC_ASSERT(vec != NULL);
		return NULL;
	}

	vec->size = size;
	vec->capacity = (capacity > vec->size || (vec->size && capacity == vec->size)) ? capacity : vec->size + CVEC_VOID_START_SZ;

	vec->elem_size = elem_sz;

	if (!(vec->a = (cvec_u8*)CVEC_MALLOC(vec->capacity*elem_sz))) {
		CVEC_ASSERT(vec->a != NULL);
		CVEC_FREE(vec);
		return NULL;
	}
	/* not clearing to 0 here as in cvector_str because elem_free cannot be calling CVEC_FREE directly
	 * since it takes the address of the element not the element itself */

	vec->elem_free = elem_free;
	vec->elem_init = elem_init;

	return vec;
}

/** Create (on the heap) and initialize vector with num elements of vals.
 *  elem_sz is the size of the type you want to store ( ie sizeof(T) where T is your type ).
 *  See cvec_void_heap() for more information about the elem_free and elem_init parameters.
 */
cvector_void* cvec_init_void_heap(void* vals, size_t num, size_t elem_sz, void(*elem_free)(void*), int(*elem_init)(void*, void*))
{
	cvector_void* vec;
	size_t i;

	if (!(vec = (cvector_void*)CVEC_MALLOC(sizeof(cvector_void)))) {
		CVEC_ASSERT(vec != NULL);
		return NULL;
	}

	vec->elem_size = elem_sz;

	vec->capacity = num + CVEC_VOID_START_SZ;
	vec->size = num;
	if (!(vec->a = (cvec_u8*)CVEC_MALLOC(vec->capacity*elem_sz))) {
		CVEC_ASSERT(vec->a != NULL);
		CVEC_FREE(vec);
		return NULL;
	}

	if (elem_init) {
		for (i=0; i<num; ++i) {
			if (!elem_init(&vec->a[i*elem_sz], &((cvec_u8*)vals)[i*elem_sz])) {
				CVEC_ASSERT(0);
				CVEC_FREE(vec->a);
				CVEC_FREE(vec);
				return NULL;
			}
		}
	} else {
		CVEC_MEMMOVE(vec->a, vals, elem_sz*num);
	}

	vec->elem_free = elem_free;
	vec->elem_init = elem_init;

	return vec;
}

/** Same as cvec_void_heap() except the vector passed in was declared on the stack so
 *  it isn't allocated in this function.  Use the cvec_free_void in that case
 */
int cvec_void(cvector_void* vec, size_t size, size_t capacity, size_t elem_sz, void(*elem_free)(void*), int(*elem_init)(void*, void*))
{
	vec->size = size;
	vec->capacity = (capacity > vec->size || (vec->size && capacity == vec->size)) ? capacity : vec->size + CVEC_VOID_START_SZ;

	vec->elem_size = elem_sz;

	if (!(vec->a = (cvec_u8*)CVEC_MALLOC(vec->capacity*elem_sz))) {
		CVEC_ASSERT(vec->a != NULL);
		vec->size = vec->capacity = 0;
		return 0;
	}

	vec->elem_free = elem_free;
	vec->elem_init = elem_init;

	return 1;
}

/** Same as init_vec_heap() except the vector passed in was declared on the stack so
 *  it isn't allocated in this function.  Use the cvec_free_void in this case
 */
int cvec_init_void(cvector_void* vec, void* vals, size_t num, size_t elem_sz, void(*elem_free)(void*), int(*elem_init)(void*, void*))
{
	size_t i;

	vec->elem_size = elem_sz;

	vec->capacity = num + CVEC_VOID_START_SZ;
	vec->size = num;
	if (!(vec->a = (cvec_u8*)CVEC_MALLOC(vec->capacity*elem_sz))) {
		CVEC_ASSERT(vec->a != NULL);
		vec->size = vec->capacity = 0;
		return 0;
	}

	if (elem_init) {
		for (i=0; i<num; ++i) {
			if (!elem_init(&vec->a[i*elem_sz], &((cvec_u8*)vals)[i*elem_sz])) {
				CVEC_ASSERT(0);
				return 0;
			}
		}
	} else {
		CVEC_MEMMOVE(vec->a, vals, elem_sz*num);
	}

	vec->elem_free = elem_free;
	vec->elem_init = elem_init;

	return 1;
}

/** Makes dest a copy of src.  The parameters
 *  are void so it can be used as the constructor when making
 *  a vector of cvector_void's.  Assumes dest (the structure)
 *  is already allocated (probably on the stack) and that
 *  capacity is 0 (ie the array doesn't need to be freed).
 *
 *  Really just a wrapper around copy, that initializes dest/vec1's
 *  members to NULL/0.  If you pre-initialized dest to 0, you could
 *  just use copy.
 */
int cvec_copyc_void(void* dest, void* src)
{
	cvector_void* vec1 = (cvector_void*)dest;
	cvector_void* vec2 = (cvector_void*)src;

	vec1->a = NULL;
	vec1->size = 0;
	vec1->capacity = 0;

	return cvec_copy_void(vec1, vec2);
}

/** Makes dest a copy of src.  Assumes dest
 * (the structure) is already allocated (probably on the stack) and
 * is in a valid state (ie array is either NULL or allocated with
 * size and capacity set appropriately).
 *
 * TODO Should I copy capacity, so dest is truly identical or do
 * I only care about the actual contents, and let dest->cap = src->size
 * maybe plus CVEC_VOID_START_SZ
 */
int cvec_copy_void(cvector_void* dest, cvector_void* src)
{
	int i;
	cvec_u8* tmp = NULL;
	if (!(tmp = (cvec_u8*)CVEC_REALLOC(dest->a, src->capacity*src->elem_size))) {
		CVEC_ASSERT(tmp != NULL);
		return 0;
	}
	dest->a = tmp;

	if (src->elem_init) {
		for (i=0; i<src->size; ++i) {
			if (!src->elem_init(&dest->a[i*src->elem_size], &src->a[i*src->elem_size])) {
				CVEC_ASSERT(0);
				return 0;
			}
		}
	} else {
		/* could use memcpy here since we know we just allocated dest->a */
		CVEC_MEMMOVE(dest->a, src->a, src->size*src->elem_size);
	}

	dest->size = src->size;
	dest->capacity = src->capacity;
	dest->elem_size = src->elem_size;
	dest->elem_free = src->elem_free;
	dest->elem_init = src->elem_init;
	return 1;
}

/** Append a to end of vector (size increased 1).
 * Capacity is increased by doubling when necessary.
 *
 * TODO For all of cvector_void, now that elem_init returns int, is it worth
 * the extra code and overhead of checking it and asserting/returning 0?
 */
int cvec_push_void(cvector_void* vec, void* a)
{
	cvec_u8* tmp;
	size_t tmp_sz;
	if (vec->capacity == vec->size) {
		tmp_sz = CVEC_VOID_ALLOCATOR(vec->capacity);
		if (!(tmp = (cvec_u8*)CVEC_REALLOC(vec->a, vec->elem_size*tmp_sz))) {
			CVEC_ASSERT(tmp != NULL);
			return 0;
		}
		vec->a = tmp;
		vec->capacity = tmp_sz;
	}
	if (vec->elem_init) {
		if (!vec->elem_init(&vec->a[vec->size*vec->elem_size], a)) {
			CVEC_ASSERT(0);
			return 0;
		}
	} else {
		CVEC_MEMMOVE(&vec->a[vec->size*vec->elem_size], a, vec->elem_size);
	}

	vec->size++;
	return 1;
}

/** Same as push except no elem_init even if it's set */
int cvec_pushm_void(cvector_void* vec, void* a)
{
	cvec_u8* tmp;
	size_t tmp_sz;
	if (vec->capacity == vec->size) {
		tmp_sz = CVEC_VOID_ALLOCATOR(vec->capacity);
		if (!(tmp = (cvec_u8*)CVEC_REALLOC(vec->a, vec->elem_size*tmp_sz))) {
			CVEC_ASSERT(tmp != NULL);
			return 0;
		}
		vec->a = tmp;
		vec->capacity = tmp_sz;
	}
	CVEC_MEMMOVE(&vec->a[vec->size*vec->elem_size], a, vec->elem_size);

	vec->size++;
	return 1;
}

/** Remove the last element (size decreased 1).
 * Copy the element into ret if ret is not NULL.  This function assumes
 * that ret is large accept the element and just CVEC_MEMMOVE's it in.
 * Similar to pop_backs it is users responsibility.
 */
void cvec_pop_void(cvector_void* vec, void* ret)
{
	vec->size--;
	if (ret) {
		CVEC_MEMMOVE(ret, &vec->a[vec->size*vec->elem_size], vec->elem_size);
	}
	if (vec->elem_free) {
		vec->elem_free(&vec->a[vec->size*vec->elem_size]);
	}
}

/** Same as pop except no elem_free even if it's set. */
void cvec_popm_void(cvector_void* vec, void* ret)
{
	vec->size--;
	if (ret) {
		CVEC_MEMMOVE(ret, &vec->a[vec->size*vec->elem_size], vec->elem_size);
	}
}

/** Return pointer to last element */
void* cvec_back_void(cvector_void* vec)
{
	return &vec->a[(vec->size-1)*vec->elem_size];
}

/** Increase the size of the array num items.  Items
 *  are not initialized to anything! */
int cvec_extend_void(cvector_void* vec, size_t num)
{
	cvec_u8* tmp;
	size_t tmp_sz;
	if (vec->capacity < vec->size + num) {
		tmp_sz = vec->capacity + num + CVEC_VOID_START_SZ;
		if (!(tmp = (cvec_u8*)CVEC_REALLOC(vec->a, vec->elem_size*tmp_sz))) {
			CVEC_ASSERT(tmp != NULL);
			return 0;
		}
		vec->a = tmp;
		vec->capacity = tmp_sz;
	}

	vec->size += num;
	return 1;
}

/** Return a void pointer to the ith element.
  * Another way to get elements from vector that is used in vector_tests.c
  * is a macro like this one
  * #define GET_ELEMENT(VEC,I,TYPE) ((TYPE*)&VEC.a[(I)*VEC.elem_size])
*/
void* cvec_get_void(cvector_void* vec, size_t i)
{
	return &vec->a[i*vec->elem_size];
}

/**
 * Insert a at index i (0 based).
 * Everything from that index and right is shifted one to the right.
 */
int cvec_insert_void(cvector_void* vec, size_t i, void* a)
{
	cvec_u8* tmp;
	size_t tmp_sz;
	if (vec->capacity == vec->size) {
		tmp_sz = CVEC_VOID_ALLOCATOR(vec->capacity);
		if (!(tmp = (cvec_u8*)CVEC_REALLOC(vec->a, vec->elem_size*tmp_sz))) {
			CVEC_ASSERT(tmp != NULL);
			return 0;
		}

		vec->a = tmp;
		vec->capacity = tmp_sz;
	}
	CVEC_MEMMOVE(&vec->a[(i+1)*vec->elem_size], &vec->a[i*vec->elem_size], (vec->size-i)*vec->elem_size);

	if (vec->elem_init) {
		if (!vec->elem_init(&vec->a[i*vec->elem_size], a)) {
			CVEC_ASSERT(0);
			return 0;
		}
	} else {
		CVEC_MEMMOVE(&vec->a[i*vec->elem_size], a, vec->elem_size);
	}

	vec->size++;
	return 1;
}

/** Same as insert but no elem_init even if defined. */
int cvec_insertm_void(cvector_void* vec, size_t i, void* a)
{
	cvec_u8* tmp;
	size_t tmp_sz;
	if (vec->capacity == vec->size) {
		tmp_sz = CVEC_VOID_ALLOCATOR(vec->capacity);
		if (!(tmp = (cvec_u8*)CVEC_REALLOC(vec->a, vec->elem_size*tmp_sz))) {
			CVEC_ASSERT(tmp != NULL);
			return 0;
		}

		vec->a = tmp;
		vec->capacity = tmp_sz;
	}
	CVEC_MEMMOVE(&vec->a[(i+1)*vec->elem_size], &vec->a[i*vec->elem_size], (vec->size-i)*vec->elem_size);

	CVEC_MEMMOVE(&vec->a[i*vec->elem_size], a, vec->elem_size);

	vec->size++;
	return 1;
}

/**
 * Insert the first num elements of array a at index i.
 * Note that it is the user's responsibility to pass in val_id
 * arguments.  Also CVEC_MEMMOVE is used (when there is no elem_init function)
 * so don't try to insert part of the vector array into itself
 * (that would require CVEC_MEMMOVE)
 */
int cvec_insert_array_void(cvector_void* vec, size_t i, void* a, size_t num)
{
	cvec_u8* tmp;
	size_t tmp_sz, j;
	if (vec->capacity < vec->size + num) {
		tmp_sz = vec->capacity + num + CVEC_VOID_START_SZ;
		if (!(tmp = (cvec_u8*)CVEC_REALLOC(vec->a, vec->elem_size*tmp_sz))) {
			CVEC_ASSERT(tmp != NULL);
			return 0;
		}
		vec->a = tmp;
		vec->capacity = tmp_sz;
	}

	CVEC_MEMMOVE(&vec->a[(i+num)*vec->elem_size], &vec->a[i*vec->elem_size], (vec->size-i)*vec->elem_size);
	if (vec->elem_init) {
		for (j=0; j<num; ++j) {
			if (!vec->elem_init(&vec->a[(j+i)*vec->elem_size], &((cvec_u8*)a)[j*vec->elem_size])) {
				CVEC_ASSERT(0);
				return 0;
			}
		}
	} else {
		CVEC_MEMMOVE(&vec->a[i*vec->elem_size], a, num*vec->elem_size);
	}
	vec->size += num;
	return 1;
}

/** Same as insert_array but no elem_init even if defined. */
int cvec_insert_arraym_void(cvector_void* vec, size_t i, void* a, size_t num)
{
	cvec_u8* tmp;
	size_t tmp_sz;
	if (vec->capacity < vec->size + num) {
		tmp_sz = vec->capacity + num + CVEC_VOID_START_SZ;
		if (!(tmp = (cvec_u8*)CVEC_REALLOC(vec->a, vec->elem_size*tmp_sz))) {
			CVEC_ASSERT(tmp != NULL);
			return 0;
		}
		vec->a = tmp;
		vec->capacity = tmp_sz;
	}

	CVEC_MEMMOVE(&vec->a[(i+num)*vec->elem_size], &vec->a[i*vec->elem_size], (vec->size-i)*vec->elem_size);

	CVEC_MEMMOVE(&vec->a[i*vec->elem_size], a, num*vec->elem_size);
	vec->size += num;
	return 1;
}

/**
 * Replace value at i with a, return old value in ret if non-NULL.
 */
int cvec_replace_void(cvector_void* vec, size_t i, void* a, void* ret)
{
	if (ret) {
		CVEC_MEMMOVE(ret, &vec->a[i*vec->elem_size], vec->elem_size);
	} else if (vec->elem_free) {
		vec->elem_free(&vec->a[i*vec->elem_size]);
	}

	if (vec->elem_init) {
		if (!vec->elem_init(&vec->a[i*vec->elem_size], a)) {
			CVEC_ASSERT(0);
			return 0;
		}
	} else {
		CVEC_MEMMOVE(&vec->a[i*vec->elem_size], a, vec->elem_size);
	}
	return 1;
}

/**
 * Same as replace but no elem_free or elem_init even if they're defined.
 * Because it doesn't call elem_init, there's no chance of failure so there's
 * no return value.
 */
void cvec_replacem_void(cvector_void* vec, size_t i, void* a, void* ret)
{
	if (ret) {
		CVEC_MEMMOVE(ret, &vec->a[i*vec->elem_size], vec->elem_size);
	}

	CVEC_MEMMOVE(&vec->a[i*vec->elem_size], a, vec->elem_size);
}

/**
 * Erases elements from start to end inclusive.
 * Example cvec_erase_void(myvec, 1, 3) would call elem_free (if an elem_free function was provided)
 * and remove elements at 1, 2, and 3 and the element that was at index 4 would now be at 1 etc.
 */
void cvec_erase_void(cvector_void* vec, size_t start, size_t end)
{
	size_t i;
	size_t d = end - start + 1;
	if (vec->elem_free) {
		for (i=start; i<=end; i++) {
			vec->elem_free(&vec->a[i*vec->elem_size]);
		}
	}
	CVEC_MEMMOVE(&vec->a[start*vec->elem_size], &vec->a[(end+1)*vec->elem_size], (vec->size-1-end)*vec->elem_size);
	vec->size -= d;
}

/** Same as erase except it *does not* call elem_free */
void cvec_remove_void(cvector_void* vec, size_t start, size_t end)
{
	size_t d = end - start + 1;
	CVEC_MEMMOVE(&vec->a[start*vec->elem_size], &vec->a[(end+1)*vec->elem_size], (vec->size-1-end)*vec->elem_size);
	vec->size -= d;
}

/** Makes sure capacity >= size (the parameter not the member). */
int cvec_reserve_void(cvector_void* vec, size_t size)
{
	cvec_u8* tmp;
	if (vec->capacity < size) {
		if (!(tmp = (cvec_u8*)CVEC_REALLOC(vec->a, vec->elem_size*(size+CVEC_VOID_START_SZ)))) {
			CVEC_ASSERT(tmp != NULL);
			return 0;
		}
		vec->a = tmp;
		vec->capacity = size + CVEC_VOID_START_SZ;
	}
	return 1;
}

/** Set capacity to size.
 * You will lose data if you shrink the capacity below the current size.
 * If you do, the size will be set to capacity of course.
*/
int cvec_set_cap_void(cvector_void* vec, size_t size)
{
	size_t i;
	cvec_u8* tmp;
	if (size < vec->size) {
		if (vec->elem_free) {
			for (i=vec->size-1; i>=size; i--) {
				vec->elem_free(&vec->a[i*vec->elem_size]);
			}
		}
		vec->size = size;
	}

	vec->capacity = size;

	if (!(tmp = (cvec_u8*)CVEC_REALLOC(vec->a, vec->elem_size*size))) {
		CVEC_ASSERT(tmp != NULL);
		return 0;
	}
	vec-> a = tmp;
	return 1;
}

/** Set all size elements to val. */
int cvec_set_val_sz_void(cvector_void* vec, void* val)
{
	size_t i;

	if (vec->elem_free) {
		for(i=0; i<vec->size; i++) {
			vec->elem_free(&vec->a[i*vec->elem_size]);
		}
	}

	if (vec->elem_init) {
		for (i=0; i<vec->size; i++) {
			if (!vec->elem_init(&vec->a[i*vec->elem_size], val)) {
				CVEC_ASSERT(0);
				return 0;
			}
		}
	} else {
		for (i=0; i<vec->size; i++) {
			CVEC_MEMMOVE(&vec->a[i*vec->elem_size], val, vec->elem_size);
		}
	}
	return 1;
}

/** Fills entire allocated array (capacity) with val.  If you set an elem_free function
 * then size is set to capacity like cvector_str for the same reason, ie I need to know
 * that the elem_free function needs to be called on those elements.
 * TODO Remove this function?  Same reason as set_val_cap_str.
 */
int cvec_set_val_cap_void(cvector_void* vec, void* val)
{
	size_t i;
	if (vec->elem_free) {
		for (i=0; i<vec->size; i++) {
			vec->elem_free(&vec->a[i*vec->elem_size]);
		}
		vec->size = vec->capacity;
	}

	if (vec->elem_init) {
		for (i=0; i<vec->capacity; i++) {
			if (!vec->elem_init(&vec->a[i*vec->elem_size], val)) {
				CVEC_ASSERT(0);
				return 0;
			}
		}
	} else {
		for (i=0; i<vec->capacity; i++) {
			CVEC_MEMMOVE(&vec->a[i*vec->elem_size], val, vec->elem_size);
		}
	}
	return 1;
}

/** Sets size to 0 (does not change contents unless elem_free is set
 *  then it will elem_free all size elements as in cvector_str). */
void cvec_clear_void(cvector_void* vec)
{
	size_t i;
	if (vec->elem_free) {
		for (i=0; i<vec->size; ++i) {
			vec->elem_free(&vec->a[i*vec->elem_size]);
		}
	}
	vec->size = 0;
}

/** Frees everything so don't use vec after calling this. If you set an elem_free function
 * it will be called on all size elements of course. Passing NULL is a NO-OP, matching the behavior
 * of free(). */
void cvec_free_void_heap(void* vec)
{
	size_t i;
	cvector_void* tmp = (cvector_void*)vec;
	if (!tmp) return;
	if (tmp->elem_free) {
		for (i=0; i<tmp->size; i++) {
			tmp->elem_free(&tmp->a[i*tmp->elem_size]);
		}
	}
	CVEC_FREE(tmp->a);
	CVEC_FREE(tmp);
}

/** Frees the internal array and sets size and capacity to 0 */
void cvec_free_void(void* vec)
{
	size_t i;
	cvector_void* tmp = (cvector_void*)vec;
	if (tmp->elem_free) {
		for (i=0; i<tmp->size; i++) {
			tmp->elem_free(&tmp->a[i*tmp->elem_size]);
		}
	}

	CVEC_FREE(tmp->a);

	tmp->size = 0;
	tmp->capacity = 0;
}

/*! \mainpage CVector notes
 *

\section Intro
This is a relatively simple ANSI compliant C vector library with specific structures and
functions for int's, double's and string's and support for all other types
using either a generic structure where the type is passed in as void* and stored in a cvec_u8 array
(to avoid dereferencing void* warnings and frequent casting) or generated type-specific
vectors using a macro or template system (see below).

The generic vector is very flexible and allows you to provide free and init functions
if you like that it will call at appropriate times similar to the way C++ containers
will call destructors/constructors.

Other modifiable parameters are at the top of the respective cvector.c's
<pre>
size_t CVEC_I_START_SZ = 50;
size_t CVEC_D_START_SZ = 50;
size_t CVEC_STR_START_SZ = 20;
size_t CVEC_VOID_START_SZ = 20;

#define CVEC_I_ALLOCATOR(x) ((x+1) * 2)
#define CVEC_D_ALLOCATOR(x) ((x+1) * 2)
#define CVEC_STR_ALLOCATOR(x) ((x+1) * 2)
#define CVEC_VOID_ALLOCATOR(x) ((x+1) * 2)
</pre>
The allocator macros are used in all functions that increase the size by 1.
In others (constructors, insert_array, reserve) CVEC_X_START_SZ is the amount
extra allocated.

Note that the (x+1) portion allows you to use the non-void vectors
without calling any of the init functions first *if* you zero them out.  This
means size, capacity, and a are 0/NULL which is valid because realloc acts like
malloc when given a NULL pointer.  With cvector_void you still have to set
elem_size, and optionally elem_free/elem_init. See the zero_init_x_test()'s
in cvector_tests.c for example of that use.

There are also 2 templates, one for basic types and one for types that contain
dynamically allocated memory and you might want a free and/or init function.
In other words the first template is based off cvector_i and the second is based
off of cvector_void, so look at the corresponding documentation for behavior.

There are 2 ways to use/create your own cvector types.  The easiest way is to use
the macros defined in cvector_macro.h which are also included in the all-in-one header
cvector.h.  You can see how to use them in cvector_tests.c:

	#define RESIZE(a) (((a)+1)*2)

	CVEC_NEW_DECLS(short)
	CVEC_NEW_DECLS2(f_struct)

	CVEC_NEW_DEFS(short, RESIZE)
	CVEC_NEW_DEFS2(f_struct, RESIZE)

The RESIZE macro has to be defined before using the macros for now, serving the
same purpose as the regular allocator macros above.  Obviously the DECL macros
declare type and prototypes while the DEFS define them.  Using the macros for
user made types is much easier than the files because you can call the macro
right in the header where you define the type instead of having to include the
type in the generated file.  Basically 1 step rather than 2-3 and no extra files
needed.

The other way, and the only way in previous versions of CVector, is to generate
your own files from the template files which are located in cvector_template.h
and cvector_template2.h.

To generate your own cvector files for a type just run:

	python3 generate_code.py yourtype

which will generate the results for both templates so just delete the one
you don't want.

cvector_short and cvector_f_struct are examples of the generated files.  While I
now test the macros instead of the files, it's the same code, and you can still
see how I used to test them.

\section des_notes Design Notes
With the exception of CVEC_STRDUP calls in cvector_str, memory allocations are checked and asserted.
I decided that the likelihood of individual string allocations failing is low enough that it wasn't
worth the slowdown or extra code.  However, the equivalent calls to elem_init in vector_void and
generated vector_TYPEs are checked/asserted (since they're more likely to be large enough to possibly
fail).  If not in debug mode (ie NDEBUG is defined) 0 is returned on allocation failure.

For functions that take a ret parameter (ie pop and replace functions for str, void, and type 2
template/macro generated vectors), NULL is a valid option if you don't care to get the value.
I didn't want to force users to make a temporary variable just to catch something they weren't
going to use.

No other error checking is performed.  If you pass bad parameters (ie NULL for the vector
pointer, or end < start for the range functions), bad things will happen.
This is consistent with my belief that it is the caller's responsibility to pass valid arguments
and library code shouldn't be larger/uglier/slower for everyone just to pretty print errors.  This
is also consistent with the C standard library where, for the most part, passing invalid parameters
results in undefined behavior (see section 4.1.6 in C89, 7.1.4 in C99 and C11).

The back functions simply return the address of size - 1.  This is fine even if your size is zero
for the use of <= back_i(myvec) since the beginning of the array will already be > back.  If I were
to return NULL in the case of size 0, you'd just exchange a possible size check before the call for
a possible NULL check after the call.  I choose this way because it doesn't add an if check
to the function so it's smaller/faster, I think the <= use case is more likely, and it's easier
and more normal to know when your vector is empty than to remember to check for NULL after the fact.

The insert functions (insert_i and insert_array_i for example) do allow you to insert at the end.
The CVEC_MEMMOVE inside the functions will simply move 0 bytes if you pass the current size as the index.
C99 and C11 guarrantee this behavior in the standard (and thus C++ does as well).  Though I wrote
this library to be compliant with C89, which does not guarrantee this behavior, I think
it's safe to assume they'd use the same implementation since it doesn't contradict C89 and it
just makes sense.

\section Building
I use premake generated makefiles which are
included in the build subdirectory.  However, if you modified premake4.lua
the command to regenerate them is `premake4 gmake`.  cd into the build
directory and run `make` or `make config=release`. I have not tried it on
windows though it should work (well I'm not sure about CUnit ...).

There is no output of any kind, no errors or warnings.

It has been relatively well tested using CUnit tests which all pass.
I've also run it under valgrind and there are no memory leaks.

<pre>
valgrind --leak-check=full -v ./cvector
==116175==
==116175== HEAP SUMMARY:
==116175==     in use at exit: 0 bytes in 0 blocks
==116175==   total heap usage: 10,612 allocs, 10,612 frees, 1,151,748 bytes allocated
==116175==
==116175== All heap blocks were freed -- no leaks are possible
==116175==
==116175== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
</pre>

You can probably get Cunit from your package manager but
if you want to get the most up to date version of CUnit go here:

http://cunit.sourceforge.net/index.html
http://sourceforge.net/projects/cunit/

I'm using version 2.1-3.

\section Usage
To actually use the library just copy the appropriate c/h file pair(s) to your project
or just use cvector.h.  To get a good idea of how to use the library and see it in
action and how it should behave, look at cvector_tests.c

\section LICENSE
CVector is licensed under the MIT License.

Copyright (c) 2011-2022 Robert Winkler

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
 *
 *
 */


text:
package edu.clemson.resolve.jetbrains.psi;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;

public interface ResConventionsClause extends ResCompositeElement {

  @Nullable
  ResEntailsClause getEntailsClause();

  @Nullable
  ResMathExp getMathExp();

  @Nullable
  PsiElement getSemicolon();

  @NotNull
  PsiElement getConventions();

}


text:
import gym
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
from gym import wrappers
from datetime import datetime
from q_learning import FeatureTransformer
from q_learning_bins import plot_running_avg

class SGDRegressor:
  def __init__(self, D):
    self.w = np.random.randn(D) / np.sqrt(D)

  def partial_fit(self, x, y, e, lr=1e-1):
    self.w += lr*(y - x.dot(self.w))*e

  def predict(self, X):
    X = np.array(X)
    return X.dot(self.w)

# Holds one SGDRegressor for each action
class Model:
  def __init__(self, env, feature_transformer):
    self.env = env
    self.models = []
    self.feature_transformer = feature_transformer

    sample_feature = feature_transformer.transform( [env.reset()] )
    D = sample_feature.shape[1]

    for i in range(env.action_space.n):
      # model = SGDRegressor(learning_rate="constant")
      # model.partial_fit(feature_transformer.transform( [env.reset()] ), [0])
      model = SGDRegressor(D)
      self.models.append(model)

    self.eligibilities = np.zeros((env.action_space.n, D))

  def reset(self):
    self.eligibilities = np.zeros_like(self.eligibilities)

  def predict(self, s):
    X = self.feature_transformer.transform([s])
    result = np.stack([m.predict(X) for m in self.models]).T
    return result

  def update(self, s, a, G, gamma, lambda_):
    X = self.feature_transformer.transform([s])
    # assert(len(X.shape) == 2)

    # slower
    # for action in range(self.env.action_space.n):
    #   if action != a:
    #     self.eligibilities[action] *= gamma*lambda_
    #   else:
    #     self.eligibilities[a] = grad + gamma*lambda_*self.eligibilities[a]

    self.eligibilities *= gamma*lambda_
    self.eligibilities[a] += X[0]
    self.models[a].partial_fit(X[0], G, self.eligibilities[a])

  def sample_action(self, s, eps):
    if np.random.random() < eps:
      return self.env.action_space.sample()
    else:
      return np.argmax(self.predict(s))

# returns a list of states_and_rewards, and the total reward
def play_one(model, env, eps, gamma, lambda_):
  observation = env.reset()
  done = False
  totalreward = 0
  states_actions_rewards = []
  iters = 0
  model.reset()
  while not done and iters < 1000000:
    action = model.sample_action(observation, eps)
    prev_observation = observation
    observation, reward, done, info = env.step(action)

    if done:
      reward = -300

    # update the model
    next = model.predict(observation)
    assert(next.shape == (1, env.action_space.n))
    G = reward + gamma*np.max(next[0])
    model.update(prev_observation, action, G, gamma, lambda_)

    states_actions_rewards.append((prev_observation, action, reward))

    if reward == 1: # if we changed the reward to -200
      totalreward += reward

    iters += 1

    # if iters > 0 and iters % 1000 == 0:
    #   print(iters)
    # if done:
    #   print "finished in < 1000 steps!"

  return states_actions_rewards, totalreward

if __name__ == '__main__':
  env = gym.make('CartPole-v0')
  ft = FeatureTransformer(env)
  model = Model(env, ft)
  gamma = 0.999
  lambda_ = 0.7

  if 'monitor' in sys.argv:
    filename = os.path.basename(__file__).split('.')[0]
    monitor_dir = './' + filename + '_' + str(datetime.now())
    env = wrappers.Monitor(env, monitor_dir)

  N = 500
  totalrewards = np.empty(N)
  # costs = np.empty(N)
  for n in range(N):
    # eps = 1.0/(0.1*n+1)
    # eps = 0.1*(0.97**n)
    eps = 1.0/np.sqrt(n+1)
    # eps = 0.1
    states_actions_rewards, totalreward = play_one(model, env, eps, gamma, lambda_)
    totalrewards[n] = totalreward
    if n % 100 == 0:
      print("episode:", n, "total reward:", totalreward, "eps:", eps, "avg reward (last 100):", totalrewards[max(0, n-100):(n+1)].mean())
  print("avg reward for last 100 episodes:", totalrewards[-100:].mean())
  print("total steps:", totalrewards.sum())

  plt.plot(totalrewards)
  plt.title("Rewards")
  plt.show()

  plot_running_avg(totalrewards)


text:
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;

namespace QrF.Core.ComFr.Repositories
{
    public interface IOnModelCreating
    {
        void OnModelCreating(ModelBuilder modelBuilder);
    }
}


text:
var proveedorView = function (strClase) {
    this.clase = strClase;
};
proveedorView.prototype = new view('proveedor');
proveedorView.prototype.getClassNameProveedor = function () {
    return this.getClassName() + "Vista";
};
var oProveedorView = new proveedorView('proveedor');

proveedorView.prototype.loadButtons = function (id) {

    var botonera = "";
    botonera += '

';
    botonera += '';
    botonera += '';
    botonera += '';
    botonera += '

';
    return botonera;

}
proveedorView.prototype.loadFormValues = function (valores, campos) {
//                    $('#proveedor_form #titulo').val(valores['titulo']);
//                    $('#proveedor_form #contenido').val(valores['contenido']);
//                    $('#proveedor_form #alta').val(valores['alta']);
//                    $('#proveedor_form #cambio').val(valores['cambio']);
//                    $('#proveedor_form #hits').val(valores['hits']);
//                    $('#proveedor_form #id_usuario').val(valores['id_usuario']);
//                    $('#proveedor_form #etiquetas').val(valores['etiquetas']);
//                    $('#proveedor_form #publicado').val(valores['publicado']);
//                    $('#proveedor_form #portada').val(valores['portada']);
    this.doFillForm(valores, campos);
};

proveedorView.prototype.getFormValues = function () {
    var valores = [];
//                    valores['titulo'] = $('#proveedor_form #titulo');
//                    valores['contenido'] = $('#proveedor_form #contenido');
//                    valores['alta'] = $('#proveedor_form #alta');
//                    valores['cambio'] = $('#proveedor_form #cambio');
//                    valores['hits'] = $('#proveedor_form #hits');
//                    valores['id_usuario'] = $('#proveedor_form #id_usuario');
//                    valores['etiquetas'] = $('#proveedor_form #etiquetas');
//                    valores['publicado'] = $('#proveedor_form #publicado');
//                    valores['portada'] = $('#proveedor_form #portada');

    var disabled = $('#proveedorForm').find(':input:disabled').removeAttr('disabled');
    valores = $('#proveedorForm').serializeObject();
    disabled.attr('disabled', 'disabled');
    return valores;
};

proveedorView.prototype.doEventsLoading = function () {
    var thisObject = this;

};

proveedorView.prototype.okValidation = function (f) {
    $('#proveedorForm').on('success.form.bv', f);
};


text:
<?php
abstract class BasicEnum {
    private static $constCacheArray = NULL;

    private static function getConstants() {
        if (self::$constCacheArray == NULL) {
            self::$constCacheArray = [];
        }
        $calledClass = get_called_class();
        if (!array_key_exists($calledClass, self::$constCacheArray)) {
            $reflect = new ReflectionClass($calledClass);
            self::$constCacheArray[$calledClass] = $reflect->getConstants();
        }
        return self::$constCacheArray[$calledClass];
    }

    public static function isValidName($name, $strict = false) {
        $constants = self::getConstants();

        if ($strict) {
            return array_key_exists($name, $constants);
        }

        $keys = array_map('strtolower', array_keys($constants));
        return in_array(strtolower($name), $keys);
    }

    public static function isValidValue($value, $strict = true) {
        $values = array_values(self::getConstants());
        return in_array($value, $values, $strict);
    }
}
?>


text:
package nz.govt.doc.t1m.services.dataSheet.litterBeach;

import nz.govt.doc.t1m.domain.dataSheet.litterBeach.LitterBeachEntity;
import nz.govt.doc.t1m.domain.response.PagedResponse;
import nz.govt.doc.t1m.domain.response.Response;
import nz.govt.doc.t1m.services.dataSheet.litterBeach.LitterBeachCriteria;
import nz.govt.doc.t1m.services.dataSheet.litterBeach.LitterBeachRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.transaction.Transactional;

/**
 */
@Component
public class LitterBeachService {

    @Autowired
    protected LitterBeachRepository litterBeachRepository;

    public PagedResponse<LitterBeachEntity> findByCriteria(LitterBeachCriteria criteria) {
        return litterBeachRepository.findByCriteria(criteria);
    }

    public Response<LitterBeachEntity> findLitterBeachById(Integer litterBeachId) {
        return new Response<>(litterBeachRepository.findOne(litterBeachId));
    }

//    @Transactional
//    public Response<LitterBeachEntity> saveLitterBeach(LitterBeachEntity litterBeachEntity) {
//        LitterBeachEntity litterBeachResponse = litterBeachRepository.save(litterBeachEntity);
//        Response res = new Response<>(litterBeachResponse);
//        return res;
//    }

    @Transactional
    public LitterBeachEntity saveLitterBeach(LitterBeachEntity litterBeachEntity) {
        LitterBeachEntity litterBeachResponse = litterBeachRepository.save(litterBeachEntity);
        return litterBeachResponse;
    }

    public void removeLitterBeach(Integer litterBeachId) {
        litterBeachRepository.delete(litterBeachId);
    }
}


text:
package org.more.webui.web;
import java.util.Map.Entry;
import java.util.Set;
import org.more.util.ClassUtils;
import org.more.webui.component.UIComponent;
import org.more.webui.component.support.UICom;
import org.more.webui.context.BeanManager;
import org.more.webui.context.FacesConfig;
import org.more.webui.context.FacesContext;
import org.more.webui.lifestyle.Lifecycle;
import org.more.webui.lifestyle.PhaseListener;
import org.more.webui.lifestyle.UIPhaseListener;
import org.more.webui.render.RenderKit;
import freemarker.template.TemplateModelException;
/**
 *
 * @version : 2012-6-27
 * @author 赵永春 (zyc@byshell.org)
 */
class FactoryBuild {
    private ClassUtils   classUtil    = null; //扫描的类包路径
    private WebUIFactory webUIFactory = null;
    public FactoryBuild(WebUIFactory webUIFactory) {
        this.webUIFactory = webUIFactory;
    }
    private void setup(FacesConfig config) {
        if (this.classUtil != null)
            return;
        String scanPackageStr = config.getScanPackages();
        String[] scanPackages = scanPackageStr.split(",");
        this.classUtil = ClassUtils.newInstance(scanPackages);
    }
    /**生成{@link FacesContext} */
    public FacesContext buildFacesContext(FacesConfig config) throws TemplateModelException {
        this.setup(config);
        FacesContext fc = this.webUIFactory.createFacesContext(config);
        RenderKit kit = new RenderKit();
        kit.initKit(fc);
        fc.addRenderKit("default", kit);
        Set<Class<?>> classSet = null;
        //A.扫描注解添加组建。
        classSet = classUtil.getClassSet(UICom.class);
        for (Class<?> type : classSet) {
            UICom uicom = type.getAnnotation(UICom.class);
            if (UIComponent.class.isAssignableFrom(type) == false)
                throw new ClassCastException(type + " to UIComponent");
            else {
                /*添加组建*/
                fc.addComponentType(uicom.tagName(), type);
                /*为组建添加默认标签渲染器,因为只有用于渲染器的组建才会生效。*/
                fc.getRenderKit("default").addRenderType(uicom.tagName(), uicom.renderType());
            }
        }
        //C.向全局Freemarker服务中注册标签
        kit = fc.getRenderKit("default");
        for (Entry<String, Object> tagEntry : kit.getTags().entrySet())
            fc.getFreemarker().setSharedVariable(tagEntry.getKey(), tagEntry.getValue());
        return fc;
    }
    /**生成{@link Lifecycle}*/
    public Lifecycle buildLifestyle(FacesConfig config, FacesContext context) {
        this.setup(config);
        /*创建生命周期对象*/
        Lifecycle lifestyle = this.webUIFactory.createLifestyle(config, context);
        /*添加生命周期监听器*/
        BeanManager beanManager = context.getBeanContext();
        Set<Class<?>> classSet = classUtil.getClassSet(UIPhaseListener.class);
        for (Class type : classSet)
            if (PhaseListener.class.isAssignableFrom(type) == false)
                throw new ClassCastException(type + " to PhaseListener");
            else {
                PhaseListener listener = beanManager.getBean(type);
                lifestyle.addPhaseListener(listener);
            }
        return lifestyle;
    }
}


text:
#include <X11/Xlib.h>
#include <freerdp/kbd/kbd.h>

#include "xf_input.h"

void xf_input_synchronize_event(rdpInput* input, uint32 flags)
{
	printf("Client sent a synchronize event (flags:0x%X)\n", flags);
}

void xf_input_keyboard_event(rdpInput* input, uint16 flags, uint16 code)
{
	unsigned int keycode;
	boolean extended = false;
	xfPeerContext* xfp = (xfPeerContext*) input->context;
	xfInfo* xfi = xfp->info;

	if (flags & KBD_FLAGS_EXTENDED)
		extended = true;

	keycode = freerdp_kbd_get_keycode_by_scancode(code, extended);

	if (keycode != 0)
	{
#ifdef WITH_XTEST
		pthread_mutex_lock(&(xfp->mutex));

		if (flags & KBD_FLAGS_DOWN)
			XTestFakeKeyEvent(xfi->display, keycode, True, 0);
		else if (flags & KBD_FLAGS_RELEASE)
			XTestFakeKeyEvent(xfi->display, keycode, False, 0);

		pthread_mutex_unlock(&(xfp->mutex));
#endif
	}
}

void xf_input_unicode_keyboard_event(rdpInput* input, uint16 flags, uint16 code)
{
	printf("Client sent a unicode keyboard event (flags:0x%X code:0x%X)\n", flags, code);
}

void xf_input_mouse_event(rdpInput* input, uint16 flags, uint16 x, uint16 y)
{
	int button = 0;
	boolean down = false;
	xfPeerContext* xfp = (xfPeerContext*) input->context;
	xfInfo* xfi = xfp->info;

	pthread_mutex_lock(&(xfp->mutex));
#ifdef WITH_XTEST

	if (flags & PTR_FLAGS_WHEEL)
	{
		boolean negative = false;

		if (flags & PTR_FLAGS_WHEEL_NEGATIVE)
			negative = true;

		button = (negative) ? 5 : 4;

		XTestFakeButtonEvent(xfi->display, button, True, 0);
		XTestFakeButtonEvent(xfi->display, button, False, 0);
	}
	else
	{
		if (flags & PTR_FLAGS_MOVE)
			XTestFakeMotionEvent(xfi->display, 0, x, y, 0);

		if (flags & PTR_FLAGS_BUTTON1)
			button = 1;
		else if (flags & PTR_FLAGS_BUTTON2)
			button = 3;
		else if (flags & PTR_FLAGS_BUTTON3)
			button = 2;

		if (flags & PTR_FLAGS_DOWN)
			down = true;

		if (button != 0)
			XTestFakeButtonEvent(xfi->display, button, down, 0);
	}
#endif
	pthread_mutex_unlock(&(xfp->mutex));
}

void xf_input_extended_mouse_event(rdpInput* input, uint16 flags, uint16 x, uint16 y)
{
	xfPeerContext* xfp = (xfPeerContext*) input->context;
	xfInfo* xfi = xfp->info;

	pthread_mutex_lock(&(xfp->mutex));
#ifdef WITH_XTEST
	XTestFakeMotionEvent(xfi->display, 0, x, y, CurrentTime);
#endif
	pthread_mutex_unlock(&(xfp->mutex));
}

void xf_input_register_callbacks(rdpInput* input)
{
	input->SynchronizeEvent = xf_input_synchronize_event;
	input->KeyboardEvent = xf_input_keyboard_event;
	input->UnicodeKeyboardEvent = xf_input_unicode_keyboard_event;
	input->MouseEvent = xf_input_mouse_event;
	input->ExtendedMouseEvent = xf_input_extended_mouse_event;
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Some Florida Lichens (New York) 35 (1990)

#### Original name
Anisomeridium tuckeri R.C. Harris

### Remarks
null