text:
const {stripIndent} = require("common-tags");
const R = require("ramda");
const {nicksMatch} = require("../lib/nicks");

const FILENAME = "aliases.json";

const parseNicksArg = (nicksRaw) => {
  return nicksRaw.trim().split(/\s+/);
};

const pred = R.curry(nicksMatch);

const addAliases = R.curry((newGroup, state) => R.pipe(
  R.defaultTo([]),
  R.append(newGroup),
  R.reduce(
    (result, nextGroup) => {
      const toMerge = R.groupBy(
        (candidateGroup) => R.innerJoin(pred, candidateGroup, nextGroup).length > 0,
        result
      );
      const merged = R.pipe(
        R.defaultTo([]),
        R.flatten,
        R.concat(nextGroup),
        R.uniqWith(pred)
      )(toMerge[true]);
      const distinct = R.defaultTo([], toMerge[false]);
      return R.append(
        merged,
        distinct
      );
    },
    []
  )
)(state));

const findAliases = R.curry((nick, state) => R.pipe(
  R.defaultTo([]),
  R.find(R.find(pred(nick))),
  R.defaultTo([nick])
)(state));

const deleteAliases = R.curry((nick, state) => R.pipe(
  R.defaultTo([]),
  R.reject(R.find(pred(nick)))
)(state));

const countAliases = (state) => R.pipe(
  R.defaultTo([]),
  R.flatten,
  R.length
)(state);

module.exports = (s3Store, {help, match, style, use}) => {
  const getState = (...args) => s3Store.getState(FILENAME, ...args);
  const saveState = (...args) => s3Store.saveState(FILENAME, ...args);
  const doUpdate = (update, cb) => {
    getState((err, oldState) => {
      if (err) return cb(err);
      const newState = update(oldState);
      saveState(newState, (err) => {
        cb(err ? err : null, oldState, newState);
      });
    });
  };

  help("aliases", stripIndent`
    Allows users to save a list of nicks they use in IRC. They are used by other plugins like ${style.em("tell")}.
    ${style.em("!im <nick> <nick> ...")}: Links the given nicks, ${style.strong("and your current nick")}, as the same user.
    ${style.em("!who [nick]")}: Shows all known aliases of yourself or the given nick.
    ${style.em("!add-aliases <nick> <nick> ...")}: Similar to ${style.em("!im")}, but doesn't include your current nick. Useful for setting up aliases for someone else.
    ${style.em("!del-aliases <nick>")}: Removes the alias group containing <nick>. Useful if two groups are accidentally joined and need to be recreated separately with ${style.em("!add-aliases")}.
  `);

  match(/^!im(?:\s+(.+))?$/i, ({reply, nick}, [nicksArg]) => {
    const nicks = [nick, ...parseNicksArg(style.clear(nicksArg))];
    doUpdate(addAliases(nicks), (err, oldState, newState) => {
      if (err) {
        console.error(err);
        return reply(style.strong("Failed to update state"));
      }
      const diff = countAliases(newState) - countAliases(oldState);
      reply(diff > 0 ? `Added ${diff} nick(s)` : "I know");
    });
  });

  match(/^!add-aliases\s+(.+)$/i, ({reply, nick}, [nicksArg]) => {
    const nicks = parseNicksArg(style.clear(nicksArg));
    doUpdate(addAliases(nicks), (err, oldState, newState) => {
      if (err) {
        console.error(err);
        return reply(style.strong("Failed to update state"));
      }
      const diff = countAliases(newState) - countAliases(oldState);
      reply(diff > 0 ? `Added ${diff} nick(s)` : "No change");
    });
  });

  match(/^!del-aliases\s+(.+)$/i, ({reply}, [nickArg]) => {
    doUpdate(deleteAliases(nickArg), (err, oldState, newState) => {
      if (err) {
        console.error(err);
        return reply(style.strong("Failed to update state"));
      }
      const diff = countAliases(oldState) - countAliases(newState);
      const removed = findAliases(nickArg, oldState);
      reply(diff > 0 ? `Removed ${diff} nick(s): ${removed.map(style.nick).join(" ")}` : "No change");
    });
  });

  match(/^!who(?:\s+(\S+))?\s*$/i, ({reply, nick}, [nickArg]) => {
    const query = style.clear(nickArg || nick);
    getState((err, state) => {
      if (err) {
        console.error(err);
        return reply(style.strong("Failed to get state"));
      }
      const aliases = findAliases(query, state);
      if (aliases.length > 1) {
        reply(aliases.map(style.nick).join(" "));
      } else {
        reply(`I don't know any other aliases for ${style.nick(query)}`)
      }
    });
  });

  use((next, ctx) => {
    getState((err, state) => {
      if (err) {
        console.error("Failed to add aliases to context");
        next(ctx);
      } else {
        const aliases = findAliases(ctx.nick, state);
        next({
          ...ctx,
          aliases,
          isAlias: (nick) => R.find(pred(nick), aliases) != undefined
        });
      }
    });
  });
};


text:
del MeshCentral2.zip
"C:\Program Files\WinRAR\WinRAR.exe" a MeshCentral2.zip @SourceFileList.txt

redpajama_set_name: RedPajamaGithub


text:
package org.apache.geode.internal.cache;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.Test;
import org.junit.experimental.categories.Category;

import org.apache.geode.internal.cache.InitialImageOperation.RequestImageMessage;
import org.apache.geode.test.junit.categories.UnitTest;

@Category(UnitTest.class)
public class RequestImageMessageTest {

  @Test
  public void shouldBeMockable() throws Exception {
    RequestImageMessage mockRequestImageMessage = mock(RequestImageMessage.class);
    when(mockRequestImageMessage.getProcessorType()).thenReturn(1);
    assertThat(mockRequestImageMessage.getProcessorType()).isEqualTo(1);
  }
}


text:
layout: default
---

Error

    		The server did not get along with Chuck Norris and received three roundhouse kicks in the face.

            Please try again

    {% include slack_button.html %}


