text:
/********************************************************************************/
/*										*/
/*			     	TPM Proxy for Unix				*/
/*			     Written by Stefan Berger				*/
/*		       IBM Thomas J. Watson Research Center			*/
/*	      $Id: tpm_proxy.c 4702 2013-01-03 21:26:29Z kgoldman $ 		*/
/*										*/
/* (c) Copyright IBM Corporation 2006, 2010.					*/
/*										*/
/* All rights reserved.								*/
/* 										*/
/* Redistribution and use in source and binary forms, with or without		*/
/* modification, are permitted provided that the following conditions are	*/
/* met:										*/
/* 										*/
/* Redistributions of source code must retain the above copyright notice,	*/
/* this list of conditions and the following disclaimer.			*/
/* 										*/
/* Redistributions in binary form must reproduce the above copyright		*/
/* notice, this list of conditions and the following disclaimer in the		*/
/* documentation and/or other materials provided with the distribution.		*/
/* 										*/
/* Neither the names of the IBM Corporation nor the names of its		*/
/* contributors may be used to endorse or promote products derived from		*/
/* this software without specific prior written permission.			*/
/* 										*/
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS		*/
/* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT		*/
/* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR	*/
/* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT		*/
/* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,	*/
/* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT		*/
/* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,	*/
/* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY	*/
/* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT		*/
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE	*/
/* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.		*/
/********************************************************************************/

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <unistd.h>
#include <sys/ioctl.h>
//#include "tpm_driver.h"
#include "tpm_proxy.h"

#define DEFAULT_PORT 6543	/* default TCPIP server port */
#define LOAD32(buffer,offset)         ( ntohl(*(uint32_t *)&buffer[offset]) )

void usage(const char * name)
{
    printf("Usage: %s [--port|-p <n>] [--nodaemon|-n] [--verbose|-v] [--log|-l]\n"
	   "          [--device|-d <device name>]\n"
	   "\n"
	   "options can be one of the following:\n"
	   "--port <n>  : The port number the server is supposed to be running on.\n"
	   "\tDefault - 6543\n"
	   "--nodaemon  : Prevents the process from going into the background.\n"
	   "\tDefault - in background\n"
	   "--log <filename> : Log transactions into given file.\n"
	   "--verbose   : verbose mode\n"
	   "--device    : TPM device; default is /dev/tpm0\n"
	   "\n"
	   "The device (e.g., /dev/tpm0) must be read/write by the user running the proxy\n"
	   );
}

int detach(void);
int startup(short port, FILE * logfile, int, const char *);
void signal_handler(int signum);

FILE * logfile = NULL;

int main(int argc, char ** argv)
{
    /* default command line parameters */
    int daemon = TRUE;		/* TRUE, process in background */
    int verbose = FALSE;	/* FALSE, no verbose tracing */
    int port = DEFAULT_PORT;	/* server port */
    char * logfilename = NULL;	/* no logging */
    char * tpm_device = "/dev/tpm0";

    int rc = 0;
    int i = 1;

    setvbuf(stdout, 0, _IONBF, 0);      /* output may be going through pipe */

    while ((i < argc) && (rc == 0)) {
	if (0 == strcmp("-h",argv[i])) {
	    usage(argv[0]);
	    rc = 1;
	}
	else if (0 == strcmp("--port",argv[i]) ||
		 0 == strcmp("-p", argv[i])) {
	    i++;
	    if (i < argc) {
		port = atoi(argv[i]);
		if (port < 0 || port > 0xffff) {
		    printf("Error, bad port specified: %d\n", port);
		    rc = 1;
		}
	    } else {
		usage(argv[0]);
		rc = 1;
	    }
	}
	else if (0 == strcmp("--nodaemon",argv[i]) ||
		 0 == strcmp("-n",argv[i])) {
	    daemon = FALSE;
	}
	else if (0 == strcmp("--verbose",argv[i]) ||
		 0 == strcmp("-v",argv[i])) {
	    verbose = TRUE;
	}
	else if (0 == strcmp("--logfile",argv[i]) ||
		 0 == strcmp("-l",argv[i])) {
	    i++;
	    if (i < argc) {
		logfilename = (char *)strdup(argv[i]);
	    } else {
		usage(argv[0]);
		rc = 1;
	    }
	}
	else if (0 == strcmp("--device",argv[i]) ||
		 0 == strcmp("-d",argv[i])) {
	    i++;
	    if (i < argc) {
		tpm_device = (char *)strdup(argv[i]);
	    } else {
		usage(argv[0]);
		rc = 1;
	    }
	}
	else {
	    printf("Error, illegal command line parameter: %s\n", argv[i]);
	    rc = 1;
	}
	i++;
    }
    /* if command line arguments are OK */
    if (rc == 0) {
	if (NULL != logfilename) {
	    logfile = fopen(logfilename,"w");
	    if (NULL != logfile) {
		setvbuf(logfile, 0, _IONBF, 0);      /* output may be going through pipe */
		printf("Logging transactions in %s\n", logfilename);
	    } else {
		printf("Could not open logfile %s\n", logfilename);
		rc = 1;
	    }
	}
    }
    if (rc == 0) {
	int res = 1;
	if (TRUE == daemon) {
	    printf("Will become a daemon.\n");
	    res = detach();
	}
	if ( 0 != res) {
	    signal(SIGKILL, signal_handler);
	    signal(SIGINT , signal_handler);
	    signal(SIGTERM, signal_handler);
	    signal(SIGQUIT, signal_handler);
	    signal(SIGABRT, signal_handler);
	}
    }
    if (rc == 0) {
	printf("Starting server on port = %d\n", port);
	rc = startup(port, logfile, verbose, tpm_device);
    }
    return rc;
}

void signal_handler(int signum)
{
    if (NULL != logfile) {
	fclose(logfile);
	logfile = NULL;
    }
    exit(0);
}

void logging (FILE * logfile, const char * prefix, const unsigned char * buffer, int len)
{
    if (NULL != logfile) {
	int i = 0;
	if (NULL != prefix) {
	    fwrite(prefix, 1, strlen(prefix), logfile);
	}
	fwrite("  ", 1, 2, logfile);
	while (i < len) {
	    char buf[100];
	    sprintf(buf,"%02x ",(unsigned char)buffer[i]);
	    fwrite(buf, 1, strlen(buf), logfile);
	    i++;
	    if (0 == (i & 15) && (i < len)) {
		fwrite("\n", 1, 1, logfile);
		memset(buf, 0x20, sizeof(buf));
		if (NULL != prefix) {
		    fwrite(buf, 1, strlen(prefix) + 2, logfile);
		}
	    }
	}
	fwrite("\n",1,1,logfile);
    }
}