text:
class Turboquery::TableMover

  attr_accessor :source, :destination, :from_table, :to_table

  def initialize(source:, destination:, from_table:, to_table:)
    self.source = source
    self.destination = destination
    self.from_table = from_table
    self.to_table = to_table
  end

  def move
    create_destination unless destination_exists?
    key = copy_source_to_s3
    copy_s3_to_destination(key)
  end

  private

  def source_exists?
    source.table_exists?(from_table)
  end

  def destination_exists?
    destination.table_exists?(to_table)
  end

  def create_destination
    structure = source.dump_table_ddl(from_table)
    structure.gsub!(/^CREATE TABLE [^\(]+\(/, "CREATE TABLE #{to_table} (")
    destination.execute(structure)
    fail 'Unable to create destination table' unless destination_exists?
  end

  def copy_source_to_s3
    source.copy_table_to_s3(from_table)
  end

  def copy_s3_to_destination(key)
    destination.copy_s3_to_table(key, to_table)
  end

end


text:
package cmd

import (
	"os"
	"path"

	log "github.com/golang/glog"
	"github.com/google/gnxi/gnxi_tester/config"
	"github.com/google/gnxi/gnxi_tester/orchestrator"
	"github.com/spf13/cobra"
)

var (
	wipeCmd = &cobra.Command{
		Use:     "wipe",
		Short:   "Wipe config file and containers...",
		Example: "gnxi_tester wipe [files, containers]",
		Run:     handleWipe,
	}
)

// handleWipe wipes files and containers from the host.
func handleWipe(cmd *cobra.Command, args []string) {
	if len(args) == 0 {
		args = []string{"files", "containers"}
	}
	for _, arg := range args {
		switch arg {
		case "files":
			wipeFiles()
			log.Infof("Removed files")
		case "containers":
			tests := config.GetTests()
			names := []string{}
			for test := range tests {
				if test != "provision" {
					names = append(names, test)
				}
			}
			if err := orchestrator.WipeContainers(names); err != nil {
				log.Error(err)
				return
			}
			log.Info("Deleted containers and images")
		}
	}
}

// wipeFiles deletes .gnxi.yml and .gnxi
func wipeFiles() {
	home, err := os.UserHomeDir()
	if err != nil {
		log.Error(err)
	}
	os.Remove(path.Join(home, ".gnxi.yml"))
	os.RemoveAll(path.Join(home, ".gnxi"))
}


text:
package fi.uta.fsd.metka.storage.repository.enums;

/**
 * This enumeration should contain all the different codes for return results that can be sent from within storage in response to requests.
 * ReturnResult reuse is recommended but not mandated so multiple result codes can mean basically the same thing.
 * Some methods can return a collection of results or they can use the results indirectly in some way.
 */
public enum ReturnResult {
    REVISION_CREATED,                   // Either new revisionable was created or new draft revision was created for revisionable, edit returns revision found if existing revision is used
    REVISION_FOUND,                     // Either RevisionEntity or RevisionData was requested and result was found successfully
    REVISION_NOT_FOUND,                 // Either RevisionEntity or RevisionData was requested but no result was found
    REVISION_CONTAINED_NO_DATA,         // RevisionData was requested but RevisionEntity didn't contain any data, this is a serious error
    REVISION_OF_INCORRECT_TYPE,         // RevisionEntity or RevisionData of a certain ConfigurationType was requested but the found revision was of a different type
    REVISION_NOT_VALID,                 // There's something wrong with revision
    NO_REVISION_FOR_REVISIONABLE,       // Revisionable object didn't contain any revisions (either both revision number values were null or no revisions could be found from database), this is a serious error
    REVISIONABLE_FOUND,                 // Requested revisionable was found and returned
    REVISIONABLE_NOT_FOUND,             // Requested revisionable object couldn't be found. Either there's no revisionable for requested id, or the revisionable with the id is of different type than requested
    REVISIONABLE_OF_INCORRECT_TYPE,     // RevisionableEntity of certain ConfigurationType was requested but the found Revisionable was of a different type
    REVISIONABLE_NOT_CREATED,           // Revisionable creation failed due to some error
    REVISIONABLE_NOT_REMOVED,           // Revisionable was not marked as removed when it was expected to be
    REVISIONABLE_REMOVED,               // Revisionable was marked as removed and changes can't be made
    CONFIGURATION_CONTAINED_NO_DATA,    // Entity was found but data was empty, this is a serious error
    CONFIGURATION_FOUND,                // Requested configuration (either data or gui) was found
    CONFIGURATION_NOT_FOUND,            // Configuration (either data or gui) was not found
    CONFIGURATION_NOT_VALID,            // Configuration had problems either during serialization or deserialization
    CONFIGURATION_INVALID_VERSION,      // Configuration had an invalid version number (NOT the current version OR current + 1)
    DATABASE_DISCREPANCY,               // Data in the database is in a state that causes errors, operations had to be stopped
    DATABASE_INSERT_FAILED,             // Insert or merge operation failed for some reason
    DATABASE_INSERT_SUCCESS,            // Insert or update operation was successful
    MISC_JSON_NOT_FOUND,                // Requested miscellaneous json file was either not found or was empty.
    MISC_JSON_FOUND,                    // Requested miscellaneous json file was found
    REVISION_UPDATE_SUCCESSFUL,         // RevisionData was serialized and merged successfully
    REVISION_NOT_A_DRAFT,               // Revision was not in a draft state when draft was expected or parent was not a draft when child requested edit
    OPERATION_SUCCESSFUL_WITH_ERRORS,   // Operation was successful (changed data was updated to database) but there were field errors
    TYPE_NOT_VALID_CONFIGURATION_TYPE,  // Given type was not one of defined Configuration types
    SEARCH_FAILED,                      // Performed search failed
    VIEW_SUCCESSFUL,                    // Some data was requested for viewing, data was gathered successfully
    INCORRECT_TYPE_FOR_OPERATION,       // Operation was requested for a configuration type that is not handled by that operation
    ALL_PARAMETERS_FOUND,               // All required parameters were provided
    PARAMETERS_MISSING,                 // Some parameter that is required is instead missing
    USER_NOT_HANDLER,                   // User is not the current handler of a given revision
    CAN_CREATE_DRAFT,                   // User is allowed to create a new draft revision of object
    REVISION_NOT_CREATE,                // Some reason stopped revision creation for new draft revision
    EXCEPTION,                          // Unhandled exception happened at some point
    OPERATION_SUCCESSFUL,               // General success result for operations
    OPERATION_FAIL,                     // General fail result for operations
    NO_RESULTS,                         // General no results response for operations that request data that is not found but there is no error
    WRONG_USER,                         // User with the wrong user name tried to perform operation that is restricted to one user at a time (e.g. saving a revision)
    WRONG_ROLES,                        // Role(s) the user has don't allow them to perform the requested operation
    REFERENCE_FOUND,                    // Requested reference information was found
    REFERENCE_MISSING,                  // Requested reference information was not found
    EMPTY_QUERY,                        // Provided query was empty and so it could not be parsed
    MALFORMED_LANGUAGE,                 // Provided query language parameter is malformed
    MALFORMED_QUERY,                    // Search query (usually expert search) was in some way invalid and could not be parsed to actual query
    PAGE_CREATED,                       // Binder page was created
    PAGE_UPDATED,                       // Binder page was updated
    PAGE_REMOVED,                       // Binder page was removed successfully
    RESTRICTION_VALIDATION_FAILURE,     // Restriction validation encountered a failed validation
    CASCADE_FAILURE,                    // Operation was cascaded but one of more of the cascades fail and so the root operation fails
    API_AUTHENTICATION_FAILED,          // Authentication in API-method failed
    EMPTY_PATH,                         // Required path was empty
    MALFORMED_PATH,                     // Required path was malformed e.g. incomplete or didn't point to valid end
    EMPTY_SUBQUERY,                     // If subquery returns an empty list then the whole query is aborted. The Main query won't compile if subquery is empty
    NO_CHANGES,                         // Operation did not result in any changes
    HAS_HANDLER,                        // Revision already has handler in a situation where null handler is required
    EXCEPTION_DURING_API_CALL,
    RESULT_SET_TOO_LARGE,
    FILE_ALREADY_EXISTS,                // Special failure condition when file move is tried to a location that already contains a file
    FILE_MISSING,                       // Attachment file was not found
    CONFIG_UPDATE_PARTIAL_FAILURE,      // Failure to save revisions with an updated data configuration
}


text:
#import "MDCButtonBarColorThemer.h"
#import "MaterialButtonBar.h"
#import "MaterialNavigationBar.h"

@implementation MDCButtonBarColorThemer

+ (void)applyColorScheme:(NSObject<MDCColorScheme> *)colorScheme
             toButtonBar:(MDCButtonBar *)buttonBar {
  buttonBar.backgroundColor = colorScheme.primaryColor;

  // When a button bar is contained in a navigation bar do not color the button bar. This is useful
  // for when an app bar with imagery in the flexible header has a button bar. If the button bar has
  // a color then the imagery is obstucted by the solid color of the button bar.
  [MDCButtonBar appearanceWhenContainedIn:[MDCNavigationBar class], nil].backgroundColor
      = nil;
}

@end


text:
extern crate libc;
extern crate apue;

use libc::{STDIN_FILENO, fork, getpid, setsid, tcgetpgrp};
use apue::LibcResult;

fn main() {
    unsafe {
        let pid = fork().check_not_negative().expect("fork error");
        if pid == 0 {
            // child: create new session
            let sid = setsid();
            // verify that I am the new process group leader
            assert!(sid == getpid());
            // verify that we
            assert!(tcgetpgrp(STDIN_FILENO) == -1);
            println!("that was easy..");
        }
    }
}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.5"/>
<title>Voro++: voro++.cc Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Voro++

Main Page

Data Structures

Files

File List

Globals

voro++.cc

Go to the documentation of this file.

    1 // Voro++, a 3D cell-based Voronoi library

    2 //

    3 // Author   : Chris H. Rycroft (LBL / UC Berkeley)

    4 // Email    : chr@alum.mit.edu

    5 // Date     : August 30th 2011

    6

    7 /** \file voro++.cc

    8  * \brief A file that loads all of the function implementation files. */

    9

   10 #include "cell.cc"

   11 #include "common.cc"

   12 #include "v_base.cc"

   13 #include "container.cc"

   14 #include "unitcell.cc"

   15 #include "container_prd.cc"

   16 #include "pre_container.cc"

   17 #include "v_compute.cc"

   18 #include "c_loops.cc"

   19 #include "wall.cc"

v_base.cc

Function implementations for the base Voronoi container class.

c_loops.cc

Function implementations for the loop classes.

v_compute.cc

Function implementantions for the voro_compute template.

container.cc

Function implementations for the container and related classes.

unitcell.cc

Function implementations for the unitcell class.

container_prd.cc

Function implementations for the container_periodic_base and related classes.

pre_container.cc

Function implementations for the pre_container and related classes.

common.cc

Implementations of the small helper functions.

cell.cc

Function implementations for the voronoicell and related classes.

wall.cc

Function implementations for the derived wall classes.

<address class="footer">
Generated on Thu Oct 17 2013 11:14:00 for Voro++ by

 1.8.5
</address>


text:
package e2e

import (
	"testing"

	_ "k8s.io/client-go/plugin/pkg/client/auth"
	"k8s.io/component-base/logs"

	"github.com/kubernetes-sigs/service-catalog/test/e2e/framework"

	"github.com/onsi/ginkgo"
	"github.com/onsi/ginkgo/config"
	"github.com/onsi/gomega"
	"k8s.io/klog"
)

// RunE2ETests checks configuration parameters (specified through flags) and then runs
// E2E tests using the Ginkgo runner.
func RunE2ETests(t *testing.T) {
	logs.InitLogs()
	defer logs.FlushLogs()

	gomega.RegisterFailHandler(ginkgo.Fail)
	// Disable skipped tests unless they are explicitly requested.
	if config.GinkgoConfig.FocusString == "" && config.GinkgoConfig.SkipString == "" {
		config.GinkgoConfig.SkipString = `\[Flaky\]|\[Feature:.+\]`
	}

	klog.Infof("Starting e2e run %q on Ginkgo node %d", framework.RunId, config.GinkgoConfig.ParallelNode)
	ginkgo.RunSpecs(t, "Service Catalog e2e suite")
}


text:
class Hickwall < ActiveRecord::Base
	acts_as_knox
end


text:
package com.yq.user.bo;

import java.util.Date;

   /**
    * gcuser for excel 实体类
    */

public class GcuserForExcel{
	private Integer id;
	private String username;
	private int sjb;
	private String up;
	private Date upgmdate;
	private String name;
	private String addsheng;
	private String addshi;
	private String addqu;
	private String call;
	private String qq;
	private Date bddate;

	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public int getSjb() {
		return sjb*500;
	}
	public void setSjb(int sjb) {
		this.sjb = sjb;
	}
	public String getUp() {
		return up;
	}
	public void setUp(String up) {
		this.up = up;
	}
	public Date getUpgmdate() {
		return upgmdate;
	}
	public void setUpgmdate(Date upgmdate) {
		this.upgmdate = upgmdate;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAddsheng() {
		return addsheng;
	}
	public void setAddsheng(String addsheng) {
		this.addsheng = addsheng;
	}
	public String getAddshi() {
		return addshi;
	}
	public void setAddshi(String addshi) {
		this.addshi = addshi;
	}
	public String getAddqu() {
		return addqu;
	}
	public void setAddqu(String addqu) {
		this.addqu = addqu;
	}
	public String getCall() {
		return call;
	}
	public void setCall(String call) {
		this.call = call;
	}
	public String getQq() {
		return qq;
	}
	public void setQq(String qq) {
		this.qq = qq;
	}
	public Date getBddate() {
		return bddate;
	}
	public void setBddate(Date bddate) {
		this.bddate = bddate;
	}
}


text:
package com.facebook.crypto;

import android.annotation.TargetApi;
import android.os.Build;
import android.test.InstrumentationTestCase;

import com.facebook.android.crypto.keychain.AndroidCryptoLibrary;
import com.facebook.crypto.keychain.KeyChain;
import com.facebook.soloader.SoLoader;

import junit.framework.Assert;

import java.util.Arrays;

import static com.facebook.crypto.CryptoTestUtils.fixedKeyChain;
import static com.facebook.crypto.CryptoTestUtils.toBytes;

/**
 * Tests encryption using 128-bits keys.
 * It uses examples from
 * http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/gcm/gcm-revised-spec.pdf
 */
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class Cipher128BitsTest extends InstrumentationTestCase {

    protected void setUp() throws Exception {
      SoLoader.init(this.getInstrumentation().getContext(), false);
    }

    public void testCases() throws Exception {
        // Test Case 3 - Page 29
        testCase(
                // key
                "feffe9928665731c6d6a8f9467308308",
                // iv
                "cafebabefacedbaddecaf888",
                // plain text
                "d9313225f88406e5a55909c5aff5269a" +
                "86a7a9531534f7da2e4c303d8a318a72" +
                "1c3c0c95956809532fcf0e2449a6b525" +
                "b16aedf5aa0de657ba637b391aafd255",
                // cipher text
                "42831ec2217774244b7221b784d0d49c" +
                "e3aa212f2c02a4e035c17e2329aca12e" +
                "21d514b25466931c7d8f6a5aac84aa05" +
                "1ba30b396a0aac973d58e091473f5985");
        // Test Case 4 - Page 30
        testCase(
                // key
                "feffe9928665731c6d6a8f9467308308",
                // iv
                "cafebabefacedbaddecaf888",
                // plain text
                "d9313225f88406e5a55909c5aff5269a" +
                "86a7a9531534f7da2e4c303d8a318a72" +
                "1c3c0c95956809532fcf0e2449a6b525" +
                "b16aedf5aa0de657ba637b39",
                // cipher text
                "42831ec2217774244b7221b784d0d49c" +
                "e3aa212f2c02a4e035c17e2329aca12e" +
                "21d514b25466931c7d8f6a5aac84aa05" +
                "1ba30b396a0aac973d58e091");
    }

    public void testCase(String key, String iv, String plain, String cipher) throws Exception {
        // Test Case 16 - Page 40
        KeyChain keyChain = fixedKeyChain(key, iv);
        CryptoConfig config = CryptoConfig.KEY_128;
        Crypto crypto = new Crypto(keyChain, new AndroidCryptoLibrary(), config);
        byte[] plainBytes = toBytes(plain);
        byte[] encrypted = crypto.encrypt(plainBytes, new Entity("whatever"));
        byte[] expected = toBytes(cipher);
        // remove initial 2 bytes + IV
        // remove final tag 16 bytes
        int metadataLength = config.getHeaderLength() + config.getTailLength();
        int prefix = metadataLength - config.tagLength;
        byte[] bareEncrypted = Arrays.copyOfRange(encrypted, prefix, encrypted.length - config.tagLength);
        Assert.assertTrue(Arrays.equals(expected, bareEncrypted));
    }
}


text:
package org.apache.wink.server.internal.handlers;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Properties;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.ws.rs.HttpMethod;

import org.apache.wink.common.RestConstants;
import org.apache.wink.common.http.HttpStatus;
import org.apache.wink.server.handlers.HandlersChain;
import org.apache.wink.server.handlers.MessageContext;
import org.apache.wink.server.handlers.RequestHandler;
import org.apache.wink.server.handlers.ResponseHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HeadMethodHandler implements RequestHandler, ResponseHandler {

    private static final Logger logger                     =
                                                               LoggerFactory
                                                                   .getLogger(HeadMethodHandler.class);

    private static final String ORIGINAL_RESPONSE_ATT_NAME =
                                                               HeadMethodHandler.class.getName() + "_original_response"; //$NON-NLS-1$

    public void handleRequest(MessageContext context, HandlersChain chain) throws Throwable {

        // first thing - proceed the chain
        chain.doChain(context);

        // check the search result.
        // if the request is HEAD and no method was found, try to find a GET
        // method
        // and discard the entity
        SearchResult searchResult = context.getAttribute(SearchResult.class);
        if (searchResult.isError() && searchResult.getError().getResponse().getStatus() == HttpStatus.METHOD_NOT_ALLOWED
            .getCode()
            && context.getHttpMethod().equalsIgnoreCase(HttpMethod.HEAD)) {
            logger
                .trace("No HEAD method so trying GET method while not sending the response entity"); //$NON-NLS-1$
            context.setHttpMethod(HttpMethod.GET);
            HttpServletResponse originalResponse = context.getAttribute(HttpServletResponse.class);
            NoBodyResponse noBodyResponse = new NoBodyResponse(originalResponse);
            context.setAttribute(HttpServletResponse.class, noBodyResponse);
            context.setAttribute(HttpServletResponseWrapper.class, noBodyResponse);
            context.setAttribute(NoBodyResponse.class, noBodyResponse);
            context.getAttributes().put(ORIGINAL_RESPONSE_ATT_NAME, originalResponse);
            chain.doChain(context);
        }
    }

    public void handleResponse(MessageContext context, HandlersChain chain) throws Throwable {
        HttpServletResponse originalResponse =
            (HttpServletResponse)context.getAttributes().remove(ORIGINAL_RESPONSE_ATT_NAME);
        if (originalResponse != null) {
            HttpServletResponse response = context.getAttribute(HttpServletResponse.class);
            response.flushBuffer();
            NoBodyResponse noBodyResponse = context.getAttribute(NoBodyResponse.class);
            response.setContentLength(noBodyResponse.getContentLengthValue());
            // set the original response on the context
            context.setAttribute(HttpServletResponse.class, originalResponse);
        }
        chain.doChain(context);
    }

    private static final class NoBodyResponse extends HttpServletResponseWrapper {

        private PrintWriter    writer         = null;
        private CountingStream countingStream = null;

        NoBodyResponse(HttpServletResponse servletResponse) {
            super(servletResponse);
        }

        int getContentLengthValue() {
            return countingStream.getByteCount();
        }

        @Override
        public void flushBuffer() {
            if (writer != null) {
                writer.flush();
            }
        }

        public PrintWriter getWriter() throws IOException {
            if (writer == null) {
                String charsetName =
                    getCharacterEncoding() != null ? getCharacterEncoding()
                        : RestConstants.CHARACTER_ENCODING_UTF_8;
                OutputStreamWriter osWriter =
                    new OutputStreamWriter(getOutputStream(), charsetName);
                writer = new PrintWriter(osWriter);
            }
            return writer;
        }

        public ServletOutputStream getOutputStream() throws IOException {
            if (countingStream == null) {
                countingStream = new CountingStream();
            }
            return countingStream;
        }

        private static final class CountingStream extends ServletOutputStream {

            private int byteCount = 0;

            /**
             * @return number of bytes written
             */
            public int getByteCount() {
                return byteCount;
            }

            public void write(int b) throws IOException {
                byteCount++;
            }

            public void write(byte b[], int off, int len) throws IOException {
                byteCount += len;
            }

        } // class CountingStream

    } // class NoBodyResponseWrapper

    public void init(Properties props) {
    }

}


text:
namespace BeeDownloader.Views
{
	partial class ProgressBox
	{
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.IContainer components = null;

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing && (components != null))
			{
				components.Dispose();
			}
			base.Dispose(disposing);
		}

		#region Windows Form Designer generated code

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ProgressBox));
			this.mText = new System.Windows.Forms.Label();
			this.progressBar1 = new System.Windows.Forms.ProgressBar();
			this.button1 = new System.Windows.Forms.Button();
			this.SuspendLayout();
			//
			// mText
			//
			this.mText.AutoSize = true;
			this.mText.Location = new System.Drawing.Point(12, 21);
			this.mText.Name = "mText";
			this.mText.Size = new System.Drawing.Size(16, 13);
			this.mText.TabIndex = 0;
			this.mText.Text = "...";
			this.mText.UseWaitCursor = true;
			//
			// progressBar1
			//
			this.progressBar1.Location = new System.Drawing.Point(12, 37);
			this.progressBar1.Name = "progressBar1";
			this.progressBar1.Size = new System.Drawing.Size(375, 23);
			this.progressBar1.Style = System.Windows.Forms.ProgressBarStyle.Marquee;
			this.progressBar1.TabIndex = 1;
			this.progressBar1.UseWaitCursor = true;
			//
			// button1
			//
			this.button1.Enabled = false;
			this.button1.Location = new System.Drawing.Point(312, 66);
			this.button1.Name = "button1";
			this.button1.Size = new System.Drawing.Size(75, 23);
			this.button1.TabIndex = 2;
			this.button1.Text = "Cancel";
			this.button1.UseVisualStyleBackColor = true;
			this.button1.UseWaitCursor = true;
			//
			// ProgressBox
			//
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(399, 100);
			this.ControlBox = false;
			this.Controls.Add(this.button1);
			this.Controls.Add(this.progressBar1);
			this.Controls.Add(this.mText);
			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
			this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
			this.MaximizeBox = false;
			this.MinimizeBox = false;
			this.Name = "ProgressBox";
			this.ShowInTaskbar = false;
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
			this.Text = "BeeDownloader";
			this.UseWaitCursor = true;
			this.ResumeLayout(false);
			this.PerformLayout();

		}

		#endregion

		private System.Windows.Forms.Label mText;
		private System.Windows.Forms.ProgressBar progressBar1;
		private System.Windows.Forms.Button button1;
	}
}