int startup(short port, FILE * logfile, int verbose, const char *tpm_device)
{
    int 	rc = 0;
    int         irc = 0;
    char 	messageBuffer[4096];
    size_t 	messageLength;
    int 	server_sockfd = -1;
    struct sockaddr_in server_addr;
    /* command/response buffer */
    unsigned char buffer[4096]; 	/* 4096 is the Linux driver buffer size */
    int len = 0;
    int paramSize;
    int tpm_fd = 0;

    /* create a socket */
    if (rc == 0) {
	server_sockfd  = socket(AF_INET,
				SOCK_STREAM,
				0);
        if (server_sockfd == -1) {
	    messageLength = sprintf(messageBuffer,
				    "Error creating server socket() %d %s\n",
				    errno, strerror(errno));
	    if (NULL != logfile) {
		logging(logfile, messageBuffer, NULL, 0);
	    }
	    logging(stdout, messageBuffer, NULL, 0);
            rc = 1;
        }
    }
    if (rc == 0) {
	memset(&server_addr, 0x0, sizeof(server_addr));
	server_addr.sin_family              = AF_INET;
	server_addr.sin_port                = htons(port);
	server_addr.sin_addr.s_addr         = htonl(INADDR_ANY);
	int on = 1;
        /* Set SO_REUSEADDR before calling bind() for servers that bind to a fixed port number. */
	irc = setsockopt(server_sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
        if (irc != 0) {
	    messageLength = sprintf(messageBuffer,
				    "Error, server setsockopt() %d %s\n",
				    errno, strerror(errno));
	    if (NULL != logfile) {
		logging(logfile, messageBuffer, NULL, 0);
	    }
	    logging(stdout, messageBuffer, NULL, 0);
            rc = 1;
        }
    }
    /* bind the (local) server port name to the socket */
    if (rc == 0) {
	irc = bind(server_sockfd,
		   (struct sockaddr *)&server_addr,
		   sizeof(server_addr));
        if (irc != 0) {
	    messageLength = sprintf(messageBuffer,
				    "Error, server bind() %d %s\n",
				    errno, strerror(errno));
	    if (NULL != logfile) {
		logging(logfile, messageBuffer, NULL, 0);
	    }
	    logging(stdout, messageBuffer, NULL, 0);
            rc = 1;
        }
    }
    /* listen on the server socket connection for an incoming command */
    if (rc == 0) {
	irc = listen(server_sockfd, 1);
	if (irc != 0) {
	    messageLength = sprintf(messageBuffer,
				    "Error, server listen() %d %s\n",
				    errno, strerror(errno));
	    if (NULL != logfile) {
		logging(logfile, messageBuffer, NULL, 0);
	    }
	    logging(stdout, messageBuffer, NULL, 0);
	    rc = 1;
	}
    }
    /* this is the inner command/response loop */
    while (rc == 0) {
	struct sockaddr_in cli_addr;
	socklen_t cli_len = sizeof(cli_addr);
	int client_sockfd;
	/* block until connection from client */
	if (rc == 0) {
	    client_sockfd = accept(server_sockfd,
				   (struct sockaddr *)&cli_addr,
				   &cli_len);
	    if (client_sockfd < 0) {
		messageLength = sprintf(messageBuffer,
					"Error, accept() %d %s\n",
					errno, strerror(errno));
		if (NULL != logfile) {
		    logging(logfile, messageBuffer, NULL, 0);
		}
		logging(stdout, messageBuffer, NULL, 0);
		rc = 1;
	    }
	}
	if (rc == 0) {
	    /* read the TPM command from the client application */
	    len = read(client_sockfd, buffer, sizeof(buffer));
	    /* socket read error */
	    if (len <= 0) {
		messageLength = sprintf(messageBuffer,
					"Error, socket read() %d %s\n",
					errno, strerror(errno));
		if (NULL != logfile) {
		    logging(logfile, messageBuffer, NULL, 0);
		}
		logging(stdout, messageBuffer, NULL, 0);
		rc = 1;
	    }
	}
	/* open the HW TPM */
	if (rc == 0) {
	    tpm_fd = open(tpm_device,O_RDWR);
	    if (tpm_fd <= 0) {
		messageLength = sprintf(messageBuffer,
					"Error opening %s\n",tpm_device);
		if (NULL != logfile) {
		    logging(logfile, messageBuffer, NULL, 0);
		}
		logging(stdout, messageBuffer, NULL, 0);
		rc = 1;
	    }
	}
	if (rc == 0) {
	    fcntl(tpm_fd, O_RDONLY|O_NONBLOCK);
	    /* log the TPM request */
	    if (NULL != logfile) {
		logging(logfile," REQUEST:", buffer, len);
	    }
	    if (verbose) {
		logging(stdout," REQUEST:", buffer, len);
	    }
	    /* write the command to the TPM */
	    len = write(tpm_fd, buffer, len);
	    if (len < 0) {
		messageLength = sprintf(messageBuffer,
					"Error, TPM write() %d %s\n",
					errno, strerror(errno));
		if (NULL != logfile) {
		    logging(logfile, messageBuffer, NULL, 0);
		}
		logging(stdout, messageBuffer, NULL, 0);
		rc = 1;
	    }
	}
	if (rc == 0) {
	    /* read the response from the TPM */
	    len = read(tpm_fd, buffer, sizeof(buffer));
	    if (len <= 0) {
		messageLength = sprintf(messageBuffer,
					"Error, TPM read() %d %s\n",
					errno, strerror(errno));
		if (NULL != logfile) {
		    logging(logfile, messageBuffer, NULL, 0);
		}
		logging(stdout, messageBuffer, NULL, 0);
		rc = 1;
	    }
	}
	if (rc == 0) {
	    /* log the TPM response */
	    if (NULL != logfile) {
		logging(logfile,"RESPONSE:", buffer, len);
	    }
	    if (verbose) {
		logging(stdout, "RESPONSE:", buffer, len);
	    }
	    /* get the response paramSize from the buffer at offset 2 */
	    paramSize = LOAD32(buffer, 2);
	    /* sanity check on response packet */
	    if (len != paramSize) {
		messageLength = sprintf(messageBuffer,
					"Error, Malformed TPM response, read %u paramSize %u\n",
					len, paramSize);
		if (NULL != logfile) {
		    logging(logfile, messageBuffer, NULL, 0);
		}
		logging(stdout, messageBuffer, NULL, 0);
		rc = 1;
	    }
	}
	if (rc == 0) {
	    /* This is likely obsolete.  There was a TPM at one time that returned something unusual
	       for the TPM_Quote command.  This work around ensures that the first byte is always
	       zero.  */
	    buffer[0] = 0;
	    /* close the TPM */
	    close(tpm_fd);
	    /* write the response to the socket client */
	    len = write(client_sockfd, buffer, len);
	    if (len <= 0) {
		messageLength = sprintf(messageBuffer,
					"Error, socket write() %d %s\n",
					errno, strerror(errno));
		if (NULL != logfile) {
		    logging(logfile, messageBuffer, NULL, 0);
		}
		logging(stdout, messageBuffer, NULL, 0);
		rc = 1;
	    }
	}
	close(client_sockfd);
    }
    close(server_sockfd);
    return rc;
}

int detach(void)
{
    signal(SIGHUP , SIG_IGN);
    if (getppid() != 1) {
	int childpid;
	signal(SIGTTOU, SIG_IGN);
	signal(SIGTTIN, SIG_IGN);
	signal(SIGTSTP, SIG_IGN);
	if ( (childpid = fork()) > 0) {
	    return 0;
	}
	setsid();
    }
    close(0);
    //	close(1);
    //	close(2);
    umask(0);
    chdir("/");
    return 1;
}


text:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

?>

<?php echo $this->lang->line('title_topic_update'); ?>

    <?php
    $attributes = array("class" => "form-group",
        "id" => "updateTopicForm",
        "name" => "updateTopicForm");
    echo form_open('Topic/update_topic', $attributes);
    ?>
    <?php
    if($error == true) {
        echo "
" . $this->lang->line('update_topic_form_err') . "
";
    }
    ?>

<?php echo $this->lang->line('update_title_topic'); ?>

            <input maxlength="<?=TOPIC_MAX_LENGTH?>" type="text" name="title" class="form-control" id="title" value="<?php echo $title_topic; ?>">

    <input type="hidden" name="id" id="id" value="<?php echo $id; ?>">

            <a id="btn_cancel" class="btn btn-default" href="<?=base_url('/topic')?>"><?=$this->lang->line('btn_cancel')?>
            <?php
                echo form_submit('save', $this->lang->line('save'), 'class="btn btn-primary"');
            ?>

    <?php echo form_close(); ?>

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace Microsoft.CodeAnalysis.CSharp
{
    internal sealed class BindStatementBinder : Binder
    {
        private readonly BindStatementSyntax _syntax;
        public List<ExpressionStatementSyntax> AddToRegistryStatements { get; set; } = new List<ExpressionStatementSyntax>();
        public List<StatementSyntax> CleanupRegistryStatements { get; set; } = new List<StatementSyntax>();

        public BindStatementBinder(Binder enclosing, BindStatementSyntax syntax)
            : base(enclosing)
        {
            _syntax = syntax;
        }

        internal override BoundStatement BindBindStatementParts(DiagnosticBag diagnostics, Binder originalBinder)
        {
            BoundStatement boundBody = originalBinder.BindPossibleEmbeddedStatement(_syntax.Statement, diagnostics);
            bool hasErrors = false;
            var l1 = new List<string>();
            var l2 = new List<string>();

            foreach (var bindSection in _syntax.Bindings)
            {
                IdentifierNameSyntax i = bindSection.InterfaceIdentifier as IdentifierNameSyntax;
                IdentifierNameSyntax c = bindSection.ClassIdentifier as IdentifierNameSyntax;

                if (i == null)
                {
                    hasErrors = true;
                    Error(diagnostics, ErrorCode.ERR_InterfaceMemberNotFound, _syntax, bindSection.InterfaceIdentifier);

                }
                else l1.Add(i.Identifier.ValueText);

                if (c == null)
                {
                    hasErrors = true;
                    Error(diagnostics, ErrorCode.ERR_ClassTypeExpected, _syntax, bindSection.ClassIdentifier);

                }
                else l2.Add(c.Identifier.ValueText);
            }

            var x = l1.ToImmutableArray<string>();
            var y = l2.ToImmutableArray<string>();

            List<IOperation> binds = new List<IOperation>();

            foreach (var es in AddToRegistryStatements)
                binds.Add(originalBinder.BindExpressionStatement(es, diagnostics));

            List<IOperation> unbinds = new List<IOperation>();

            foreach (var es in CleanupRegistryStatements)
                unbinds.Add(originalBinder.BindStatement(es, diagnostics));

            return new BoundBindStatement(_syntax, x, y, binds.ToImmutableArray(), unbinds.ToImmutableArray(), boundBody, hasErrors);

        }
    }
}


text:
Pendulum swinging on a spring.
## Instructions
### Controls
- <kbd>Esc</kbd> - exit the program.
- Mouse wheel - zoom in/out.
- Left mouse button - drag the bob.
## Screenshots
[![3. Oscillation screenshot 1](../screenshots/3.-Oscillation-screenshot-1.png)](../screenshots/3.-Oscillation-screenshot-1.png)
---
[![3. Oscillation screenshot 2](../screenshots/3.-Oscillation-screenshot-2.png)](../screenshots/3.-Oscillation-screenshot-2.png)


text:
(a, *rest, b) = range(5)

(             : punctuation.parenthesis.begin.python, source.python
a             : source.python
,             : punctuation.separator.element.python, source.python
              : source.python
*             : keyword.operator.arithmetic.python, source.python
rest          : source.python
,             : punctuation.separator.element.python, source.python
              : source.python
b             : source.python
)             : punctuation.parenthesis.end.python, source.python
              : source.python
=             : keyword.operator.assignment.python, source.python
              : source.python
range         : meta.function-call.python, source.python, support.function.builtin.python
(             : meta.function-call.python, punctuation.definition.arguments.begin.python, source.python
5             : constant.numeric.dec.python, meta.function-call.arguments.python, meta.function-call.python, source.python
)             : meta.function-call.python, punctuation.definition.arguments.end.python, source.python


text:
"""LSTM SSD Meta-architecture definition.

General tensorflow implementation of convolutional Multibox/SSD detection
models with LSTM states, for use on video data. This implementation supports
both regular LSTM-SSD and interleaved LSTM-SSD framework.

See https://arxiv.org/abs/1711.06368 and https://arxiv.org/abs/1903.10172
for details.
"""
import abc
import re
import tensorflow as tf

from object_detection.core import box_list_ops
from object_detection.core import matcher
from object_detection.core import standard_fields as fields
from object_detection.meta_architectures import ssd_meta_arch
from object_detection.utils import ops
from object_detection.utils import shape_utils

slim = tf.contrib.slim

class LSTMSSDMetaArch(ssd_meta_arch.SSDMetaArch):
  """LSTM Meta-architecture definition."""

  def __init__(self,
               is_training,
               anchor_generator,
               box_predictor,
               box_coder,
               feature_extractor,
               encode_background_as_zeros,
               image_resizer_fn,
               non_max_suppression_fn,
               score_conversion_fn,
               classification_loss,
               localization_loss,
               classification_loss_weight,
               localization_loss_weight,
               normalize_loss_by_num_matches,
               hard_example_miner,
               unroll_length,
               target_assigner_instance,
               add_summaries=True):
    super(LSTMSSDMetaArch, self).__init__(
        is_training=is_training,
        anchor_generator=anchor_generator,
        box_predictor=box_predictor,
        box_coder=box_coder,
        feature_extractor=feature_extractor,
        encode_background_as_zeros=encode_background_as_zeros,
        image_resizer_fn=image_resizer_fn,
        non_max_suppression_fn=non_max_suppression_fn,
        score_conversion_fn=score_conversion_fn,
        classification_loss=classification_loss,
        localization_loss=localization_loss,
        classification_loss_weight=classification_loss_weight,
        localization_loss_weight=localization_loss_weight,
        normalize_loss_by_num_matches=normalize_loss_by_num_matches,
        hard_example_miner=hard_example_miner,
        target_assigner_instance=target_assigner_instance,
        add_summaries=add_summaries)
    self._unroll_length = unroll_length

  @property
  def unroll_length(self):
    return self._unroll_length

  @unroll_length.setter
  def unroll_length(self, unroll_length):
    self._unroll_length = unroll_length

  def predict(self, preprocessed_inputs, true_image_shapes, states=None,
              state_name='lstm_state', feature_scope=None):
    with tf.variable_scope(self._extract_features_scope,
                           values=[preprocessed_inputs], reuse=tf.AUTO_REUSE):
      feature_maps = self._feature_extractor.extract_features(
          preprocessed_inputs, states, state_name,
          unroll_length=self._unroll_length, scope=feature_scope)
    feature_map_spatial_dims = self._get_feature_map_spatial_dims(feature_maps)
    image_shape = shape_utils.combined_static_and_dynamic_shape(
        preprocessed_inputs)
    self._batch_size = preprocessed_inputs.shape[0].value / self._unroll_length
    self._states = states
    anchors = self._anchor_generator.generate(feature_map_spatial_dims,
                                              im_height=image_shape[1],
                                              im_width=image_shape[2])
    with tf.variable_scope('MultipleGridAnchorGenerator', reuse=tf.AUTO_REUSE):
      self._anchors = box_list_ops.concatenate(anchors)
    prediction_dict = self._box_predictor.predict(
        feature_maps, self._anchor_generator.num_anchors_per_location())
    with tf.variable_scope('Loss', reuse=tf.AUTO_REUSE):
      box_encodings = tf.concat(prediction_dict['box_encodings'], axis=1)
      if box_encodings.shape.ndims == 4 and box_encodings.shape[2] == 1:
        box_encodings = tf.squeeze(box_encodings, axis=2)
      class_predictions_with_background = tf.concat(
          prediction_dict['class_predictions_with_background'], axis=1)
    predictions_dict = {
        'preprocessed_inputs': preprocessed_inputs,
        'box_encodings': box_encodings,
        'class_predictions_with_background': class_predictions_with_background,
        'feature_maps': feature_maps,
        'anchors': self._anchors.get(),
        'states_and_outputs': self._feature_extractor.states_and_outputs,
    }
    # In cases such as exporting the model, the states is always zero. Thus the
    # step should be ignored.
    if states is not None:
      predictions_dict['step'] = self._feature_extractor.step
    return predictions_dict

  def loss(self, prediction_dict, true_image_shapes, scope=None):
    """Computes scalar loss tensors with respect to provided groundtruth.

    Calling this function requires that groundtruth tensors have been
    provided via the provide_groundtruth function.

    Args:
      prediction_dict: a dictionary holding prediction tensors with
        1) box_encodings: 3-D float tensor of shape [batch_size, num_anchors,
          box_code_dimension] containing predicted boxes.
        2) class_predictions_with_background: 3-D float tensor of shape
          [batch_size, num_anchors, num_classes+1] containing class predictions
          (logits) for each of the anchors. Note that this tensor *includes*
          background class predictions.
      true_image_shapes: int32 tensor of shape [batch, 3] where each row is
        of the form [height, width, channels] indicating the shapes
        of true images in the resized images, as resized images can be padded
        with zeros.
      scope: Optional scope name.

    Returns:
      a dictionary mapping loss keys (`localization_loss` and
        `classification_loss`) to scalar tensors representing corresponding loss
        values.
    """
    with tf.name_scope(scope, 'Loss', prediction_dict.values()):
      keypoints = None
      if self.groundtruth_has_field(fields.BoxListFields.keypoints):
        keypoints = self.groundtruth_lists(fields.BoxListFields.keypoints)
      weights = None
      if self.groundtruth_has_field(fields.BoxListFields.weights):
        weights = self.groundtruth_lists(fields.BoxListFields.weights)
      (batch_cls_targets, batch_cls_weights, batch_reg_targets,
       batch_reg_weights, batch_match) = self._assign_targets(
           self.groundtruth_lists(fields.BoxListFields.boxes),
           self.groundtruth_lists(fields.BoxListFields.classes),
           keypoints, weights)
      match_list = [matcher.Match(match) for match in tf.unstack(batch_match)]
      if self._add_summaries:
        self._summarize_target_assignment(
            self.groundtruth_lists(fields.BoxListFields.boxes), match_list)
      location_losses = self._localization_loss(
          prediction_dict['box_encodings'],
          batch_reg_targets,
          ignore_nan_targets=True,
          weights=batch_reg_weights)
      cls_losses = ops.reduce_sum_trailing_dimensions(
          self._classification_loss(
              prediction_dict['class_predictions_with_background'],
              batch_cls_targets,
              weights=batch_cls_weights),
          ndims=2)

      if self._hard_example_miner:
        (loc_loss_list, cls_loss_list) = self._apply_hard_mining(
            location_losses, cls_losses, prediction_dict, match_list)
        localization_loss = tf.reduce_sum(tf.stack(loc_loss_list))
        classification_loss = tf.reduce_sum(tf.stack(cls_loss_list))

        if self._add_summaries:
          self._hard_example_miner.summarize()
      else:
        if self._add_summaries:
          class_ids = tf.argmax(batch_cls_targets, axis=2)
          flattened_class_ids = tf.reshape(class_ids, [-1])
          flattened_classification_losses = tf.reshape(cls_losses, [-1])
          self._summarize_anchor_classification_loss(
              flattened_class_ids, flattened_classification_losses)
        localization_loss = tf.reduce_sum(location_losses)
        classification_loss = tf.reduce_sum(cls_losses)

      # Optionally normalize by number of positive matches
      normalizer = tf.constant(1.0, dtype=tf.float32)
      if self._normalize_loss_by_num_matches:
        normalizer = tf.maximum(tf.to_float(tf.reduce_sum(batch_reg_weights)),
                                1.0)

      with tf.name_scope('localization_loss'):
        localization_loss_normalizer = normalizer
        if self._normalize_loc_loss_by_codesize:
          localization_loss_normalizer *= self._box_coder.code_size
        localization_loss = ((self._localization_loss_weight / (
            localization_loss_normalizer)) * localization_loss)
      with tf.name_scope('classification_loss'):
        classification_loss = ((self._classification_loss_weight / normalizer) *
                               classification_loss)

      loss_dict = {
          'localization_loss': localization_loss,
          'classification_loss': classification_loss
      }
    return loss_dict

  def restore_map(self, fine_tune_checkpoint_type='lstm'):
    """Returns a map of variables to load from a foreign checkpoint.

    See parent class for details.

    Args:
      fine_tune_checkpoint_type: the type of checkpoint to restore from, either
        SSD/LSTM detection checkpoint (with compatible variable names)
        classification checkpoint for initialization prior to training.
        Available options: `classification`, `detection`, `interleaved`,
        and `lstm`.

    Returns:
      A dict mapping variable names (to load from a checkpoint) to variables in
      the model graph.
    Raises:
      ValueError: if fine_tune_checkpoint_type is not among
      `classification`/`detection`/`interleaved`/`lstm`.
    """
    if fine_tune_checkpoint_type not in [
        'classification', 'detection', 'interleaved', 'lstm',
        'interleaved_pretrain'
    ]:
      raise ValueError('Not supported fine_tune_checkpoint_type: {}'.format(
          fine_tune_checkpoint_type))

    self._restored_networks += 1
    base_network_scope = self.get_base_network_scope()
    if base_network_scope:
      scope_to_replace = '{0}_{1}'.format(base_network_scope,
                                          self._restored_networks)

    interleaved_model = False
    for variable in tf.global_variables():
      if scope_to_replace in variable.op.name:
        interleaved_model = True
        break

    variables_to_restore = {}
    for variable in tf.global_variables():
      var_name = variable.op.name
      if 'global_step' in var_name:
        continue

      # Remove FeatureExtractor prefix for classification checkpoints.
      if (fine_tune_checkpoint_type == 'classification' or
          fine_tune_checkpoint_type == 'interleaved_pretrain'):
        var_name = (
            re.split('^' + self._extract_features_scope + '/', var_name)[-1])

      # When loading from single frame detection checkpoints, we need to
      # remap FeatureMaps variable names.
      if ('FeatureMaps' in var_name and
          fine_tune_checkpoint_type == 'detection'):
        var_name = var_name.replace('FeatureMaps',
                                    self.get_base_network_scope())

      # Load interleaved checkpoint specifically.
      if interleaved_model:  # Interleaved LSTD.
        if 'interleaved' in fine_tune_checkpoint_type:
          variables_to_restore[var_name] = variable
        else:
          # Restore non-base layers from the first checkpoint only.
          if self._restored_networks == 1:
            if base_network_scope + '_' not in var_name:  # LSTM and FeatureMap
              variables_to_restore[var_name] = variable
          if scope_to_replace in var_name:
            var_name = var_name.replace(scope_to_replace, base_network_scope)
            variables_to_restore[var_name] = variable
      else:
        # Restore from the first model of interleaved checkpoints
        if 'interleaved' in fine_tune_checkpoint_type:
          var_name = var_name.replace(self.get_base_network_scope(),
                                      self.get_base_network_scope() + '_1', 1)

        variables_to_restore[var_name] = variable

    return variables_to_restore

  def get_base_network_scope(self):
    """Returns the variable scope of the base network.

    Returns:
      The variable scope of the feature extractor base network, e.g. MobilenetV1
    """
    return self._feature_extractor.get_base_network_scope()

class LSTMSSDFeatureExtractor(ssd_meta_arch.SSDFeatureExtractor):
  """LSTM SSD Meta-architecture Feature Extractor definition."""

  __metaclass__ = abc.ABCMeta

  @property
  def clip_state(self):
    return self._clip_state

  @clip_state.setter
  def clip_state(self, clip_state):
    self._clip_state = clip_state

  @property
  def depth_multipliers(self):
    return self._depth_multipliers

  @depth_multipliers.setter
  def depth_multipliers(self, depth_multipliers):
    self._depth_multipliers = depth_multipliers

  @property
  def lstm_state_depth(self):
    return self._lstm_state_depth

  @lstm_state_depth.setter
  def lstm_state_depth(self, lstm_state_depth):
    self._lstm_state_depth = lstm_state_depth

  @property
  def is_quantized(self):
    return self._is_quantized

  @is_quantized.setter
  def is_quantized(self, is_quantized):
    self._is_quantized = is_quantized

  @property
  def interleaved(self):
    return False

  @property
  def states_and_outputs(self):
    """LSTM states and outputs.

    This variable includes both LSTM states {C_t} and outputs {h_t}.

    Returns:
      states_and_outputs: A list of 4-D float tensors, including the lstm state
        and output at each timestep.
    """
    return self._states_out

  @property
  def step(self):
    return self._step

  def preprocess(self, resized_inputs):
    """SSD preprocessing.

    Maps pixel values to the range [-1, 1].

    Args:
      resized_inputs: a [batch, height, width, channels] float tensor
        representing a batch of images.

    Returns:
      preprocessed_inputs: a [batch, height, width, channels] float tensor
        representing a batch of images.
    """
    return (2.0 / 255.0) * resized_inputs - 1.0

  def get_base_network_scope(self):
    """Returns the variable scope of the base network.

    Returns:
      The variable scope of the base network, e.g. MobilenetV1
    """
    return self._base_network_scope

  @abc.abstractmethod
  def create_lstm_cell(self, batch_size, output_size, state_saver, state_name):
    """Create the LSTM cell, and initialize state if necessary.

    Args:
      batch_size: input batch size.
      output_size: output size of the lstm cell, [width, height].
      state_saver: a state saver object with methods `state` and `save_state`.
      state_name: string, the name to use with the state_saver.
    Returns:
      lstm_cell: the lstm cell unit.
      init_state: initial state representations.
      step: the step
    """
    pass

class LSTMSSDInterleavedFeatureExtractor(LSTMSSDFeatureExtractor):
  """LSTM SSD Meta-architecture Interleaved Feature Extractor definition."""

  __metaclass__ = abc.ABCMeta

  @property
  def pre_bottleneck(self):
    return self._pre_bottleneck

  @pre_bottleneck.setter
  def pre_bottleneck(self, pre_bottleneck):
    self._pre_bottleneck = pre_bottleneck

  @property
  def low_res(self):
    return self._low_res

  @low_res.setter
  def low_res(self, low_res):
    self._low_res = low_res

  @property
  def interleaved(self):
    return True

  @property
  def interleave_method(self):
    return self._interleave_method

  @interleave_method.setter
  def interleave_method(self, interleave_method):
    self._interleave_method = interleave_method

  @abc.abstractmethod
  def extract_base_features_large(self, preprocessed_inputs):
    """Extract the large base model features.

    Args:
      preprocessed_inputs: preprocessed input images of shape:
        [batch, width, height, depth].

    Returns:
      net: the last feature map created from the base feature extractor.
      end_points: a dictionary of feature maps created.
    """
    pass

  @abc.abstractmethod
  def extract_base_features_small(self, preprocessed_inputs):
    """Extract the small base model features.

    Args:
      preprocessed_inputs: preprocessed input images of shape:
        [batch, width, height, depth].

    Returns:
      net: the last feature map created from the base feature extractor.
      end_points: a dictionary of feature maps created.
    """
    pass


text:
package com.github.zbiljic.shiro.cache.infinispan;

import org.apache.shiro.cache.Cache;
import org.apache.shiro.util.LifecycleUtils;

import org.infinispan.commons.api.BasicCacheContainer;
import org.infinispan.manager.DefaultCacheManager;
import org.infinispan.manager.EmbeddedCacheManager;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

/**
 * @author Nemanja Zbiljic
 */
public class InfinispanManagerTest {

    private InfinispanCacheManager cacheManager;

    @Before
    public void setUp() {
        cacheManager = new InfinispanCacheManager();
    }

    @After
    public void tearDown() {
        LifecycleUtils.destroy(cacheManager);
    }

    @Test
    public void testCacheManagerCreationDuringInit() {
        EmbeddedCacheManager infinispanCacheManager = cacheManager.getCacheManager();
        assertNull(infinispanCacheManager);
        cacheManager.init();
        //now assert that an internal CacheManager has been created:
        infinispanCacheManager = cacheManager.getCacheManager();
        assertNotNull(infinispanCacheManager);
    }

    @Test
    public void testLazyCacheManagerCreationWithoutCallingInit() {
        EmbeddedCacheManager infinispanCacheManager = cacheManager.getCacheManager();
        assertNull(infinispanCacheManager);

        //don't call init here - the Infinispan EmbeddedCacheManager should be lazily created
        //because of the default Shiro infinispan.xml file in the classpath.  Just acquire a cache:
        Cache<String, String> cache = cacheManager.getCache("test");

        //now assert that an internal EmbeddedCacheManager has been created:
        infinispanCacheManager = cacheManager.getCacheManager();
        assertNotNull(infinispanCacheManager);

        assertNotNull(cache);
        cache.put("hello", "world");
        String value = cache.get("hello");
        assertNotNull(value);
        assertEquals(value, "world");
    }

    @Test
    public void testProvideCustomCacheManager() throws Exception {
        // create custom cache manager
        EmbeddedCacheManager customCacheManager = new DefaultCacheManager(cacheManager.getCacheManagerConfigFileInputStream());
        assertNotNull(customCacheManager);

        BasicCacheContainer infinispanCacheContainer = cacheManager.getCacheContainer();
        assertNull(infinispanCacheContainer);

        cacheManager.setCacheContainer(customCacheManager);

        //now assert that an internal EmbeddedCacheManager has been created:
        infinispanCacheContainer = cacheManager.getCacheContainer();
        assertNotNull(infinispanCacheContainer);

        // Acquire the cache:
        Cache<String, String> cache = cacheManager.getCache("test");

        assertNotNull(cache);
        cache.put("hello", "world");
        String value = cache.get("hello");
        assertNotNull(value);
        assertEquals(value, "world");

        // Don't forget to stop the custom cache manager
        customCacheManager.stop();
    }
}


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>
  <parent>
    <groupId>io.leopard</groupId>
    <artifactId>leopard-test-parent</artifactId>
    <version>0.9.13-SNAPSHOT</version>
  </parent>
  <artifactId>leopard-mocknb</artifactId>
  <name>Leopard MockNB</name>
</project>


text:
    <button class="btn btn-danger pull-right" ng-click="deleteCurrentQuery()">hledat jiného</button>

                <fb-user-picture type="normal" id="aUserLQ.doc.fb.id"/>

uživatel {{ aUserLQ.doc.fb.first_name + ' ' + aUserLQ.doc.fb.last_name }}<input type="text" ng-model="userSearch" ng-hide="aUserLQ.doc.fb">

                    Email:

                    Datum nar.:

                    Registrace:

                    Hlasoval celkem:

                    Hlasů pro:

                    Hlasů proti:

                    Privilege level:
                        <input type="number" ng-model="aUserLQ.doc.privilige_level" ng-blur="saveUser()">

jeho hlasy:

                <zn-vote ng-repeat="vote in votesLQ.docs" vote="vote"></zn-vote>

jeho návrhy:

                <zn-novel ng-repeat="novel in novelsLQ.docs" novel="novel"></zn-novel>

jeho komentáře:

            <zn-comment ng-repeat="comment in commentsLQ.docs" comment="comment"></zn-comment>


text:
package org.team2642.robot.commands.DriveTrain;

import org.team2642.robot.Robot;

import edu.wpi.first.wpilibj.command.Command;

/**
 *
 */
public class DriveInput extends Command {

    private double rotation;
    private double move;

	public DriveInput(double moveValue, double angleValue) {
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
    	requires(Robot.driveTrain);
    	rotation = angleValue;
    	move = moveValue;
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
    	Robot.driveTrain.arcadeDrive(move, rotation);
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return false;
    }

    // Called once after isFinished returns true
    protected void end() {
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}


text:
using System;
using System.Collections;
using Yaapii.Atoms.Scalar;

namespace Yaapii.Atoms.Enumerable
{
    /// <summary>
    /// Tells if an enumerable has exactly the the specified item count.
    /// </summary>
    public sealed class ExactAmount : ScalarEnvelope<bool>
    {
        /// <summary>
        /// Tells if an enumerable has exactly the the specified item count.
        /// </summary>
        public ExactAmount(int amount, IEnumerable source) : base(() =>
        {
            if (amount < 0)
            {
                throw new ArgumentException($"A positive number is needed for amount (amount: {amount}).");
            }
            var current = 0;
            var enumerator = source.GetEnumerator();
            while (enumerator.MoveNext() && current <= amount)
            {
                current++;
            }
            return current == amount;
        })
        { }
    }
}


text:
require "test_helper"

module Folio
  class LeadTest < ActiveSupport::TestCase
    # test "the truth" do
    #   assert true
    # end
  end
end

# == Schema Information
#
# Table name: folio_leads
#
#  id              :integer          not null, primary key
#  email           :string
#  phone           :string
#  note            :text
#  created_at      :datetime         not null
#  updated_at      :datetime         not null
#  name            :string
#  url             :string
#  additional_data :json
#  state           :string           default("submitted")
#  visit_id        :integer
#
# Indexes
#
#  index_folio_leads_on_visit_id  (visit_id)
#


text:
/******************************************************************************
*
* File name:   Conversions.h
* Subsystem:   Platform Services
* Description: Utility conversion methods.
*
* Name                 Date       Release
* -------------------- ---------- ---------------------------------------------
* Stephen Horton       01/01/2014 Initial release
*
*
******************************************************************************/

//-----------------------------------------------------------------------------
// System include files, includes 3rd party libraries.
//-----------------------------------------------------------------------------

#include <cstring>

//-----------------------------------------------------------------------------
// Component includes, includes elements of our system.
//-----------------------------------------------------------------------------

#include "Conversions.h"

//-----------------------------------------------------------------------------
// Static Declarations.
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// PUBLIC methods.
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// Method Type: STATIC
// Description:
// Design:
//-----------------------------------------------------------------------------
string Conversions::integer2Base(unsigned long value, const unsigned int base)
{
   string output(""); // accumulate digits for output, initialized clear
   unsigned int digit; // value of single digit
   char c; // output value for digit

   // short-cut
   if ( value == 0 )
   {
      return "0";
   }//end if

   while ( value > 0 )
   {
      // get least significant digit
      digit = (unsigned int) value % base;
      // remove digit
      value = value / base;

      // get output character for digit
      if (digit > 9 ) // check for non numeric
      {
         c = 'A' + digit - 10;
      }//end if
      else
      {
         c = '0' + digit;
      }//end else
      // add char representing digit
      output = c + output;
   }//end while
   return output;
}//end integer2Base

//-----------------------------------------------------------------------------
// Method Type: STATIC
// Description:
// Design:
//-----------------------------------------------------------------------------
int Conversions::binary2Decimal(char* binaryString)
{
   int b, k, m, n;
   int len, sum = 0;

   len = strlen(binaryString) - 1;
   for(k = 0; k <= len; k++)
   {
      // character to numeric value
      n = (binaryString[k] - '0');
      if ((n > 1) || (n < 0))
      {
         //ERROR! BINARY has only 1 and 0!
         return (0);
      }//end if
      for(b = 1, m = len; m > k; m--)
      {
         // 1 2 4 8 16 32 64 ... place-values, reversed here
         b *= 2;
      }//end for
      // sum it up
      sum = sum + n * b;
      // uncomment to show the way this works
      //printf("%d*%d + ",n,b);
   }//end for
   return(sum);
}//end binary2Decimal

//-----------------------------------------------------------------------------
// Method Type: Virtual Destructor
// Description:
// Design:
//-----------------------------------------------------------------------------
Conversions::~Conversions()
{
}//end virtual destructor

//-----------------------------------------------------------------------------
// PROTECTED methods.
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// PRIVATE methods.
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// Nested Class Definitions:
//-----------------------------------------------------------------------------


text:
Modeling with MODELLER and Clustering with ptraj
================================================

Requirements
============

- Python 2.7 (because of the ``argparse`` module, will try to change that in the
  future)
- BioPython
- Matplotlib

This is the setup I use to create protein models using MODELLER and cluster
them using ptraj. I've played around a lot with this, so please don't panic if
something doesn't work. If anything goes awry, shoot me a mail at <runiq at
archlinux dot us>.

Most of the script logic is in the ``runall.sh`` files which you'll have to run
after setting the appropriate parameters in them. If someone wants me to, I can
instead write some parsing logic for config files (I haven't felt the need to
since I'm intimately familiar with these scripts, but your mileage may vary, of
course).

Licensed under 2-clause BSD; see ``LICENSE.txt``.

1. General Procedure
====================

1.  Create decoys using MODELLER (``modeling`` directory)
2.  Either:
    a)  Set a critical RMSD distance threshold, or
    b)  Set the desired cluster number
         (``find-correct-clustering-number`` directory)
3.  Cluster using ptraj
4.  Either
    a)  Use the decoy which is closest to the consensus structure of the decoy
        (``<cluster_name>.rep.c<cluster_number>``), or
    b)  Minimize the actual consensus structure using MODELLER
        (``clustering/create_cluster_representative.py``)
5.  Choose the best cluster

2. Procedure in Detail
======================

2.1. Modeling (``modeling`` Directory)
--------------------------------------

Ingredients

- Alignment (``alignment.pir``)
- Modeling script (``modeller-parallel.py``)

Start with ``./runall.sh``. This will call ``modeller-parallel.py`` with the
parameters you set beforehand. If you want to adjust these or want to see which
parameters exist at all, call ``./modeller-parallel.py --help``.

2.2. Finding the Correct Cluster Number (``find-correct-clustering-number`` Directory)
--------------------------------------------------------------------------------------

There are two criteria you can use for clustering:

a)  Tell ptraj to put all clusters *up to a certain distance threshold* into a
    cluster. This is what MODELLER does with its ``cluster_xyz()`` function. It's
    probably sufficient in most basic cases, and 1–1.5Å are a good threshold.

    If you use this method, better err on the side of too small instead of too
    large when deciding on a distance threshold. Otherwise you risk including
    bad, non-native structures in your cluster (false positives).