text:
{{#each toDo}}

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

            <form id="modalHeader">
              <input class="form-control card-title" id="myModalLabel" value="{{title}}" placeholder="Enter a title here!">
            </form>

            {{{notes}}}

            <form>
              <input class="form-control card-tag-new pull-left" placeholder="Add new tag">
            </form>
            Add

Last Edited: {{timeLastEdit}}

          Delete
          Open Document

            <form>
              <input class="form-control card-doc-link" placeholder="Enter a document link here!" value="{{documentUrl}}">
            </form>

{{/each}}

{{#each inProgress}}

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

            <form id="modalHeader">
              <input class="form-control card-title" id="myModalLabel" value="{{title}}" placeholder="Enter a title here!">
            </form>

            {{{notes}}}

            <form>
              <input class="form-control card-tag-new pull-left" placeholder="Add new tag">
            </form>
            Add

Last Edited: {{timeLastEdit}}

          Delete
          Open Document

            <form>
              <input class="form-control card-doc-link" placeholder="Enter a document link here!" value="{{documentUrl}}">
            </form>

{{/each}}

{{#each complete}}

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

            <form id="modalHeader">
              <input class="form-control card-title" id="myModalLabel" value="{{title}}" placeholder="Enter a title here!" {{#if done}}disabled{{/if}} {{#if stageDone}}disabled{{/if}}>
            </form>

            {{{notes}}}

            <form>
              <input class="form-control card-tag-new pull-left" placeholder="Add new tag">
            </form>
            Add

Last Edited: {{timeLastEdit}}

          Delete
          Open Document

            <form>
              <input class="form-control card-doc-link" placeholder="Enter a document link here!" value="{{documentUrl}}" {{#if done}}disabled{{/if}} {{#if stageDone}}disabled{{/if}}>
            </form>

{{/each}}


text:
package com.asakusafw.runtime.value;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import org.junit.Test;

/**
 * Test for {@link FloatOption}.
 */
@SuppressWarnings("deprecation")
public class FloatOptionTest extends ValueOptionTestRoot {

    /**
     * test for initial state.
     */
    @Test
    public void init() {
        FloatOption option = new FloatOption();
        assertThat(option.isNull(), is(true));
    }

    /**
     * test for get.
     */
    @Test
    public void get() {
        FloatOption option = new FloatOption();
        option.modify(100);
        assertThat(option.get(), is(100.f));
        assertThat(option.isNull(), is(false));
    }

    /**
     * test for or w/ absent value.
     */
    @Test
    public void or() {
        FloatOption option = new FloatOption();
        assertThat(option.or(30), is(30.f));
        assertThat(option.isNull(), is(true));
    }

    /**
     * test for or w/ present value.
     */
    @Test
    public void orNotNull() {
        FloatOption option = new FloatOption();
        option.modify(100);
        assertThat(option.or(30), is(100.f));
    }

    /**
     * test for copyFrom.
     */
    @Test
    public void copy() {
        FloatOption option = new FloatOption();
        FloatOption other = new FloatOption();
        other.modify(50);
        option.copyFrom(other);
        assertThat(option.get(), is(50.f));

        option.modify(0);
        assertThat(other.get(), is(50.f));
    }

    /**
     * test for copyFrom w/ null.
     */
    @Test
    public void copyNull() {
        FloatOption option = new FloatOption();
        option.modify(100);

        FloatOption other = new FloatOption();
        option.copyFrom(other);
        assertThat(option.isNull(), is(true));
        option.modify(100);

        option.copyFrom(null);
        assertThat(option.isNull(), is(true));
    }

    /**
     * test for compare.
     */
    @Test
    public void compareTo() {
        FloatOption a = new FloatOption();
        FloatOption b = new FloatOption();
        FloatOption c = new FloatOption();
        FloatOption d = new FloatOption();
        FloatOption e = new FloatOption();

        a.modify(-10);
        b.modify(0);
        c.modify(30);
        d.modify(-10);
        e.modify(-30);

        assertThat(compare(a, b), lessThan(0));
        assertThat(compare(b, c), lessThan(0));
        assertThat(compare(c, a), greaterThan(0));
        assertThat(compare(a, c), lessThan(0));
        assertThat(compare(b, a), greaterThan(0));
        assertThat(compare(c, b), greaterThan(0));
        assertThat(compare(a, d), is(0));
        assertThat(compare(d, e), greaterThan(0));
    }

    /**
     * test for comapre w/ null.
     */
    @Test
    public void compareNull() {
        FloatOption a = new FloatOption();
        FloatOption b = new FloatOption();
        FloatOption c = new FloatOption();

        a.modify(Float.NEGATIVE_INFINITY);

        assertThat(compare(a, b), greaterThan(0));
        assertThat(compare(b, a), lessThan(0));
        assertThat(compare(b, c), is(0));
    }

    /**
     * test for Writable.
     */
    @Test
    public void write() {
        FloatOption option = new FloatOption();
        option.modify(100);
        FloatOption restored = restore(option);
        assertThat(restored.get(), is(option.get()));
    }

    /**
     * test for Writable w/ max.
     */
    @Test
    public void write_max() {
        FloatOption option = new FloatOption();
        option.modify(Float.POSITIVE_INFINITY);
        FloatOption restored = restore(option);
        assertThat(restored.get(), is(option.get()));
    }

    /**
     * test for Writable w/ min.
     */
    @Test
    public void write_0() {
        FloatOption option = new FloatOption();
        option.modify(0);
        FloatOption restored = restore(option);
        assertThat(restored.get(), is(option.get()));
    }

    /**
     * test for Writable w/ null.
     */
    @Test
    public void writeNull() {
        FloatOption option = new FloatOption();
        FloatOption restored = restore(option);
        assertThat(restored.isNull(), is(true));
    }
}


text:
from flask import render_template, request
from app import app
import MySQLdb
from models import tweet_features, get_tweet_html, validate_tweet

@app.route('/')
@app.route('/input')
def landing():
    return render_template("input.html", img_count=0)
    # input template -> score. Carries image info.

@app.route('/score', methods=['GET', 'POST'])
def score():
    img_count = int(request.form['img_count'])
    tweet_in = request.form['tweetText']
    try:
        file1 = request.form["file"]
    except:
        file1 = None
    if file1:
        img_count += 1

    tweet_coord = tweet_features(tweet_in, img_count) # input image count
    tweet_html = get_tweet_html(tweet_in)
    invalid_tweet = validate_tweet(tweet_in, img_count)

    db = MySQLdb.connect(host='localhost', user='root', passwd='CFT^vgy7', db='tweetscore', charset='utf8')

    with db:
        cur = db.cursor()
        #just select the city from the world_innodb that the user inputs
        cur.execute("SELECT msg1, msg2, msg3 FROM recommendations_RF2 WHERE desig='%s';" % tweet_coord)
        query_results = cur.fetchall()

    if invalid_tweet is False:
        msg1 = query_results[0][0]
        msg2 = query_results[0][1]
        msg3 = query_results[0][2]

        if msg1 == "":
            msg1 = "This tweet is the best it can be! If you want to improve, try something completely different."
            msg2 = ""
            msg3 = ""

        return render_template("score.html", tweet_html=tweet_html, img_count=img_count, tweetText=tweet_in, msg1=msg1,
                               msg2=msg2, msg3=msg3)

    elif invalid_tweet == "Too long":
        msg1 = "This tweet is more than 140 characters."
        msg2 = ""
        msg3 = ""
        return render_template("score.html", tweet_html=tweet_html, img_count=img_count, tweetText=tweet_in, msg1=msg1,
                               msg2=msg2, msg3=msg3)
    else:
        msg1 = "This does not appear to be a valid tweet!"
        msg2 = ""
        msg3 = ""
        return render_template("score.html", tweet_html=tweet_html, img_count=img_count, tweetText=tweet_in, msg1=msg1,
                               msg2=msg2, msg3=msg3)

@app.route('/upload', methods=['GET', 'POST'])
# Upload an image. For now, just point to input.
def upload():
    img_count = int(request.form['img_count'])
    tweet_in = request.form['tweetText']
    return render_template("score.html", img_count=img_count, tweetText=tweet_in)

@app.route('/edit', methods=['GET', 'POST'])
def edit():
    img_count = int(request.form['img_count'])
    tweet_in = request.form['tweetText']
    return render_template("edit.html", tweetText=tweet_in, img_count=img_count)


text:
echo "Installing VICE. This may take a while. Please be patient..."

# Update and install
sudo apt-get update
sudo apt-get install -y vice

# Get code
wget http://www.zimmers.net/anonftp/pub/cbm/crossplatform/emulators/VICE/old/vice-1.5-roms.tar.gz -O /tmp/vice-1.5-roms.tar.gz
tar xvzf /tmp/vice-1.5-roms.tar.gz

# Go to data folder
cd vice-1.5-roms/data

# Copy to directory
sudo cp -rv * /usr/lib/vice

# Create config directory
mkdir -p /home/chip/.vice

# Copy config to directory
sudo cp /usr/local/bin/pocketinstaller/Configuration/vicerc /home/chip/.vice/vicerc

# Move to home dir
cd ~

# VICE icon
if test -f ~/.pocket-home/.version; then
  IS_ICON_PRESENT=`jq '.pages[0] | .items[] | select(.name == "VICE")' ~/.pocket-home/config.json`
  if [ -z ${IS_ICON_PRESENT} ]
  then
    jq '(.pages[0] | .items) |= . + [{ "name": "VICE", "icon": "/usr/local/bin/pocketinstaller/Icons/vice.png", "shell": "x64" }]' ~/.pocket-home/config.json > tmp.$$.json
    mv tmp.$$.json ~/.pocket-home/config.json
  fi
fi

echo "VICE installed. Have fun!"


text:
<?php
class Usuario extends ActiveRecord{

}
?>


text:
using System.Collections;
using SoomlaWpStore;
using SoomlaWpStore.exceptions;
using SoomlaWpCore.util;

namespace SoomlaWpCore.rewards {

	///
	/// A specific type of Reward is the one you'll use to give your
	/// users some amount of a virtual item when they complete something.
	///
	public class VirtualItemReward : Reward {
		private static string TAG = "SOOMLA VirtualItemReward";

		public string AssociatedItemId;
		public int Amount;

		///
		/// Constructor.
		///
		/// <param name="rewardId">see parent</param>
		/// <param name="name">see parent</param>
		public VirtualItemReward(string rewardId, string name, string associatedItemId, int amount)
			: base(rewardId, name)
		{
			AssociatedItemId = associatedItemId;
			Amount = amount;
		}

		///
		/// see parent.
		///
		public VirtualItemReward(JSONObject jsonReward)
			: base(jsonReward)
		{
            AssociatedItemId = jsonReward[SoomlaWpStore.data.StoreJSONConsts.VIR_ASSOCITEMID].str;
            Amount = (int)jsonReward[SoomlaWpStore.data.StoreJSONConsts.VIR_AMOUNT].n;
		}

		///
		/// Constructor.
		///
		/// <returns>see parent</returns>
		public override JSONObject toJSONObject() {
			JSONObject obj = base.toJSONObject();
            obj.AddField(SoomlaWpStore.data.StoreJSONConsts.VIR_ASSOCITEMID, AssociatedItemId);
            obj.AddField(SoomlaWpStore.data.StoreJSONConsts.VIR_AMOUNT, Amount);
			obj.AddField(SoomlaWpCore.data.JSONConsts.SOOM_CLASSNAME, GetType().Name);

			return obj;
		}

		protected override bool giveInner() {

			try {
				StoreInventory.GiveItem(AssociatedItemId, Amount);
			} catch (VirtualItemNotFoundException e) {
				SoomlaUtils.LogError(TAG, "(give) Couldn't find associated itemId: " + AssociatedItemId);
				SoomlaUtils.LogError(TAG, e.Message);
				return false;
			}
			return true;
		}

		protected override bool takeInner() {

			try {
				StoreInventory.TakeItem(AssociatedItemId, Amount);
			} catch (VirtualItemNotFoundException e) {
				SoomlaUtils.LogError(TAG, "(take) Couldn't find associated itemId: " + AssociatedItemId);
				SoomlaUtils.LogError(TAG, e.Message);
				return false;
			}
			return true;
		}

	}
}


text: from .child_package import *


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ma420_Assignments.Chapter7
{
    class Bairstow
    {
        //CONSTANT VARIABLE DEFINITIONS

        const double DEFAULT_ERROR = 0.01;
        const int DEFAULT_MAX_ITERS = 30;
        const double DEFAULT_R = -1;
        const double DEFAULT_S = -1;

        //INSTANCE VARIABLE DEFINITIONS

        List<double[]> coefficients; //stores the coefficients for every iteration

        double allowedError; //the error distance to be under

        double startR, startS;

        int maxIterNum; //the max number of iterations to perform before giving up

        //stores necessary information resulting from a single "performIteration" operation
        public struct IterationResult
        {
            public double iterR, iterS, iterRError, iterSError, deltaR, deltaS;
            public bool dataRelevant, rootFound, allRootsFound, maxIterationsExceeded;
        }

        List<List<IterationResult>> iterResults; //stores the results of the iterations
        public List<List<IterationResult>> getIterationResults() { return iterResults; }

        //returns the most recent, nonempty set of iterations (or null if none exists)
        public List<IterationResult> getLatestIterations()
        {
            List<IterationResult> results = null;
            if (iterResults.Count > 1)
            {
                if (iterResults[iterResults.Count - 1].Count > 0)
                    results = iterResults[iterResults.Count - 1];
                else
                    results = iterResults[iterResults.Count - 2];
            }
            else if (iterResults[0].Count > 0) results = iterResults[0];
            return results;
        }

        int foundRootCount; //how many roots have been found

        Tuple<double, double>[] roots; //the array storing the found roots, Item1 is the real component, Item2 is the imaginary component

        public class MAX_ITER_NUM_REACHED_EXCEPTION : Exception
        {
            int bob = 1;
        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        //PUBLIC METHOD DEFINITIONS

        public static void TestModule()
        {
            //textbook example, in order from least power to highest power of x
            //1.25 -3.875 2.125 2.75 -3.5 1
            double[] testArray = { 1.25, -3.875, 2.125, 2.75, -3.5, 1 };

            IterationResult result;
            Bairstow b = new Bairstow(testArray, 0.001, 30, 0,0);
            do
            {
                result = b.performIteration();
                Console.WriteLine("R: " + result.iterR + " S: " + result.iterS + " R-ERR: " + result.iterRError + " S-ERR: " + result.iterSError + " DELTA-R: " +
                    result.deltaR + " DELTA-S: " + result.deltaS);
                if (result.rootFound) Console.WriteLine();
            } while (result.allRootsFound == false);

            Tuple<double, double>[] roots = b.calculateRoots();
            for(int i = 0; i < roots.Length; ++i)
            {
                Console.WriteLine("REAL: " + roots[i].Item1 + " COMPLEX: " + roots[i].Item2);
            }
        }

        public Bairstow(double[] polynomial) : this(polynomial, DEFAULT_ERROR) { ; }

        public Bairstow(double[] polynomial, double s, double r) : this(polynomial, DEFAULT_ERROR, s, r) { ; }

        public Bairstow(double[] polynomial, double error, double s, double r) : this (polynomial, error, DEFAULT_MAX_ITERS, s, r) { ; }

        public Bairstow(double[] polynomial, double error) : this(polynomial, error, DEFAULT_MAX_ITERS) { ; }

        public Bairstow(double[] polynomial, double error, int maxIters) : this (polynomial, error, maxIters, DEFAULT_S, DEFAULT_R) { ; }

        public Bairstow(double[] polynomial, double error, int maxIters, double s, double r)
        {
            coefficients = new List<double[]>();
            coefficients.Add(polynomial);
            allowedError = error;
            roots = new Tuple<double, double>[polynomial.Length - 1];
            iterResults = new List<List<IterationResult>>();
            iterResults.Add(new List<IterationResult>());
            maxIterNum = maxIters;
            foundRootCount = 0;
            startR = r;
            startS = s;
        }

        // Performs a single iteration over the coefficients.  Returns the results of the iteration as well as stores them in the internal list
        // Will return a placeholder iteration result if all the roots have been found / no more roots need to be found via iterations
        public IterationResult performIteration()
        {
            IterationResult res = new IterationResult();
            if(roots.Length - foundRootCount > 2)
            {
                //if there are more than two roots left to find, perform a generic iteration step method
                res = performIterationStep();
            }
            else if(roots.Length - foundRootCount == 2)
            {
                //if there are exactly 2 roots left to find, perform quadratic solution method
                res = performQuadraticSolution();
            }
            else if(roots.Length - foundRootCount == 1)
            {
                //if only one root left, calculate it using the solveSingle method(and store it) and set dataRelevant to false
                roots[foundRootCount++] = solveSingle(coefficients[coefficients.Count-1][0], coefficients[coefficients.Count - 1][1]);
                res.dataRelevant = false;
                res.rootFound = true;
            }
            else
            {
                //all the roots have been found, set dataRelevant to false and set allRootsFound to true;
                res.allRootsFound = true;
                res.dataRelevant = false;
            }
            if (roots.Length - foundRootCount == 0)
            {
                //make sure allRootsFound is set to true;
                res.allRootsFound = true;
            }
            return res;
        }

        // Calculate a pair of roots by going through a set of iterations
        // Returns the last 2 roots in the roots array
        // If there is only a single root, it will be stored in Item1 and Item2 will be null
        public Tuple<Tuple<double, double>, Tuple<double, double>> calculateRootPair()
        {
            Tuple<Tuple<double, double>, Tuple<double, double>> results;
            if (roots.Length - foundRootCount > 0) //are we done yet?
            {   //guess not, so we need to find the next pair of roots
                //basically, call performIteration() until the result has rootFound set to true
                IterationResult iterResult = performIteration();
                while(!iterResult.rootFound)
                {
                    iterResult = performIteration();
                }
            }

            //return the last 2 or (if there is only 1) 1 root
            if (roots.Length > 1)
                results = new Tuple<Tuple<double, double>, Tuple<double, double>>(roots[foundRootCount - 2], roots[foundRootCount - 1]);
            else
                results = new Tuple<Tuple<double, double>, Tuple<double, double>>(new Tuple<double, double>(0, 0), roots[roots.Length - 1]);

            return results;
        }

        //calculates all the roots (assuming they are not already calculated)
        public Tuple<double, double>[] calculateRoots()
        {
            while (roots.Length - foundRootCount > 0)
            {
                performIteration(); //this does the heavy lifting
            }
            return roots;
        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        //PRIVATE METHOD DEFINITIONS

        //This performs a single, actual iteration of Bairstow's method
        private IterationResult performIterationStep()
        {
            IterationResult result = new IterationResult();
            result.dataRelevant = true;

            //set up the arrays
            double[] aArray = coefficients[coefficients.Count - 1];
            double[] bArray = new double[aArray.Length];
            double[] cArray = new double[bArray.Length];

            //set up the r and s variables
            double r = startR;
            double s = startS;
            List<IterationResult> currSet = iterResults[iterResults.Count - 1];
            if (currSet.Count != 0) //is there current information for this iteration set
            {   //if so, set up the r and s using the previous specified values
                IterationResult prev = currSet[currSet.Count - 1];//iterResults[overIterNum][iterNum - 1];
                r = prev.iterR + prev.deltaR;
                s = prev.iterS + prev.deltaS;
            }
            else if(foundRootCount > 0) //have we found any roots
            {   //if so, use the previous 2 values of r and s as good starting values of r and s
                List<IterationResult> prevSet = iterResults[iterResults.Count - 2];
                IterationResult lastOfPrev = prevSet[prevSet.Count - 1];
                r = lastOfPrev.iterR + lastOfPrev.deltaR;
                s = lastOfPrev.iterS + lastOfPrev.deltaS;
            }

            if(currSet.Count >= maxIterNum)
            {
                result.maxIterationsExceeded = true;
                throw new MAX_ITER_NUM_REACHED_EXCEPTION();
            }

            //Calculate the bArray and cArray values
            //This is possible and necessary for 2 reasons:
            //  1)  Synthetic division can be represented by using a recurrence relation.  I store the reults of the
            //      division in the bArray.
            //  2)  Somehow (dark magicks), the partial derivatives used for calculating the deltas can be bypassed
            //      by performing a similar synthetic division / recurrence relation on the bArray as we did to the
            //      initial coefficients on the aArray, and then using the values in other calculations.  The
            //      results of this division are stored in the cArray.
            //
            //  bArray's recurrence relation for b[0] to b[n]
            //      b[n] = a[n]
            //      b[n-1] = a[n-1] + r * b[n]
            //      b[i] = a[i] + r * b[i+1] + s * b[i+2]   //for i = n-2 to 0
            //
            //  cArray's recurrence relation for c[1] to c[n]
            //      c[n] = b[n]
            //      c[n-1] = b[n-1] + r * c[n]
            //      c[i] = b[i] + r * c[i+1] + s * c[i+2]   //for i = n-2 to 1 //but we continue it for laziness / code format's sake
            //
            //To save time, i perform both divisions basically simultaneously
            bArray[bArray.Length - 1] = aArray[bArray.Length - 1];
            bArray[bArray.Length - 2] = aArray[aArray.Length - 2] + r * bArray[bArray.Length - 1];
            cArray[bArray.Length - 1] = bArray[bArray.Length - 1];
            cArray[bArray.Length - 2] = bArray[bArray.Length - 2] + r * cArray[bArray.Length - 1];
            for(int i = bArray.Length - 3; i >= 0; --i)
            {
                bArray[i] = aArray[i] + r * bArray[i + 1] + s * bArray[i + 2];
                cArray[i] = bArray[i] + r * cArray[i + 1] + s * cArray[i + 2];
            }

            //calculate the deltas for the next iteration
            //solve a system of two equations for deltaS and deltaR
            //the c values listed below correspon (somehow) with the partial derivatives needed for calculating the deltas
            //  c2 * deltaR + c3 * deltaS = -b1
            //  c1 * deltaR + c2 * deltaS = -b0
            double deltaS = 0;
            double deltaR = 0;
            {
                int count = currSet.Count;

                int bob = 1;

                //assign some values for convenience
                double c1 = cArray[1];
                double c2 = cArray[2];
                double c3 = cArray[3];
                double b1 = bArray[1];
                double b0 = bArray[0];

                //solve a system of two equations for deltaS and deltaR
                //  c2 * deltaR + c3 * deltaS = -b1
                //  c1 * deltaR + c2 * deltaS = -b0

                //bad solution that involved maybe dividing by 0
                //ds = ( ( -c1 * b1 / c2 ) + b0) / ( ( c1 * c3 / c2 ) - c2)
                //  deltaS = (((0 - c1) * b1 / c2) + b0) / ( ( c1 * c3 / c2 ) - c2 );
                //(-b1 - c3 * ds) / c2 = dr
                //  deltaR = ((0 - b1) - c3 * deltaS) / c2;

                //because of the earlier, bad solution that would end up with a div by 0 error, I decided to solve
                //the system of equations using a series of matries

                //here we go matrices
                double one_one, one_two, one_three, two_one, two_two, two_three, store_meh;
                one_one = c2;
                one_two = c3;
                one_three = -b1;
                two_one = c1;
                two_two = c2;
                two_three = -b0;

                //Current state of the matrix
                //  [c2   c3  -b1]
                //  [c1   c2  -b0]
                //
                //corresponds to
                //
                //  [1-1      1-2     1-3]
                //  [2-1      2-2     2-3]

                //from here on out, whenever i use num1 or num2 or num3 or .. in a matrix, i'm just referring to some number, not a specific number from a previous diagram
                //when i use a numX in an english statement, assume im referring to the diagram directly above

                //add the bottom row to the top and the top to the bottom in hopes of getting rid of any 0s in the coefficients to deltaR and deltaS
                {
                    bool good = false;
                    double temp_one = 0, temp_two = 0, temp_three = 0, mult = 1;

                    //add some multiple of the bottom row to the top
                    while (!good) {
                        temp_one = one_one + two_one * mult;
                        temp_two = one_two + two_two * mult;
                        temp_three = one_three + two_three * mult;
                        good = (temp_one != 0) && (temp_two != 0); //make sure neither of the important two are 0
                        ++mult;
                    }
                    one_one = temp_one;
                    one_two = temp_two;
                    one_three = temp_three;

                    good = false;
                    mult = 0; //because we may not have to actually add anything to make the bottom happy
                    //add some multiple of the top row to the bottom
                    while (!good)
                    {
                        temp_one = one_one * mult + two_one;
                        temp_two = one_two * mult + two_two;
                        temp_three = one_three * mult + two_three;
                        good = (temp_one != 0) && (temp_two != 0); //make sure neither of the important two are 0
                        ++mult;
                    }
                    two_one = temp_one;
                    two_two = temp_two;
                    two_three = temp_three;
                }

                /*
                //old, bad code for the above code
                //add the bottom row to the top
                one_one += two_one;
                one_two += two_two;
                one_three += two_three;
                //add the top row to the bottom
                two_one += one_one;
                two_two += one_two;
                two_three += one_three;
                */

                //hopefully, every cell has something in it (otherwise I may be screwed...)
                //store one_one and divide that row by it to get
                //  [1    num1    num2]
                store_meh = one_one;
                one_one = one_one / store_meh;
                one_two = one_two / store_meh;
                one_three = one_three / store_meh;

                //current state is
                //  [1    num1    num2]
                //  [num3 num4    num5]

                //subtract num3 from num 3, num1 * num 3 from num4, and num2 * num3 from num5
                //yields a bottom row of
                //  [0    num6    num7]
                store_meh = two_one;
                two_one = 0;
                two_two -= (store_meh * one_two);
                two_three -= (store_meh * one_three);

                //current state is
                //  [1    num1    num2]
                //  [0    num3    num4]

                //divide num3 by num3 to get 1 and num4 by num3
                //yields a bottom row of
                //  [0    1   num5]
                store_meh = two_two;
                two_two = 1;
                two_three = two_three / store_meh;

                //current state is below
                //[1    num1    num2]
                //[0    1       num3]

                //subtract num1 from itself and subtract (num3 * num1) from num2
                //yields a top row of
                //[1    0       num4]

                store_meh = one_two;
                one_two = 0;
                one_three -= (store_meh * two_three);

                //current (and final) state is
                //[1    0   num1]
                //[0    1   num2]

                //so, deltaR = num1 and deltaS = num2
                deltaR = one_three;
                deltaS = two_three;
            }

            //get the errors
            double sErr = /*make sure s isn't zero*/(s != 0) ? Math.Abs(deltaS / s)
                : (deltaS != 0) ? 1 : 0; //if s is zero and deltaS isn't, error should be 100%, otherwise we apparently nailed it head on
            double rErr = /*make sure r isn't zero*/(r != 0) ? Math.Abs(deltaR / r)
                : (deltaR != 0) ? 1 : 0; //if r is zero and deltaR isn't, error should be 100%, otherwise we apparently nailed it head on

            //assign all the relevant data
            result.iterR = r;
            result.iterS = s;
            result.iterRError = rErr;
            result.iterSError = sErr;
            result.deltaR = deltaR;
            result.deltaS = deltaS;

            //if latest error is beneath allowedError, calculate roots using solveRSQuadratic and store the data the roots array as well as update necessary instance variables
            //make sure to set res.rootFound to true;
            if (sErr < allowedError && rErr < allowedError)
            {
                result.rootFound = true; //make sure the result knows it found a root

                //solve for the roots and assign them
                Tuple<Tuple<double, double>, Tuple<double, double>> rootPair = solveRSQuadratic(r, s);
                roots[foundRootCount++] = rootPair.Item1;
                roots[foundRootCount++] = rootPair.Item2;

                //if there are more roots to be found, add another iterationresults list
                if(roots.Length - foundRootCount > 0)
                {
                    iterResults.Add(new List<IterationResult>());

                    //calculate / assign the next set of coefficients
                    //supposedly, the next set of coefficients already reside in bArray
                    double[] nextSet = new double[aArray.Length - 2];
                    for(int i = 0; i < nextSet.Length; ++i)
                    {
                        nextSet[i] = bArray[i + 2];
                    }
                    coefficients.Add(nextSet);
                }
                else
                {
                    result.allRootsFound = true;
                }
            }

            //make sure to add the results to the correct iteration set
            if (!result.rootFound)
                iterResults[iterResults.Count - 1].Add(result);
            else
                iterResults[iterResults.Count - 2].Add(result);

            return result;
        }

        //solves a (normal, not r/s) quadratic equation and stores the results in the roots table
        //this only happens if either the user submitted a quadratic to be solved or the highest power of x is even
        private IterationResult performQuadraticSolution()
        {
            IterationResult result = new IterationResult();
            result.dataRelevant = false;
            result.rootFound = true;

            double[] currentEq = coefficients[coefficients.Count - 1];

            //solve for the roots and assign them
            Tuple<Tuple<double, double>, Tuple<double, double>> rootPair = solveNormalQuadratic(currentEq[2], currentEq[1], currentEq[0]);
            roots[foundRootCount++] = rootPair.Item1;
            roots[foundRootCount++] = rootPair.Item2;

            if(roots.Length - foundRootCount == 0)
            {
                result.allRootsFound = true;
            }
            return result;
        }

        //solves a quadratic of the form 0 = x^2 + rx + s and returns its roots
        //is its own thing because reasons
        private Tuple<Tuple<double, double>, Tuple<double,double> > solveRSQuadratic(double r, double s)
        {
            double discriminant = r * r + 4 * s;
            double real1, real2, complex1, complex2;
            if(discriminant > 0)
            {
                real1 = (r + Math.Sqrt(discriminant)) / 2;
                real2 = (r - Math.Sqrt(discriminant)) / 2;
                complex1 = 0;
                complex2 = 0;
            }
            else
            {
                real1 = r / 2;
                real2 = real1;
                complex1 = Math.Sqrt(Math.Abs(discriminant)) / 2;
                complex2 = 0 - complex1;
            }
            Tuple<Tuple<double, double>, Tuple<double, double>> results;
            results = new Tuple<Tuple<double, double>, Tuple<double, double>>(new Tuple<double, double>(real1, complex1), new Tuple<double, double>(real2, complex2));
            return results;
        }

        //solves a normal quadratic of the form 0 = ax^2 + bx + c and returns its roots
        //is its own thing because reasons
        private Tuple<Tuple<double, double>, Tuple<double,double>> solveNormalQuadratic(double a, double b, double c)
        {
            double discriminant = b * b - 4 * a * c;
            double real1, real2, complex1, complex2;
            if(discriminant > 0)
            {
                real1 = (b + Math.Sqrt(discriminant)) / (2 * a);
                real2 = (b - Math.Sqrt(discriminant)) / (2 * a);
                complex1 = 0;
                complex2 = 0;
            }
            else
            {
                real1 = b / (2 * a);
                real2 = real1;
                complex1 = Math.Sqrt(Math.Abs(discriminant)) / (2 * a);
                complex2 = 0 - complex1;
            }
            Tuple<Tuple<double, double>, Tuple<double, double>> results;
            results = new Tuple<Tuple<double, double>, Tuple<double, double>>(new Tuple<double, double>(real1, complex1), new Tuple<double, double>(real2, complex2));
            return results;
        }

        //solves a single, linear equation of the form 0 = a(1)x + a(0) and returns its root / solution
        private Tuple<double, double> solveSingle(double a0, double a1)
        {
            return new Tuple<double, double>((0 - a0) / a1, 0);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SuperSocket.SocketBase.Config;
using SuperSocket.SocketBase.Provider;
using SuperSocket.SocketBase.Metadata;

namespace SuperSocket.SocketEngine
{
    class WorkItemFactoryInfo
    {
        public string ServerType { get; set; }

        public bool IsServerManager { get; set; }

        public StatusInfoAttribute[] StatusInfoMetadata { get; set; }

        public IServerConfig Config { get; set; }

        public IEnumerable<ProviderFactoryInfo> ProviderFactories { get; set; }

        public ProviderFactoryInfo LogFactory { get; set; }

        public ProviderFactoryInfo SocketServerFactory { get; set; }
    }
}


text:
layout: default
title: "Puppet Server: Configuration"
canonical: "/puppetserver/latest/configuration.html"
---

[auth.conf]: /puppet/latest/reference/config_file_auth.html
[`trapperkeeper-authorization`]: https://github.com/puppetlabs/trapperkeeper-authorization
[`puppetserver.conf`]: ./config_file_puppetserver.html
[deprecated]: ./deprecated_features.html

Puppet Server honors almost all settings in `puppet.conf` and should pick them up automatically. However, for some tasks, such as configuring the webserver or an external Certificate Authority (CA), we introduced new Puppet Server-specific configuration files and settings.

These new files and settings are detailed below. For more information on specific differences in Puppet Server's support for `puppet.conf` settings as compared to the Ruby Puppet master software, see the documentation on [`puppet.conf` differences](./puppet_conf_setting_diffs.markdown).

## Configuration Files

All of Puppet Server's new configuration files and settings (with the exception of the [logging config file](#logging)) are in the `conf.d` directory, located by default at `/etc/puppetlabs/puppetserver/conf.d`. These new config files are in the HOCON format, which keeps the basic structure of JSON but is more human-readable. For more information, see the [HOCON documentation](https://github.com/typesafehub/config/blob/master/HOCON.md).

At startup, Puppet Server reads all the `.conf` files in the `conf.d` directory. You must restart Puppet Server for any changes to those files to take effect. The `conf.d` directory contains the following files and settings:

* [`global.conf`](./config_file_global.html)
* [`webserver.conf`](./config_file_webserver.html)
* [`web-routes.conf`](./config_file_web-routes.html)
* [`puppetserver.conf`](./config_file_puppetserver.html)
* [`auth.conf`](./config_file_auth.html)
* [`master.conf`](./config_file_master.html) ([deprecated][])
* [`ca.conf`](./config_file_ca.html) ([deprecated][])

## Logging

All of Puppet Server's logging is routed through the JVM [Logback](http://logback.qos.ch/) library. By default, it logs to `/var/log/puppetlabs/puppetserver/puppetserver-access.log`, the log level is 'INFO', and Puppet Server sends nothing to syslog.

The default Logback configuration file is at `/etc/puppetserver/logback.xml` or `/etc/puppetlabs/puppetserver/logback.xml`. You can edit this file to change the logging behavior, and/or specify a different Logback config file in [`global.conf`](#globalconf). For more information on configuring Logback itself, see the [Logback Configuration Manual](http://logback.qos.ch/manual/configuration.html). Puppet Server picks up changes to logback.xml at runtime, so you don't need to restart the service for changes to take effect.

Puppet Server relies on `logrotate` to manage the log file, and installs a configuration file at `/etc/logrotate.d/puppetserver` or `/etc/logrotate.d/pe-puppetserver`.

### HTTP Traffic

Puppet Server logs HTTP traffic in a format similar to Apache, and to a separate file than the main log file. By default, this is located at `/var/log/puppetlabs/puppetserver/puppetserver-access.log` (open source releases) and `/var/log/pe-puppetserver/puppetserver-access.log` (Puppet Enterprise).

By default, the following information is logged for each HTTP request:

* remote host
* remote log name
* remote user
* date of the logging event
* URL requested
* status code of the request
* response content length
* remote IP address
* local port
* elapsed time to serve the request, in milliseconds

The Logback configuration file is at `/etc/puppetlabs/puppetserver/request-logging.xml`. You can edit this file to change the logging behavior, and/or specify a different Logback configuration file in [`webserver.conf`](#webserverconf) with the [`access-log-config`](https://github.com/puppetlabs/trapperkeeper-webserver-jetty9/blob/master/doc/jetty-config.md#access-log-config) setting. For more information on configuring the logged data, see the [Logback Access Pattern Layout](http://logback.qos.ch/manual/layouts.html#AccessPatternLayout).

### Authorization

Additional logging as it relates `auth.conf` can be enabled in Puppet Server's
`logback.xml` file. By default, only a single message is logged when a request
is denied.

To enable a one-time logging of the parsed and transformed `auth.conf` file add
the following to Puppet Server's `logback.xml` file:

~~~
<logger name="puppetlabs.trapperkeeper.services.authorization.authorization-service" level="DEBUG"/>
~~~

To enable rule-by-rule logging for each request as it's checked for
authorization add the following to Puppet Server's `logback.xml` file:

~~~
<logger name="puppetlabs.trapperkeeper.authorization.rules" level="TRACE"/>
~~~

## Service Bootstrapping

Puppet Server is built on top of our open-source Clojure application framework, [Trapperkeeper](https://github.com/puppetlabs/trapperkeeper). One of the features that Trapperkeeper provides is the ability to enable or disable individual services that an application provides. In Puppet Server, you can use this feature to enable or disable the CA service, by modifying your `bootstrap.cfg` file (usually located in `/etc/puppetserver/bootstrap.cfg`); in that file, you should see some lines that look like this:

~~~
# To enable the CA service, leave the following line uncommented
puppetlabs.services.ca.certificate-authority-service/certificate-authority-service
# To disable the CA service, comment out the above line and uncomment the line below
#puppetlabs.services.ca.certificate-authority-disabled-service/certificate-authority-disabled-service
~~~

In most cases, you'll want the CA service enabled. However, if you're running a multi-master environment or using an external CA, you might want to disable the CA service on some nodes.

## Enabling the Insecure SSLv3 Protocol

Puppet Server usually cannot use SSLv3, because it is disabled by default at the JRE layer. (As of javase 7u75 / 1.7.0_u75. See the [7u75 Update Release Notes](http://www.oracle.com/technetwork/java/javase/7u75-relnotes-2389086.html) for more information.)

You should almost always leave SSLv3 disabled, because it isn't secure anymore; it's been broken since the [POODLE vulnerability](https://blogs.oracle.com/security/entry/information_about_ssl_poodle_vulnerability). If you have clients that can't use newer protocols, you should try to upgrade them instead of downgrading Puppet Server.

However, if you absolutely must, you can allow Puppet Server to negotiate with SSLv3 clients.

To enable SSLv3 at the JRE layer, first create a properties file (e.g. `/etc/sysconfig/puppetserver-properties/java.security`) with the following content:

~~~
# Override properties in $JAVA_HOME/jre/lib/security/java.security
# An empty value enables all algorithms including INSECURE SSLv3
# java should be started with
# -Djava.security.properties=/etc/sysconfig/puppetserver-properties/java.security
# for this file to take effect.
jdk.tls.disabledAlgorithms=
~~~

Once this property file exists, update `JAVA_ARGS`, typically defined in `/etc/sysconfig/puppetserver`, and add the option `-Djava.security.properties=/etc/sysconfig/puppetserver-properties/java.security`. This will configure the JVM to override the `jdk.tls.disabledAlgorithms` property defined in `$JAVA_HOME/jre/lib/security/java.security`. The `puppetserver` service needs to be restarted for this setting to take effect.


text:
var actions = require('./actions/device.json'),
    commandAndEvents = require('./command-and-events');

module.exports = function (url) {
  var create = commandAndEvents.create(url, 'device', actions),
      cache;

  function cacheOrCreate() {
    if(!cache) {
      cache = create('shutdown');
    }

    return cache;
  }

  return { create: cacheOrCreate, get: cacheOrCreate };
};


text:
@extends('layouts.master')

@section('content')

{{{ $priceReport->product->name }}}

        @if($deviation <= 0)

            {{{ number_format(abs($deviation), 2) }}}%

            de ahorro

           $ {{{ number_format($suggestedPrice, 2) }}} sugerido | $ {{{ number_format($priceReport->price, 2) }}} tu precio

        @elseif($deviation > 0)

            {{{ number_format(abs($deviation), 2) }}}%

            de sobreprecio

           $ {{{ number_format($suggestedPrice, 2) }}} sugerido | $ {{{ number_format($priceReport->price, 2) }}} tu precio

        @endif

          <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
          Aprovecha! En Carrefour (a 300m) podés conseguir este producto por $14.24 y ahorrarte un 22.4%.

        @include('widgets.ibp', array('ibp' => $ibp))
        @include('widgets.priceHistory', array('priceHistory' => $priceHistory))

    @include('partials.footer')

@stop

@section('extrajs')

@if ($possibleBusinesses)

          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Ayudanos a ubicarte

Estás en alguno de estos lugares?

            @foreach ($possibleBusinesses as $business)
              hash, $business->id)) }}}" class="list-group-item setBusiness">
                {{{ $business->large_name }}}

            @endforeach

@endif

@stop


text:
package com.example.leopeng.listdemo;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Objects;

/**
 * Created by leopeng on 10/02/2017.
 */

public class BookListAdapter extends BaseAdapter {
    private Context context;
    private ArrayList<Book> books;

    public BookListAdapter(Context context, ArrayList<Book> books) {
        this.context = context;
        this.books = books;
    }

    public int getCount() {
        return books.size();
    }

    public Object getItem(int position) {
        return books.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public static class ViewHolder {
        TextView bookName;
        TextView author;
        TextView bookDescription;
        TextView status;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.simple_list_item, parent, false);
        }

        Book currentBook = (Book) getItem(position);

        // 看一看listview的viewholder实现机制,如何做到itemview优雅的复用,这些findViewById都是不用重复执行的
        TextView textViewBookName = (TextView)convertView.findViewById(R.id.bookName);
        TextView textViewAuthor = (TextView)convertView.findViewById(R.id.author);
        TextView textViewBookDescription = (TextView)convertView.findViewById(R.id.bookDescription);
        TextView textViewStatus = (TextView)convertView.findViewById(R.id.status);

        textViewBookName.setText(currentBook.getBookName());
        textViewAuthor.setText(currentBook.getAuthor());
        textViewBookDescription.setText(currentBook.getBookDescription());
        textViewStatus.setText(currentBook.getStatus());

        return convertView;
    }
}


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.handler;

import java.nio.ByteBuffer;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 *
This class extends the {@link AbstractContentOutputStream}, and forwards all write() and close() calls to a {@link
 * FastContentWriter}. This means that once {@link #close()} has been called, the asynchronous completion of all pending
 * operations can be awaited using the {@link Future} interface of this class. Any asynchronous failure will be
 * rethrown when calling either of the get() methods on this class.

 *
Please notice that the Future implementation of this class will NEVER complete unless {@link #close()} has been
 * called.

 *
 * @author Simon Thoresen Hult
 */
public class FastContentOutputStream extends AbstractContentOutputStream implements Future<Boolean> {

    private final FastContentWriter out;

    /**
     *
Constructs a new FastContentOutputStream that writes into the given {@link ContentChannel}.

     *
     * @param out The ContentChannel to write the stream into.
     */
    public FastContentOutputStream(ContentChannel out) {
        this(new FastContentWriter(out));
    }

    /**
     *
Constructs a new FastContentOutputStream that writes into the given {@link FastContentWriter}.

     *
     * @param out The ContentWriter to write the stream into.
     */
    public FastContentOutputStream(FastContentWriter out) {
        Objects.requireNonNull(out, "out");
        this.out = out;
    }

    @Override
    protected void doFlush(ByteBuffer buf) {
        out.write(buf);
    }

    @Override
    protected void doClose() {
        out.close();
    }

    @Override
    public boolean cancel(boolean mayInterruptIfRunning) {
        return out.cancel(mayInterruptIfRunning);
    }

    @Override
    public boolean isCancelled() {
        return out.isCancelled();
    }

    @Override
    public boolean isDone() {
        return out.isDone();
    }

    @Override
    public Boolean get() throws InterruptedException, ExecutionException {
        return out.get();
    }

    @Override
    public Boolean get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        return out.get(timeout, unit);
    }

    public void addListener(Runnable listener, Executor executor) {
        out.addListener(listener, executor);
    }
}