b)  Set the cluster number yourself. This requires you to find a "good" cluster
    number. [Shao.etal2007]_ argue that the "best" cluster number is the one
    with the highest *information content*. The scripts supplied in this package
    allow you to choose your target cluster number based on the four metrics
    suggested in that paper; the critical distance, DBI, pSF, and SSR/SST ratio.

    A short blurb on how to interpret the metrics:
     -  Number of decoys in cluster should be high (according to [Shortle.etal1998]_)
     -  DBI should be low
     -  pSF should be high
     - SSR/SST should have an "elbow"

Ingredients for 2b):
-  ptraj for clustering
-  script to plot metrics (``plot_clustering_metrics.py``)
-  ``clustering_run.py`` and ``newick.py``
-  matplotlib library (should be installed on your computer)

Just run ``./runall.sh`` in the ``find-correct-cluster-number`` directory. If everything works, you should now have a file called ``clustering_metrics.png`` in which the metrics are plotted vs. the cluster number.

2.3. Clustering (``clustering`` Directory)
------------------------------------------

When you've found a good cluster number or a good RMSD threshold, you can
finally start your actual clustering run! Yay!

Ingredients:
-  Script that removes micromanaging (``cluster.sh``)
-  Script that supplies ptraj with the actual clustering command
   (``ptraj_cluster``)
-  script to create a representative structure from decoy PDBs and a ptraj
   clustering log file

All this can be done automatically by running ``./runall.sh`` in the
``clustering`` directory. After reading the ptraj paper [Shao.etal2007]_, I've
decided on the AverageLinkage algorithm (see ``ptraj_cluster`` script).

2.4. (Optional) Creating a Minimized Consensus Structure
--------------------------------------------------------

By default, ptraj can output the representative structure in PDB format if you
tell it to. This is the decoy in a cluster that is closest to the cluster's
consensus structure. If you actually want to work with the consensus structure,
however, note that it is not biologically relevant, so you'll have to minimize
before working with it. The ``create_clustering_representatives.py`` script
does that for you.

2.5. Choosing the Best Cluster
------------------------------

Your methods are probably as good as mine, but here are the guidelines I
generally follow:

 -  Good clusters are probably better according to [Shortle.etal1998]_
 -  Evaluate all representative structures with the SwissModel-Server
    (http://swissmodel.expasy.org/workspace/index.php?func=tools_structureassessment1)
 -  Compare DOPE scores of models (script ``assess_dope.py``)
 -  Create Ramachandran plots and compare outliers using RAMPAGE
    (http://mordred.bioc.cam.ac.uk/~rapper/rampage.php)

3. Ptraj
========

3.1. General Stuff
------------------

If you want to read about ptraj in general and its ``cluster`` command in particular, I heartily recommend the AMBERTools manual. You basically do the following:

1.  Read in your PDB files with the ``trajin`` command (p. 109 in AMBERTools manual)

    I've done this programmatically in the scripts because I'd have to write
    2000 lines of ``trajin "../modeling/<model_name>.B9999????.pdb"``, which is
    not an activity I'd describe as "intellectually stimulating". (See
    ``find-correct-cluster-number/runall.sh``, the line below "Create ptraj
    input file" on how this is done.)

2. Cluster using the ``cluster`` command (p. 117 in AMBERTools manual).  If you
   look at the ``find-correct-cluster-number/runall.sh`` script, you'll notice
   I first cluster until all decoys are merged into a single cluster and then
   perform a number of additional clustering runs (up to a cluster number of
   20). This is done because the results of the first ``cluster`` command are
   cached in a file called ``ClusterMerging.txt``.  This file can be used with
   the ``ReadMerge`` pseudo algorithm when doing subsequent clustering runs,
   which we do, because we'd like to obtain the metrics in the clustering log
   file, thank you very much. The cache file can also be used to reconstruct
   the merge tree for the AverageLinkage algorithm, but the script for that is
   not yet fit for public consumption.

3. Call ptraj: ``ptraj <one_of_your_modeller_generated_pdb_files.pdb> ptraj_script``

   Unfortunately, the ``cluster`` command is not (yet) parallelized, so the first clustering run might take a while.

3.2. Ptraj Masks
----------------

When using ptraj, you can choose which atoms should be taken into consideration
when calculating the RMSD between your decoys. This is done using *masks*. By
default, I choose all main-chain atoms of residues 7–216 for superpositioning
and RMSD calculations. The corresponding mask looks like this:

    :7-216@N,CA,C,O

If you want to change the group of atoms to perform the clustering on (and you most certainly will), look no further than p. 267 of the AMBERTools manual.

References
==========

..  [Shao.etal2007] Shao, J.; Tanner, S. W.; Thompson, N. & Cheatham, T. E.
    **Clustering Molecular Dynamics Trajectories: 1. Characterizing the Performance
    of Different Clustering Algorithms** *Journal of Chemical Theory and
    Computation*, 2007, 3, 2312-2334.

..  [Shortle.etal1998] Shortle, D.; Simons, K. T. & Baker, D. **Clustering of
    low-energy conformations near the native structures of small proteins.** *Proc
    Natl Acad Sci USA*, Department of Biochemistry, University of Washington School
    of Medicine, Seattle, WA 98195, USA., 1998, 95, 11158-11162


text:
test repository for CEN 3031

// added some comment
// added more comments


text: THE PLAYERS


text:
package java_quaero.ast;

import java.io.*;

import java_cup.runtime.*;
import java_quaero.parser.*;

/** Implementación del lenguaje con la siguiente gramática:

```
lines : lines line ;
lines : line ;

line : nums \n ;

nums : nums , num ;
nums : num ;

num : [0-9]+ ;
```

 */
public class Main {

	public static void showTokens(String input) throws Exception {
		Lexer lexer = Parser.makeLexer(input);
		Symbol token = lexer.next_token();
		while (token.sym != Tokens.EOF) {
			System.out.println(token.sym +": "+ token.value);
			token = lexer.next_token();
		}
		System.out.println("FIN");
	}

	public static void showParse(String input) throws Exception {
		Parser parser = Parser.makeParser(input);
		Symbol result = parser.parse();
		System.out.println(result.sym +": "+ result.value);
	}

	public static void main(String[] args) throws Exception {
		BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder source = new StringBuilder();
		for (String line = stdIn.readLine(); line != null; line = stdIn.readLine()) {
			if (line.length() > 0) {
				source.append(line).append("\n");
			} else { // Empty line means input ends.
				//showTokens(source.toString());
				showParse(source.toString());
			}
		}
	}

}


text:
package nl.ica.ddoa.dda.springexample;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class StartApp {
	public static void main(String[] args) {
		ApplicationContext factory = new ClassPathXmlApplicationContext  ("application-context.xml");
		Moppenvrager vrager = (Moppenvrager)factory.getBean("moppenvrager");
		vrager.vraagAanIemandEenMop();
	}

}


text:
""" @file Parallelization.py
Defines the CrombieTools.Parallelization package.
@author Daniel Abercrombie <dabercro@mit.edu>

@package CrombieTools.Parallelization
Package for running processes in parallel.
Submodule of CrombieTools.
"""

import os
from multiprocessing import Process, Queue
from Queue import Empty
from time import time

"""Number of processors from environment"""
DefaultNumProcs = int(os.environ.get('CrombieNLocalProcs') or 1)

def RunParallel(objectToRun, functionName, parametersLists, procs=DefaultNumProcs, printing=True, doCopy=True):
    """ Starts parallel processes.

    @param objectToRun is an objectToRun that can be copied and run independently when
    it's own Copy() function is called.
    @param functionName is the str name of the function that will be run in multiple instances.
    @param parametersLists is a list of lists. Each sublist contains the parameters for the functionName.
    @param procs is the maximum number of processors that will be used.
    @param printing tells which files are about to be processed and how long they took if True.
    @param doCopy copies the object that the function should be run over
    """

    totStartTime = time()

    if 'Copy' not in dir(objectToRun) and doCopy:
        print('Object not copyable.')
        print('Exiting...')
        exit(1)

    if not functionName in dir(objectToRun):
        print('You gave an invalid function name!')
        exit(1)

    if 'GetOutDirectory' in dir(objectToRun):
        outDir = str(objectToRun.GetOutDirectory())
        if not os.path.exists(outDir):
            os.makedirs(outDir)

    def runOnQueue(inQueue):
        running = True

        objCopy = objectToRun.Copy() if doCopy else objectToRun
        functionToRun = getattr(objCopy, functionName)

        while running:
            try:
                parameters = inQueue.get(True, 1)
                if printing:
                    print('About to process ' + str(parameters))

                startTime = time()
                functionToRun(*parameters)
                if printing:
                    print('Finished ' + str(parameters) + ' ... Elapsed time: ' + str(time() - startTime) + ' seconds')

            except Empty:
                if printing:
                    print('Worker finished...')

                running = False

        if (doCopy):
            del objCopy

    if printing:
        print('About to use {0} processers.'.format(procs))

    theQueue     = Queue()
    theProcesses = []

    for parameters in parametersLists:
        theQueue.put(parameters)

    for worker in range(procs):
        aProcess = Process(target=runOnQueue, args=(theQueue,))
        aProcess.start()
        theProcesses.append(aProcess)

    for aProccess in theProcesses:
        aProccess.join()

    print('All done!\n')
    print('Total jobs: ' + str(len(parametersLists)))
    print('Total time: ' + str(time() - totStartTime) + ' seconds\n')

def RunOnDirectory(objectToRun, procs=DefaultNumProcs, printing=True):
    """ Runs an objectToRun over a directory.

    @param objectToRun has GetInDirectory() and RunOnFile() function members.
    This function then runs the objectToRun's over all the files in that directory.
    @param procs is the maximum number of processes to start.
    @param printing tells which files are about to be processed and how long they took if True.
    """
    theFiles = []

    if not 'GetInDirectory' in dir(objectToRun):
        print('##########################################')
        print('# Missing GetInDirectory in this object. #')
        print('##########################################')
        exit(1)

    inDir = str(objectToRun.GetInDirectory())

    outDir = None
    if 'GetOutDirectory' in dir(objectToRun):
        outDir = str(objectToRun.GetOutDirectory())

    def GetSize(name):
        return os.path.getsize(inDir + name)

    for inFileName in sorted(os.listdir(inDir), key=GetSize, reverse=True):
        if inFileName.endswith('.root'):
            if outDir and os.path.exists(outDir + inFileName):
                print(outDir + inFileName + ' already exists !!! ... Skipping.')
                continue
            theFiles.append([inFileName])

    RunParallel(objectToRun, 'RunOnFile', theFiles, procs, printing)


text:
Baasic AngularJS Membership library provides access to [Baasic REST API](http://dev.baasic.com/api/reference/home) membership end-points.

## Dependencies

Baasic AngularJS Membership library has the following dependencies:

* [Baasic Core AngularJS SDK](../../../baasic-sdk-angularjs-core)

## Usage

This section will describe how to add the Baasic AngularJS Membership library to your project.

### Adding the Library to your Project

Please add the _Baasic Membership_ include after the _Baasic Angular Core_ include:

```html
<script src='/js/baasic-angular-core-1.0.0.min.js'></script>
<script src='/js/baasic-angular-membership-1.0.0.min.js'></script>
```

### Initialization

To be able to use the library you will need to add the Baasic (_baasic.membership_) dependency to your AngularJS module.

```javascript
angular.module('my-module', ["baasic.api", "baasic.membership"])
```

## Build Process

1. Install [NodeJs](http://nodejs.org/download/)
2. Open Shell/Command Prompt in the Baasic AngularJS folder
3. Run `npm install`
4. Install gulp globally: `npm install -g gulp`
5. Run `gulp`

## Contributing

* [Pull requests are always welcome](../../../baasic-sdk-angularjs-membership/pulls)
* Please [report](../../../baasic-sdk-angularjs-membership/issues) any issues you might  have found
* Help us write the documentation
* Create interesting apps using SDK
* Looking for something else to do? Get in <u>touch</u> ...


text:
using System;
using System.Diagnostics.Contracts;

namespace PartitionableArray
{
	public class PartitionableArray<T>
	{
		#region Internal

		private struct Element
		{
			public T value;

			// Keep track of this element in the list of interesting elements
			public bool interesting;
			public int prev;
			public int next;
		}

		private Element[] arr;

		private PartitionFn test;

		private int sentinel
		{
			get { return arr.Length - 1; }
		}

		[ContractInvariantMethod]
		private void invariant()
		{
			Contract.Invariant(test != null);
			Contract.Invariant(arr != null);
			Contract.Invariant(arr.Length >= 1);
			Contract.Invariant(sentinel == arr.Length - 1);
			Contract.Invariant(Length == arr.Length - 1);
			Contract.Invariant(0 <= count);
			Contract.Invariant(count <= Length);
			Contract.Invariant(count < arr.Length);
			Contract.Invariant(Count == count);
		}

		// Remove an interesting element from the list
		private void remove(int index)
		{
			Contract.Requires<IndexOutOfRangeException>(
				0 <= index && index < Length,
				"The index must be within the bounds of the array.");
			Contract.Requires(arr[index].interesting == true);
			Contract.Requires(test(arr[index].value) == true);
			Contract.Ensures(arr[index].interesting == false);
			Contract.Ensures(Contract.OldValue(Count) - 1 == Count);

			count--;
			arr[index].interesting = false;

			arr[arr[index].prev].next = arr[index].next;
			arr[arr[index].next].prev = arr[index].prev;
		}

		// Add an interesting element to the list
		private void add(int index)
		{
			Contract.Requires<IndexOutOfRangeException>(
				0 <= index && index < Length,
				"The index must be within the bounds of the array.");
			Contract.Requires(arr[index].interesting == false);
			Contract.Requires(test(arr[index].value) == true);
			Contract.Ensures(arr[index].interesting == true);
			Contract.Ensures(Contract.OldValue(Count) + 1 == Count);

			count++;
			arr[index].interesting = true;

			arr[index].next = sentinel;
			arr[index].prev = arr[sentinel].prev;
			arr[arr[sentinel].prev].next = index;
			arr[sentinel].prev = index;
		}

		#endregion

		#region Public

		/// <summary>
		/// Given a value, decide if it is interesting.
		/// </summary>
		[Pure]
		public delegate bool PartitionFn(T val);

		/// <summary>
		/// Gets maximum the number of elements in the array.
		/// </summary>
		/// <value>
		/// The maximum number of elements in the array.
		/// </value>
		public int Length
		{
			get { return arr.Length - 1; }
		}

		int count = 0;
		/// <summary>
		/// Gets the number of interesting elements in the array.
		/// </summary>
		/// <value>
		/// The number of interesting elements in the array.
		/// </value>
		public int Count
		{
			get { return count; }
		}

		/// <summary>
		/// Initializes a new instance of the PartitionableArray class.
		/// </summary>
		/// <param name='fn'>
		/// A partition function to use to determine if the elements of the
		/// array are interesting.
		/// </param>
		/// <param name='length'>
		/// The fixed maximum number of elements in the array.
		/// </param>
		public PartitionableArray(PartitionFn fn, int length)
		{
			Contract.Requires<ArgumentOutOfRangeException>(0 <= length,
				"Length must be a non-negative integer.");
			Contract.Ensures(test == fn);
			Contract.Ensures(Length == length);
			Contract.Ensures(
				// If default value is interesting, all elements are interesting
				(test(arr[sentinel].value) && Count == length)
				// Otherwise, no elements are interesting
				|| Count == 0);

			test = fn;
			arr = new Element[length + 1]; // One extra element for sentinel
			arr[sentinel].prev = arr[sentinel].next = sentinel; // Set up the sentinel
			for (int i = 0; i < Length; i++) // Check for interesting default values
				if (test(arr[i].value))
					add(i);
		}

		/// <summary>
		/// Gets the index of an interesting element.
		/// <para>No guarantees are made as to which element's index will be
		/// returned, just that the index will be that of an interesting
		/// element.</para>
		/// </summary>
		/// <returns>
		/// The index of an interesting element.
		/// </returns>
		public int AnyInteresting()
		{
			Contract.Requires<NullReferenceException>(Count > 0,
				"The array must contain interesting elements.");
			Contract.Ensures(0 <= Contract.Result<int>()
				&& Contract.Result<int>() < Length,
				"The returned index must be within the bounds of the array.");
			Contract.Ensures(test(this[Contract.Result<int>()]),
				"The returned index must be that of an interesting element.");

			return arr[sentinel].next;
		}

		/// <summary>
		/// Gets or sets the value at a certain index in the array.
		/// </summary>
		/// <param name='index'>
		/// The index in the array.
		/// </param>
		public T this[int index]
		{
			get
			{
				Contract.Requires<IndexOutOfRangeException>(
					0 <= index && index < Length,
					"Index must be within array bounds.");
				Contract.Assume(index < this.arr.Length);

				return arr[index].value;
			}
			set
			{
				Contract.Requires<IndexOutOfRangeException>(
					0 <= index && index < Length,
					"Index must be within array bounds.");
				Contract.Ensures(
					// If old and new values are interesting, Count is unchanged
					((test(Contract.OldValue(arr[index].value))
						== test(arr[index].value))
						&& Contract.OldValue(Count) == Count)
					// If old was uninteresting and new value is interesting, Count increments
					|| (!test(Contract.OldValue(arr[index].value))
						&& test(arr[index].value)
						&& Contract.OldValue(Count) + 1 == Count)
					// If old value was interesting and new value is uninteresting, Count decrements
					|| (test(Contract.OldValue(arr[index].value))
						&& !test(arr[index].value)
						&& Contract.OldValue(Count) - 1 == Count));
				Contract.Assume(index < arr.Length);

				if (test(arr[index].value)) remove(index);
				arr[index].value = value;
				if (test(arr[index].value)) add(index);
			}
		}

		#endregion
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/grid_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fadingEdgeLength="0px"
    android:horizontalSpacing="0dip"
    android:listSelector="@null"
    android:numColumns="auto_fit"
    android:stretchMode="columnWidth"
    android:verticalSpacing="0dip"
    tools:context="com.jonass.filmespopulares.fragments.MainActivityFragment"
    tools:showIn="@layout/activity_main" />


text:
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { HttpModule } from '@angular/http';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { UserService } from '../services/user-service'
import { ProfileComponent } from './profile.component'
import { ProfileSettingsComponent } from './profile-settings/profile-settings.component'

import { FileSelectDirective, FileDropDirective, FileUploadModule } from 'ng2-file-upload';
import { OthersProfileComponent } from './others-profile/others-profile.component'

@NgModule({
    declarations: [
        ProfileComponent,
        ProfileSettingsComponent,
        OthersProfileComponent

    ],
    imports: [
        RouterModule,
        HttpModule,
        BrowserModule,
        FormsModule,
        ReactiveFormsModule
    ],
    exports: [],
    providers: [
        UserService
    ]
})
export class ProfileModule { }


text:
'use strict';

/**
 * module dependencies
 */

var path = require('path');
var Core = require('assemble-core');
var utils = require('./lib/utils');
var cli = require('./lib/cli');

/**
 * Create an `assemble` app. This is the main function exported
 * by the assemble module.
 *
 * ```js
 * var assemble = require('assemble');
 * var app = assemble();
 * ```
 * @param {Object} `options` Optionally pass default options to use.
 * @api public
 */

function Assemble(options) {
  if (!(this instanceof Assemble)) {
    return new Assemble(options);
  }

  Core.apply(this, arguments);
  this.isAssemble = true;

  this.initAssemble(this);
}

/**
 * Inherit assemble-core
 */

Core.extend(Assemble);

/**
 * Initialize Assemble defaults
 */

Assemble.prototype.initAssemble = function(app) {
  var opts = this.options;
  var exts = opts.exts || ['md', 'hbs', 'html'];
  var regex = utils.extRegex(exts);

  // ensure `name` is set for composer-runtimes
  if (!this.name) {
    this.name = opts.name || 'base';
  }

  /**
   * Register plugins
   */

  this.use(utils.pipeline(opts))
    .use(utils.pipeline())
    .use(utils.loader())
    .use(utils.config())
    .use(utils.store())
    .use(utils.argv())
    .use(utils.list())
    .use(utils.cli())
    .use(utils.ask())
    .use(cli());

  /**
   * Default engine
   */

  this.engine(exts, require('engine-handlebars'));

  /**
   * Middleware for parsing front matter
   */

  this.onLoad(regex, function(view, next) {
    // needs to be inside the middleware, to
    // account for options defined after init
    if (view.options.frontMatter !== false && app.options.frontMatter !== false) {
      utils.matter.parse(view, next);
    } else {
      next();
    }
  });

  /**
   * Built-in view collections
   *  | partials
   *  | layouts
   *  | pages
   */

  var engine = opts.defaultEngine || 'hbs';

  this.create('partials', {
    engine: engine,
    viewType: 'partial',
    renameKey: function(fp) {
      return path.basename(fp, path.extname(fp));
    }
  });

  this.create('layouts', {
    engine: engine,
    viewType: 'layout',
    renameKey: function(fp) {
      return path.basename(fp, path.extname(fp));
    }
  });

  this.create('pages', {
    engine: engine,
    renameKey: function(fp) {
      return fp;
    }
  });
};

/**
 * Set a `base` instance that can be used for storing
 * additional instances.
 */

Object.defineProperty(Assemble.prototype, 'base', {
  configurable: true,
  get: function() {
    return this.parent ? this.parent.base : this;
  }
});

/**
 * Expose `Assemble`
 */

module.exports = Assemble;


text:
<!doctype html>

	<meta charset=utf-8>
	<meta http-equiv=cache-control content=no-cache>
	<meta http-equiv=robots content=noindex>
	<meta http-equiv=robots content=nofollow>
	<meta http-equiv=robots content=noarchive>
	<link rel=stylesheet href=mail_form.css>
	<title>mail form</title>

	<form enctype=multipart/form-data action=mail_form.php method=POST>
		<input    type=text     name=mail_user placeholder=user maxlength=100 autofocus=autofocus>

		<textarea type=text     name=mail_text placeholder=text maxlength=10000></textarea>

		<input    type=password name=mail_pass placeholder=pass maxlength=100>

		<button type=submit>send</button>
	</form>