text:
package org.apache.hadoop.fs.slive;

import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.slive.Constants.OperationType;
import org.apache.hadoop.util.StringUtils;

/**
 * Simple access layer onto of a configuration object that extracts the slive
 * specific configuration values needed for slive running
 */
class ConfigExtractor {

  private static final Log LOG = LogFactory.getLog(ConfigExtractor.class);

  private Configuration config;

  ConfigExtractor(Configuration cfg) {
    this.config = cfg;
  }

  /**
   * @return the wrapped configuration that this extractor will use
   */
  Configuration getConfig() {
    return this.config;
  }

  /**
   * @return the location of where data should be written to
   */
  Path getDataPath() {
    Path base = getBaseDirectory();
    if (base == null) {
      return null;
    }
    return new Path(base, Constants.DATA_DIR);
  }

  /**
   * @return the location of where the reducer should write its data to
   */
  Path getOutputPath() {
    Path base = getBaseDirectory();
    if (base == null) {
      return null;
    }
    return new Path(base, Constants.OUTPUT_DIR);
  }

  /**
   * @param primary
   *          primary the initial string to be used for the value of this
   *          configuration option (if not provided then config and then the
   *          default are used)
   *
   * @return the base directory where output & data should be stored using
   *         primary,config,default (in that order)
   */
  Path getBaseDirectory(String primary) {
    String path = primary;
    if (path == null) {
      path = config.get(ConfigOption.BASE_DIR.getCfgOption());
    }
    if (path == null) {
      path = ConfigOption.BASE_DIR.getDefault();
    }
    if (path == null) {
      return null;
    }
    return new Path(path);
  }

  /**
   * @return the base directory using only config and default values
   */
  Path getBaseDirectory() {
    return getBaseDirectory(null);
  }

  /**
   * @return whether the mapper or reducer should exit when they get there first
   *         error using only config and default values
   */
  boolean shouldExitOnFirstError() {
    return shouldExitOnFirstError(null);
  }

  /**
   * @param primary
   *          primary the initial string to be used for the value of this
   *          configuration option (if not provided then config and then the
   *          default are used)
   *
   * @return the boolean of whether the mapper/reducer should exit when they
   *         first error from primary,config,default (in that order)
   */
  boolean shouldExitOnFirstError(String primary) {
    String val = primary;
    if (val == null) {
      val = config.get(ConfigOption.EXIT_ON_ERROR.getCfgOption());
    }
    if (val == null) {
      return ConfigOption.EXIT_ON_ERROR.getDefault();
    }
    return Boolean.parseBoolean(val);
  }

  /**
   * @return whether the mapper or reducer should wait for truncate recovery
   */
  boolean shouldWaitOnTruncate() {
    return shouldWaitOnTruncate(null);
  }

  /**
   * @param primary
   *          primary the initial string to be used for the value of this
   *          configuration option (if not provided then config and then the
   *          default are used)
   *
   * @return whether the mapper or reducer should wait for truncate recovery
   */
  boolean shouldWaitOnTruncate(String primary) {
    String val = primary;
    if (val == null) {
      val = config.get(ConfigOption.EXIT_ON_ERROR.getCfgOption());
    }
    if (val == null) {
      return ConfigOption.EXIT_ON_ERROR.getDefault();
    }
    return Boolean.parseBoolean(val);
  }

  /**
   * @return the number of reducers to use
   */
  Integer getReducerAmount() {
    // should be slive.reduces
    return getInteger(null, ConfigOption.REDUCES);
  }

  /**
   * @return the number of mappers to use using config and default values for
   *         lookup
   */
  Integer getMapAmount() {
    return getMapAmount(null);
  }

  /**
   * @param primary
   *          primary the initial string to be used for the value of this
   *          configuration option (if not provided then config and then the
   *          default are used)
   * @return the reducer amount to use
   */
  Integer getMapAmount(String primary) {
    return getInteger(primary, ConfigOption.MAPS);
  }

  /**
   * @return the duration in seconds (or null or Integer.MAX for no limit) using
   *         the configuration and default as lookup
   */
  Integer getDuration() {
    return getDuration(null);
  }

  /**
   * @return the duration in milliseconds or null if no limit using config and
   *         default as lookup
   */
  Integer getDurationMilliseconds() {
    Integer seconds = getDuration();
    if (seconds == null || seconds == Integer.MAX_VALUE) {
      return Integer.MAX_VALUE;
    }
    int milliseconds = (seconds * 1000);
    if (milliseconds < 0) {
      milliseconds = 0;
    }
    return milliseconds;
  }

  /**
   * @param primary
   *          primary the initial string to be used for the value of this
   *          configuration option (if not provided then config and then the
   *          default are used)
   * @return the duration in seconds (or null or Integer.MAX for no limit)
   */
  Integer getDuration(String primary) {
    return getInteger(primary, ConfigOption.DURATION);
  }

  /**
   * @return the total number of operations to run using config and default as
   *         lookup
   */
  Integer getOpCount() {
    return getOpCount(null);
  }

  /**
   * @param primary
   *          primary the initial string to be used for the value of this
   *          configuration option (if not provided then config and then the
   *          default are used)
   * @return the total number of operations to run
   */
  Integer getOpCount(String primary) {
    return getInteger(primary, ConfigOption.OPS);
  }

  /**
   * @return the total number of files per directory using config and default as
   *         lookup
   */
  Integer getDirSize() {
    return getDirSize(null);
  }

  /**
   * @param primary
   *          primary the initial string to be used for the value of this
   *          configuration option (if not provided then config and then the
   *          default are used)
   * @return the total number of files per directory
   */
  Integer getDirSize(String primary) {
    return getInteger(primary, ConfigOption.DIR_SIZE);
  }

  /**
   * @param primary
   *          the primary string to attempt to convert into a integer
   * @param opt
   *          the option to use as secondary + default if no primary given
   * @return a parsed integer
   */
  private Integer getInteger(String primary, ConfigOption<Integer> opt) {
    String value = primary;
    if (value == null) {
      value = config.get(opt.getCfgOption());
    }
    if (value == null) {
      return opt.getDefault();
    }
    return Integer.parseInt(value);
  }

  /**
   * @return the total number of files allowed using configuration and default
   *         for lookup
   */
  Integer getTotalFiles() {
    return getTotalFiles(null);
  }

  /**
   * @param primary
   *          primary the initial string to be used for the value of this
   *          configuration option (if not provided then config and then the
   *          default are used)
   * @return the total number of files allowed
   */
  Integer getTotalFiles(String primary) {
    return getInteger(primary, ConfigOption.FILES);
  }

  /**
   * @param primary
   *          primary the initial string to be used for the value of this
   *          configuration option (if not provided then config and then the
   *          default are used)
   * @return the random seed start point or null if none
   */
  Long getRandomSeed(String primary) {
    String seed = primary;
    if (seed == null) {
      seed = config.get(ConfigOption.RANDOM_SEED.getCfgOption());
    }
    if (seed == null) {
      return null;
    }
    return Long.parseLong(seed);
  }

  /**
   * @return the random seed start point or null if none using config and then
   *         default as lookup
   */
  Long getRandomSeed() {
    return getRandomSeed(null);
  }

  /**
   * @return the result file location or null if none using config and then
   *         default as lookup
   */
  String getResultFile() {
    return getResultFile(null);
  }

  /**
   * Gets the grid queue name to run on using config and default only
   *
   * @return String
   */
  String getQueueName() {
    return getQueueName(null);
  }

  /**
   * Gets the grid queue name to run on using the primary string or config or
   * default
   *
   * @param primary
   *
   * @return String
   */
  String getQueueName(String primary) {
    String q = primary;
    if (q == null) {
      q = config.get(ConfigOption.QUEUE_NAME.getCfgOption());
    }
    if (q == null) {
      q = ConfigOption.QUEUE_NAME.getDefault();
    }
    return q;
  }

  /**
   * @param primary
   *          primary the initial string to be used for the value of this
   *          configuration option (if not provided then config and then the
   *          default are used)
   * @return the result file location
   */
  String getResultFile(String primary) {
    String fn = primary;
    if (fn == null) {
      fn = config.get(ConfigOption.RESULT_FILE.getCfgOption());
    }
    if (fn == null) {
      fn = ConfigOption.RESULT_FILE.getDefault();
    }
    return fn;
  }

  /**
   * @param primary
   *          primary the initial string to be used for the value of this
   *          configuration option (if not provided then config and then the
   *          default are used)
   * @return the integer range allowed for the block size
   */
  Range<Long> getBlockSize(String primary) {
    return getMinMaxBytes(ConfigOption.BLOCK_SIZE, primary);
  }

  /**
   * @return the integer range allowed for the block size using config and
   *         default for lookup
   */
  Range<Long> getBlockSize() {
    return getBlockSize(null);
  }

  /**
   * @param cfgopt
   *          the configuration option to use for config and default lookup
   * @param primary
   *          the initial string to be used for the value of this configuration
   *          option (if not provided then config and then the default are used)
   * @return the parsed short range from primary, config, default
   */
  private Range<Short> getMinMaxShort(ConfigOption<Short> cfgopt, String primary) {
    String sval = primary;
    if (sval == null) {
      sval = config.get(cfgopt.getCfgOption());
    }
    Range<Short> range = null;
    if (sval != null) {
      String pieces[] = Helper.getTrimmedStrings(sval);
      if (pieces.length == 2) {
        String min = pieces[0];
        String max = pieces[1];
        short minVal = Short.parseShort(min);
        short maxVal = Short.parseShort(max);
        if (minVal > maxVal) {
          short tmp = minVal;
          minVal = maxVal;
          maxVal = tmp;
        }
        range = new Range<Short>(minVal, maxVal);
      }
    }
    if (range == null) {
      Short def = cfgopt.getDefault();
      if (def != null) {
        range = new Range<Short>(def, def);
      }
    }
    return range;
  }

  /**
   * @param cfgopt
   *          the configuration option to use for config and default lookup
   * @param primary
   *          the initial string to be used for the value of this configuration
   *          option (if not provided then config and then the default are used)
   * @return the parsed long range from primary, config, default
   */
  private Range<Long> getMinMaxLong(ConfigOption<Long> cfgopt, String primary) {
    String sval = primary;
    if (sval == null) {
      sval = config.get(cfgopt.getCfgOption());
    }
    Range<Long> range = null;
    if (sval != null) {
      String pieces[] = Helper.getTrimmedStrings(sval);
      if (pieces.length == 2) {
        String min = pieces[0];
        String max = pieces[1];
        long minVal = Long.parseLong(min);
        long maxVal = Long.parseLong(max);
        if (minVal > maxVal) {
          long tmp = minVal;
          minVal = maxVal;
          maxVal = tmp;
        }
        range = new Range<Long>(minVal, maxVal);
      }
    }
    if (range == null) {
      Long def = cfgopt.getDefault();
      if (def != null) {
        range = new Range<Long>(def, def);
      }
    }
    return range;
  }

  /**
   * @param cfgopt
   *          the configuration option to use for config and default lookup
   * @param primary
   *          the initial string to be used for the value of this configuration
   *          option (if not provided then config and then the default are used)
   * @return the parsed integer byte range from primary, config, default
   */
  private Range<Long> getMinMaxBytes(ConfigOption<Long> cfgopt, String primary) {
    String sval = primary;
    if (sval == null) {
      sval = config.get(cfgopt.getCfgOption());
    }
    Range<Long> range = null;
    if (sval != null) {
      String pieces[] = Helper.getTrimmedStrings(sval);
      if (pieces.length == 2) {
        String min = pieces[0];
        String max = pieces[1];
        long tMin = StringUtils.TraditionalBinaryPrefix.string2long(min);
        long tMax = StringUtils.TraditionalBinaryPrefix.string2long(max);
        if (tMin > tMax) {
          long tmp = tMin;
          tMin = tMax;
          tMax = tmp;
        }
        range = new Range<Long>(tMin, tMax);
      }
    }
    if (range == null) {
      Long def = cfgopt.getDefault();
      if (def != null) {
        range = new Range<Long>(def, def);
      }
    }
    return range;
  }

  /**
   * @param primary
   *          the initial string to be used for the value of this configuration
   *          option (if not provided then config and then the default are used)
   * @return the replication range
   */
  Range<Short> getReplication(String primary) {
    return getMinMaxShort(ConfigOption.REPLICATION_AM, primary);
  }

  /**
   * @return the replication range using config and default for lookup
   */
  Range<Short> getReplication() {
    return getReplication(null);
  }

  /**
   * @return the map of operations to perform using config (percent may be null
   *         if unspecified)
   */
  Map<OperationType, OperationData> getOperations() {
    Map<OperationType, OperationData> operations = new HashMap<OperationType, OperationData>();
    for (OperationType type : OperationType.values()) {
      String opname = type.lowerName();
      String keyname = String.format(Constants.OP, opname);
      String kval = config.get(keyname);
      if (kval == null) {
        continue;
      }
      operations.put(type, new OperationData(kval));
    }
    return operations;
  }

  /**
   * @param primary
   *          the initial string to be used for the value of this configuration
   *          option (if not provided then config and then the default are used)
   * @return the append byte size range (or null if none)
   */
  Range<Long> getAppendSize(String primary) {
    return getMinMaxBytes(ConfigOption.APPEND_SIZE, primary);
  }

  /**
   * @return the append byte size range (or null if none) using config and
   *         default for lookup
   */
  Range<Long> getAppendSize() {
    return getAppendSize(null);
  }

  /**
   * @param primary
   *          the initial string to be used for the value of this configuration
   *          option (if not provided then config and then the default are used)
   * @return the truncate byte size range (or null if none)
   */
  Range<Long> getTruncateSize(String primary) {
    return getMinMaxBytes(ConfigOption.TRUNCATE_SIZE, primary);
  }

  /**
   * @return the truncate byte size range (or null if none) using config and
   *         default for lookup
   */
  Range<Long> getTruncateSize() {
    return getTruncateSize(null);
  }

  /**
   * @param primary
   *          the initial string to be used for the value of this configuration
   *          option (if not provided then config and then the default are used)
   * @return the sleep range (or null if none)
   */
  Range<Long> getSleepRange(String primary) {
    return getMinMaxLong(ConfigOption.SLEEP_TIME, primary);
  }

  /**
   * @return the sleep range (or null if none) using config and default for
   *         lookup
   */
  Range<Long> getSleepRange() {
    return getSleepRange(null);
  }

  /**
   * @param primary
   *          the initial string to be used for the value of this configuration
   *          option (if not provided then config and then the default are used)
   * @return the write byte size range (or null if none)
   */
  Range<Long> getWriteSize(String primary) {
    return getMinMaxBytes(ConfigOption.WRITE_SIZE, primary);
  }

  /**
   * @return the write byte size range (or null if none) using config and
   *         default for lookup
   */
  Range<Long> getWriteSize() {
    return getWriteSize(null);
  }

  /**
   * Returns whether the write range should use the block size range
   *
   * @return true|false
   */
  boolean shouldWriteUseBlockSize() {
    Range<Long> writeRange = getWriteSize();
    if (writeRange == null
        || (writeRange.getLower() == writeRange.getUpper() && (writeRange
            .getUpper() == Long.MAX_VALUE))) {
      return true;
    }
    return false;
  }

  /**
   * Returns whether the append range should use the block size range
   *
   * @return true|false
   */
  boolean shouldAppendUseBlockSize() {
    Range<Long> appendRange = getAppendSize();
    if (appendRange == null
        || (appendRange.getLower() == appendRange.getUpper() && (appendRange
            .getUpper() == Long.MAX_VALUE))) {
      return true;
    }
    return false;
  }

  /**
   * Returns whether the truncate range should use the block size range
   *
   * @return true|false
   */
  boolean shouldTruncateUseBlockSize() {
    Range<Long> truncateRange = getTruncateSize();
    if (truncateRange == null
        || (truncateRange.getLower() == truncateRange.getUpper()
            && (truncateRange.getUpper() == Long.MAX_VALUE))) {
      return true;
    }
    return false;
  }

  /**
   * Returns whether the read range should use the entire file
   *
   * @return true|false
   */
  boolean shouldReadFullFile() {
    Range<Long> readRange = getReadSize();
    if (readRange == null
        || (readRange.getLower() == readRange.getUpper() && (readRange
            .getUpper() == Long.MAX_VALUE))) {
      return true;
    }
    return false;
  }

  /**
   * @param primary
   *          the initial string to be used for the value of this configuration
   *          option (if not provided then config and then the default are used)
   * @return the read byte size range (or null if none)
   */
  Range<Long> getReadSize(String primary) {
    return getMinMaxBytes(ConfigOption.READ_SIZE, primary);
  }

  /**
   * Gets the bytes per checksum (if it exists or null if not)
   *
   * @return Long
   */
  Long getByteCheckSum() {
    String val = config.get(Constants.BYTES_PER_CHECKSUM);
    if(val == null) {
      return null;
    }
    return Long.parseLong(val);
  }

  /**
   * @return the read byte size range (or null if none) using config and default
   *         for lookup
   */
  Range<Long> getReadSize() {
    return getReadSize(null);
  }

  /**
   * Dumps out the given options for the given config extractor
   *
   * @param cfg
   *          the config to write to the log
   */
  static void dumpOptions(ConfigExtractor cfg) {
    if (cfg == null) {
      return;
    }
    LOG.info("Base directory = " + cfg.getBaseDirectory());
    LOG.info("Data directory = " + cfg.getDataPath());
    LOG.info("Output directory = " + cfg.getOutputPath());
    LOG.info("Result file = " + cfg.getResultFile());
    LOG.info("Grid queue = " + cfg.getQueueName());
    LOG.info("Should exit on first error = " + cfg.shouldExitOnFirstError());
    {
      String duration = "Duration = ";
      if (cfg.getDurationMilliseconds() == Integer.MAX_VALUE) {
        duration += "unlimited";
      } else {
        duration += cfg.getDurationMilliseconds() + " milliseconds";
      }
      LOG.info(duration);
    }
    LOG.info("Map amount = " + cfg.getMapAmount());
    LOG.info("Reducer amount = " + cfg.getReducerAmount());
    LOG.info("Operation amount = " + cfg.getOpCount());
    LOG.info("Total file limit = " + cfg.getTotalFiles());
    LOG.info("Total dir file limit = " + cfg.getDirSize());
    {
      String read = "Read size = ";
      if (cfg.shouldReadFullFile()) {
        read += "entire file";
      } else {
        read += cfg.getReadSize() + " bytes";
      }
      LOG.info(read);
    }
    {
      String write = "Write size = ";
      if (cfg.shouldWriteUseBlockSize()) {
        write += "blocksize";
      } else {
        write += cfg.getWriteSize() + " bytes";
      }
      LOG.info(write);
    }
    {
      String append = "Append size = ";
      if (cfg.shouldAppendUseBlockSize()) {
        append += "blocksize";
      } else {
        append += cfg.getAppendSize() + " bytes";
      }
      LOG.info(append);
    }
    {
      String bsize = "Block size = ";
      bsize += cfg.getBlockSize() + " bytes";
      LOG.info(bsize);
    }
    if (cfg.getRandomSeed() != null) {
      LOG.info("Random seed = " + cfg.getRandomSeed());
    }
    if (cfg.getSleepRange() != null) {
      LOG.info("Sleep range = " + cfg.getSleepRange() + " milliseconds");
    }
    LOG.info("Replication amount = " + cfg.getReplication());
    LOG.info("Operations are:");
    NumberFormat percFormatter = Formatter.getPercentFormatter();
    Map<OperationType, OperationData> operations = cfg.getOperations();
    for (OperationType type : operations.keySet()) {
      String name = type.name();
      LOG.info(name);
      OperationData opInfo = operations.get(type);
      LOG.info(" " + opInfo.getDistribution().name());
      if (opInfo.getPercent() != null) {
        LOG.info(" " + percFormatter.format(opInfo.getPercent()));
      } else {
        LOG.info(" ???");
      }
    }
  }

}


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

@import timetopaytaxpayer.cor.model.Debit
@import partials.direct_debit_fields
@import helpers.forms.submit
@import uk.gov.hmrc.selfservicetimetopay.models.ArrangementDirectDebit
@import ssttpcalculator.model.PaymentSchedule
@import model._

@this(
  main: views.html.main,
  viewsHelpers: views.ViewsHelpers
)

@(
        debits: Seq[Debit],
        schedule: PaymentSchedule,
        ddForm: Form[ArrangementDirectDebit],
        isBankError: Boolean = false,
        loggedIn: Boolean = true)(implicit
        messages: play.api.i18n.Messages,
        request: Request[_],
        appConfig: config.AppConfig
)

@main(
    title = Messages("ssttp.arrangement.direct-debit.form.title"),
    hasErrors = ddForm.hasErrors,
    maybeSidebarLinks =  None,
    backButtonUrl = Some(ssttpdirectdebit.routes.DirectDebitController.aboutBankAccount())
) {
    @if(ddForm.hasErrors) {
        @if(isBankError) {
            @viewsHelpers.errorSummary(Messages("ssttp.direct-debit.form.bank-not-found-heading"), ddForm)
        } else {
            @viewsHelpers.errorSummary(Messages("ssttp.arrangement.direct-debit.form.error.summary.title"), ddForm)
        }
    }

@Messages("ssttp.arrangement.direct-debit.form.title")

       @viewsHelpers.form(ssttpdirectdebit.routes.DirectDebitController.submitDirectDebit, 'autoComplete -> "off") {

        <fieldset class="govuk-fieldset">
            <legend>Enter your banking details</legend>
            @viewsHelpers.direct_debit_fields(ddForm, ddForm("accountName"), ddForm("sortCode"), ddForm("accountNumber"))
        </fieldset>

        @viewsHelpers.continue(Messages("ssttp.arrangement.direct-debit.form.submit"))
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace Network
{
  namespace Http
  {
    namespace Request
    {
      namespace Header
      {
        DECLARE_STRING_CONSTANT(Accept, Accept)
        DECLARE_STRING_CONSTANT(AcceptCharset, Accept-Charset)
        DECLARE_STRING_CONSTANT(AcceptEncoding, Accept-Encoding)
        DECLARE_STRING_CONSTANT(AcceptLanguage, Accept-Language)
        DECLARE_STRING_CONSTANT(AcceptDatetime, Accept-Datetime)
        DECLARE_STRING_CONSTANT(Authorization, Authorization)
        DECLARE_STRING_CONSTANT(CacheControl, Cache-Control)
        DECLARE_STRING_CONSTANT(Connection, Connection)
        DECLARE_STRING_CONSTANT(Cookie, Cookie)
        DECLARE_STRING_CONSTANT(ContentLength, Content-Length)
        DECLARE_STRING_CONSTANT(ContentMD5, Content-MD5)
        DECLARE_STRING_CONSTANT(ContentType, Content-Type)
        DECLARE_STRING_CONSTANT(Date, Date)
        DECLARE_STRING_CONSTANT(Expect, Expect)
        DECLARE_STRING_CONSTANT(From, From)
        DECLARE_STRING_CONSTANT(Host, Host)
        DECLARE_STRING_CONSTANT(IfMatch, If-Match)
        DECLARE_STRING_CONSTANT(IfModifiedSince, If-Modified-Since)
        DECLARE_STRING_CONSTANT(IfNoneMatch, If-None-Match)
        DECLARE_STRING_CONSTANT(IfRange, If-Range)
        DECLARE_STRING_CONSTANT(IfUnmodifiedSince, If-Unmodified-Since)
        DECLARE_STRING_CONSTANT(MaxForwards, Max-Forwards)
        DECLARE_STRING_CONSTANT(Origin, Origin)
        DECLARE_STRING_CONSTANT(Pragma, Pragma)
        DECLARE_STRING_CONSTANT(ProxyAuthorization, Proxy-Authorization)
        DECLARE_STRING_CONSTANT(Range, Range)
        DECLARE_STRING_CONSTANT(Referer, Referer)
        DECLARE_STRING_CONSTANT(TE, TE)
        DECLARE_STRING_CONSTANT(UserAgent, User-Agent)
        DECLARE_STRING_CONSTANT(Via, Via)
        DECLARE_STRING_CONSTANT(Warning, Warning)
      }

    }

    namespace Response
    {

      namespace Header
      {
        DECLARE_STRING_CONSTANT(AccessControlAllowOrigin, Access-Control-Allow-Origin)
        DECLARE_STRING_CONSTANT(AcceptRanges, Accept-Ranges)
        DECLARE_STRING_CONSTANT(Age, Age)
        DECLARE_STRING_CONSTANT(Allow, Allow)
        DECLARE_STRING_CONSTANT(CacheControl, Cache-Control)
        DECLARE_STRING_CONSTANT(Connection, Connection)
        DECLARE_STRING_CONSTANT(ContentEncoding, Content-Encoding)
        DECLARE_STRING_CONSTANT(ContentLanguage, Content-Language)
        DECLARE_STRING_CONSTANT(ContentLength, Content-Length)
        DECLARE_STRING_CONSTANT(ContentLocation, Content-Location)
        DECLARE_STRING_CONSTANT(ContentMD5, Content-MD5)
        DECLARE_STRING_CONSTANT(ContentRange, Content-Range)
        DECLARE_STRING_CONSTANT(ContentType, Content-Type)
        DECLARE_STRING_CONSTANT(Date, Date)
        DECLARE_STRING_CONSTANT(ETag, ETag)
        DECLARE_STRING_CONSTANT(Expires, Expires)
        DECLARE_STRING_CONSTANT(LastModified, Last-Modified)
        DECLARE_STRING_CONSTANT(Link, Link)
        DECLARE_STRING_CONSTANT(Location, Location)
        DECLARE_STRING_CONSTANT(P3P, P3P)
        DECLARE_STRING_CONSTANT(Pragma, Pragma)
        DECLARE_STRING_CONSTANT(ProxyAuthenticate, Proxy-Authenticate)
        DECLARE_STRING_CONSTANT(Refresh, Refresh)
        DECLARE_STRING_CONSTANT(RetryAfter, Retry-After)
        DECLARE_STRING_CONSTANT(Server, Server)
        DECLARE_STRING_CONSTANT(SetCookie, Set-Cookie)
        DECLARE_STRING_CONSTANT(Status, Status)
        DECLARE_STRING_CONSTANT(StrictTransportSecurity, Strict-Transport-Security)
        DECLARE_STRING_CONSTANT(Trailer, Trailer)
        DECLARE_STRING_CONSTANT(TransferEncoding, Transfer-Encoding)
        DECLARE_STRING_CONSTANT(Upgrade, Upgrade)
        DECLARE_STRING_CONSTANT(Vary, Vary)
        DECLARE_STRING_CONSTANT(Via, Via)
        DECLARE_STRING_CONSTANT(Warning, Warning)
        DECLARE_STRING_CONSTANT(WWWAuthenticate, WWW-Authenticate)
      }
    }
  }
}

#endif  // !__NETWORK_HTTP_HEADERS_H__


text:
layout: article
title: "Weekly Word: Malinger"
date: 2007-05-02 08:35
cats: [english]
---
This is the first new word I've found in a while that I'd actually use regularly. Malinger: "To feign illness or other incapacity in order to avoid duty or work."

I can be quite the malingerer. ;) And yes, malingerer really is the noun form of malinger. This word just keeps getting better and better!

It comes from the French word malingrer "to suffer", and the Online Etymology Dictionary says that the meaning "to feign illness to avoid work" may come from the "notion of beggars with sham sores."


text:
package com.yahoo.labs.samoa.topology.impl;

import org.apache.s4.core.App;
import org.apache.s4.core.ProcessingElement;

import com.yahoo.labs.samoa.core.ContentEvent;
import com.yahoo.labs.samoa.core.EntranceProcessor;
import com.yahoo.labs.samoa.topology.EntranceProcessingItem;
import com.yahoo.labs.samoa.topology.Stream;

// TODO adapt this entrance processing item to connect to external streams so the application doesnt need to use an AdapterApp

public class S4EntranceProcessingItem extends ProcessingElement implements EntranceProcessingItem {

    private EntranceProcessor entranceProcessor;
    // private S4DoTask app;
    private int parallelism;
    protected Stream outputStream;

    /**
     * Constructor of an S4 entrance processing item.
     *
     * @param app
     *            : S4 application
     */
    public S4EntranceProcessingItem(EntranceProcessor entranceProcessor, App app) {
        super(app);
        this.entranceProcessor = entranceProcessor;
        // this.app = (S4DoTask) app;
        // this.setSingleton(true);
    }

    public void setParallelism(int parallelism) {
        this.parallelism = parallelism;
    }

    public int getParallelism() {
        return this.parallelism;
    }

    @Override
    public EntranceProcessor getProcessor() {
        return this.entranceProcessor;
    }

    //
    // @Override
    // public void put(Instance inst) {
    // // do nothing
    // // may not needed
    // }

    @Override
    protected void onCreate() {
        // was commented
        if (this.entranceProcessor != null) {
            // TODO revisit if we need to change it to a clone() call
            this.entranceProcessor = (EntranceProcessor) this.entranceProcessor.newProcessor(this.entranceProcessor);
            this.entranceProcessor.onCreate(Integer.parseInt(getId()));
        }
    }

    @Override
    protected void onRemove() {
        // do nothing
    }

    //
    // /**
    // * Sets the entrance processing item processor.
    // *
    // * @param processor
    // */
    // public void setProcessor(Processor processor) {
    // this.entranceProcessor = processor;
    // }

    @Override
    public void setName(String name) {
        super.setName(name);
    }

    @Override
    public EntranceProcessingItem setOutputStream(Stream stream) {
        if (this.outputStream != null)
            throw new IllegalStateException("Output stream for an EntrancePI sohuld be initialized only once");
        this.outputStream = stream;
        return this;
    }

    public boolean injectNextEvent() {
        if (entranceProcessor.hasNext()) {
            ContentEvent nextEvent = this.entranceProcessor.nextEvent();
            outputStream.put(nextEvent);
            return entranceProcessor.hasNext();
        } else
            return false;
        // return !nextEvent.isLastEvent();
    }
}


text:
*************
Query Builder
*************

Query builder makes it easier to working with SQL statements.

Select
======

Query builder provide a chainable API to build SQL query like a charm.

.. code-block:: php

    <?php
    $users = $db->builder()
        ->select('username, email')
        ->from('user')
        ->where('level > :level', array(':level' => $level))
        ->limit(10)
        ->orderBy('username ASC')
        ->queryAll();

In addition to ``queryAll`` to fetch all rows, you can use:

- ``queryRow`` to get the first row
- ``queryValue`` to get the first column of first row (the value)
- ``queryColumn`` to get the first column of all rows

Parameter Binding
-----------------

Both named placeholder and question mark placeholder are supported:

.. code-block:: php

    <?php
    $db->builder()
        ->where('username = ? and password = ?', [$name, $password]);

    $db->builder()
        ->where('username = :name and password = :password', [
            ':name' => $name,
            ':password' => $password
        ]);

Condition
---------

TODO

Insert
======

.. code-block:: php

    <?php
    $db->builder()
        ->insert('user', array(
            'userame' => 'test',
            'email' => 'test@example.com',
        ));

Update
======

.. code-block:: php

    <?php
    $db->builder()
        ->update(
            'user',
            array(
                'email' => 'test1@example.com',
            ), // columns to be updated
            'username = :username', // conditions
            array(':username' => $username) // params
        );

Delete
======

.. code-block:: php

    $db->builder()
        ->delete(
            'user',
            'username = :username',
            array(':username' => $username)
        );


text:
import { Header, Wrap } from './components/toolbar';
export { Header, Wrap };


text:
using Superscribe.Models;

namespace SuperGlue.Web.Routing.Superscribe
{
    public class Guid : ParamNode<System.Guid>
    {
        public Guid(string name) : base(name)
        {
        }

        public static explicit operator Guid(string name)
        {
            return new Guid(name);
        }
    }
}


text:
<?php
if (! defined ( 'PHPUnit_MAIN_METHOD' )) {
	define ( 'PHPUnit_MAIN_METHOD', 'Microsoft_WindowsAzure_BlobStreamTest::main' );
}

require_once 'PHPUnit/Framework.php';

require_once 'Microsoft/WindowsAzure/Storage/Blob.php';

class Microsoft_WindowsAzure_BlobStreamTest extends PHPUnit_Framework_TestCase {
	static $path;

	protected static $uniqId = 0;

	protected $_tempContainers = array ();

	public function __construct() {
		require_once 'TestConfiguration.php';
		self::$path = dirname ( __FILE__ ) . '/datas/';
		self::$uniqId = mt_rand ( 0, 10000 );
	}

	protected function setUp() {

	}

	protected function tearDown() {
		if (count ( $this->_tempContainers ) > 0) {
			$storageClient = $this->_createStorageClient ();
			foreach ( $this->_tempContainers as $container )
				try {
					$storageClient->deleteContainer ( $container );
				} catch ( Exception $e ) {
					// ignore
				}

			$this->_tempContainers = array ();
		}
	}

	protected function getContainerName() {
		self::$uniqId ++;
		$name = "qa-test-container-" . self::$uniqId;
		$this->_tempContainers [] = $name;
		return $name;
	}

	public static function main() {
		$suite = new PHPUnit_Framework_TestSuite ( "Microsoft_WindowsAzure_BlobStreamTest" );
		$result = PHPUnit_TextUI_TestRunner::run ( $suite );
	}

	protected function _createStorageClient() {
		return new Microsoft_WindowsAzure_Storage_Blob ( BLOB_HOST, STORAGE_ACCOUNT, STORAGE_KEY, false, Microsoft_WindowsAzure_RetryPolicy::retryN ( 10, 250 ) );
	}

	protected function _createTempFile($content) {
		$fileName = tempnam ( '', 'tst' );
		$fp = fopen ( $fileName, 'w' );
		fwrite ( $fp, $content );
		fclose ( $fp );

		return $fileName;
	}

	protected function _expectException($e, $message) {
		$this->assertNotNull ( $e, $message );
		$this->_assertExceptionMessageContain ( $e, $message );
	}

	/**
	 * Test read file
	 */
	public function testReadFile() {

		$containerName = $this->getContainerName ();
		$fileName = 'azure://' . $containerName . '/test.txt';

		$storageClient = $this->_createStorageClient ();
		$storageClient->registerStreamWrapper ();

		$storageClient->createContainer ( $containerName );
		$storageClient->putBlob ( $containerName, 'test.txt', self::$path . "simple_blob.txt" );
		$fileContent = file_get_contents ( self::$path . "simple_blob.txt" );
		//		$fh = fopen ( $fileName, 'w' );
		//		fwrite ( $fh, $fileContent );
		//		fclose ( $fh );

		// read whole file using file_get_contents
		$result = file_get_contents ( $fileName );
		$this->assertEquals ( $fileContent, $result );

		// read line by line
		$fh = fopen ( $fileName, 'r' );
		$lines = explode ( "\n", $fileContent );
		foreach ( $lines as $line ) {
			$result = fgets ( $fh );
			$this->assertEquals ( $line, str_replace ( "\n", "", $result ) );
		}
		fclose ( $fh );

		// read lines using file
		$fileLines = file ( $fileName );
		$this->assertEquals ( count ( $lines ), count ( $fileLines ) );
		for($i = 0; $i < count ( $lines ); $i ++) {
			$this->assertEquals ( $lines [$i], str_replace ( "\n", "", $fileLines [$i] ) );
		}

		// read the whole file using fread
		$fh = fopen ( $fileName, 'r' );
		$result = fread ( $fh, 1000 );
		fclose ( $fh );
		$this->assertEquals ( $fileContent, $result );

		$storageClient->unregisterStreamWrapper ();
	}

	public function testReadFile_NotExists() {
		$storageClient = $this->_createStorageClient ();
		$storageClient->registerStreamWrapper ();
		$containerName = $this->getContainerName ();
		try {
			$fileName = 'azure://' . $containerName . '/test.txt';
			file_get_contents ( $fileName );
		} catch ( Exception $e ) {
			$this->_assertExceptionMessageContain ( $e, "The specified container does not exist." );
		}

		$storageClient->createContainer ( $containerName );

		try {
			// missing blob name
			$fileName = 'azure://' . $containerName;
			file_get_contents ( $fileName );
		} catch ( Exception $e ) {
			$this->_assertExceptionMessageContain ( $e, "The specified blob does not exist." );
		}

		try {
			$fileName = 'azure://' . $containerName . '/test.txt';
			file_get_contents ( $fileName );
		} catch ( Exception $e ) {
			$this->_assertExceptionMessageContain ( $e, "The specified blob does not exist." );
		}

		$storageClient->unregisterStreamWrapper ();
	}

	protected function _assertExceptionMessageContain($ex, $message) {
		$this->assertTrue ( strpos ( $ex->getMessage (), $message ) !== false );
	}
	//Test eof()
	public function testEndOfFile() {
		$containerName = $this->getContainerName ();
		$fileName = 'azure://' . $containerName . '/test.txt';

		$storageClient = $this->_createStorageClient ();
		$storageClient->registerStreamWrapper ();

		$storageClient->createContainer ( $containerName );
		$storageClient->putBlob ( $containerName, 'test.txt', self::$path . "simple_blob.txt" );

		$fh = fopen ( $fileName, 'r' );
		fread ( $fh, 10 );

		$VerifyEnd = feof ( $fh );
		$this->assertFalse ( $VerifyEnd );

		//the length of blob content is 44.
		fread ( $fh, 34 );
		$VerifyEnd = feof ( $fh );
		$this->assertTrue ( $VerifyEnd );

		fclose ( $fh );
	}

	//Test tell
	public function testTell() {
		$containerName = $this->getContainerName ();
		$fileName = 'azure://' . $containerName . '/test.txt';

		$storageClient = $this->_createStorageClient ();
		$storageClient->registerStreamWrapper ();

		$storageClient->createContainer ( $containerName );
		$storageClient->putBlob ( $containerName, 'test.txt', self::$path . "simple_blob.txt" );

		$fh = fopen ( $fileName, 'r' );

		$position = ftell ( $fh );
		$this->assertEquals ( 0, $position );

		fread ( $fh, 10 );
		$position = ftell ( $fh );
		$this->assertEquals ( 10, $position );

		fread ( $fh, 34 );
		$position = ftell ( $fh );
		$this->assertEquals ( 44, $position );

		fread ( $fh, 1 );
		$position = ftell ( $fh );
		$this->assertEquals ( 44, $position );

		fclose ( $fh );
	}

	//Test seek. when invoke fseek(), here all rerurn -1. operation failed.
	public function testSeek() {
		$fileContent = "test seek file";
		$containerName = $this->getContainerName ();
		$fileName = 'azure://' . $containerName . '/testseek.txt';

		$storageClient = $this->_createStorageClient ();
		$storageClient->registerStreamWrapper ();
		//file_put_contents ( $fileName, $fileContent );
		$localFile = $this->_createTempFile ( $fileContent );
		$storageClient->createContainer ( $containerName );
		$storageClient->putBlob ( $containerName, "testseek.txt", $localFile );

		$fh = fopen ( $fileName, 'r' );

		$curpos = ftell ( $fh );
		$this->assertEquals ( 0, $curpos );

		//whence: 0 = SEEK_SET, the head of file
		fseek ( $fh, 5, SEEK_SET );
		$curpos = ftell ( $fh );
		$this->assertEquals ( 5, $curpos );

		//whence: 1 = SEEK_CUR, the current position of file
		fread ( $fh, 2 );
		fseek ( $fh, 1, SEEK_CUR );
		$curpos = ftell ( $fh );
		$this->assertEquals ( 8, $curpos );

		//whence: 2 = SEEK_END, the end of file
		fseek ( $fh, - 5, SEEK_END );
		$curpos = ftell ( $fh );
		$this->assertEquals ( strlen ( $fileContent ) - 5, $curpos );

		fclose ( $fh );
	}

	//Test stat. return an array.
	public function testStat() {
		$fileContent = "test stat file";
		$containerName = $this->getContainerName ();
		$fileName = 'azure://' . $containerName . '/teststat.txt';

		$storageClient = $this->_createStorageClient ();
		$storageClient->registerStreamWrapper ();
		file_put_contents ( $fileName, $fileContent );

		$fh = fopen ( $fileName, 'r' );
		$array = fstat ( $fh );

		$this->assertNotNull ( $array );
		$this->assertEquals ( $array ["mode"], 0100000 );
		$this->assertTrue ( $array ["ctime"] > 0 );
		$this->assertTrue ( $array ["ctime"] <= time () );
		$this->assertTrue ( $array ["mtime"] > 0 );
		$this->assertTrue ( $array ["mtime"] <= time () );
		$this->assertTrue ( $array ["atime"], 0 );
		$this->assertEquals ( strlen ( $fileContent ), $array ["size"] );

		fclose ( $fh );

		// The same data should be available via url_stat().
		$stat_via_url_stat = stat ( $fileName );
		$this->assertIdentical ( $stat_via_url_stat, $array );

		// In addition, stating a non existing file should return false.
		$stat_non_existing = stat ( 'azure://non-existing' );
		$this->assertTrue ( $stat_non_existing === false );
	}

	/**
	 * Flush seems not work here.
	 *
	 */
	public function testFlush() {
		$fileContent = "test flush file";
		$containerName = $this->getContainerName ();
		$fileName = 'azure://' . $containerName . '/testflush.txt';

		$storageClient = $this->_createStorageClient ();
		$storageClient->registerStreamWrapper ();
		file_put_contents ( $fileName, $fileContent );

		$newContent = "this is just a test";
		$fh = fopen ( $fileName, 'a+' );
		fwrite ( $fh, $newContent );
		$result = fflush ( $fh );

		$this->assertTrue ( $result );
		$this->assertEquals ( file_get_contents ( $fileName ), $fileContent . $newContent );

		fclose ( $fh );
	}

	/**
	 * Test write file
	 */
	public function testWriteFile() {
		$fileContent = "test write file";
		$containerName = $this->getContainerName ();
		$fileName = 'azure://' . $containerName . '/testread.txt';

		$storageClient = $this->_createStorageClient ();
		$storageClient->registerStreamWrapper ();
		file_put_contents ( $fileName, $fileContent );

		$this->assertEquals ( $fileContent, file_get_contents ( $fileName ) );

		// append file content
		$newContent = "\nWindows Azure";
		$fh = fopen ( $fileName, 'a+' );
		fwrite ( $fh, $newContent );
		fclose ( $fh );

		$this->assertEquals ( $fileContent . $newContent, file_get_contents ( $fileName ) );

		// replace file content
		$fh = fopen ( $fileName, 'w+' );
		fwrite ( $fh, $newContent );
		fclose ( $fh );

		$this->assertEquals ( $newContent, file_get_contents ( $fileName ) );

		// test fputs
		$fh = fopen ( $fileName, 'w' );
		$content = array ("line 1", "line 2", "line 3" );
		foreach ( $content as $line )
			fputs ( $fh, $line );
		fclose ( $fh );

		$localFile = tempnam ( '', 'tst' );
		$storageClient->getBlob ( $containerName, 'testread.txt', $localFile );
		$this->assertEquals ( implode ( "", $content ), file_get_contents ( $localFile ) );

		unlink ( $localFile );
		$storageClient->unregisterStreamWrapper ();

	}

	/**
	 * Test unlink file
	 */
	public function testUnlinkFile() {
		$storageClient = $this->_createStorageClient ();
		$storageClient->registerStreamWrapper ();
		$containerName = $this->getContainerName ();
		$fileName = 'azure://' . $containerName . '/test.txt';

		$exception = null;
		try {
			unlink ( $fileName );
		} catch ( Exception $e ) {
			$exception = $e;
		}
		$this->_expectException ( $exception, "The specified container does not exist." );

		file_put_contents ( $fileName, "test unlink file" );
		unlink ( $fileName );

		$result = $storageClient->listBlobs ( $containerName );
		$this->assertEquals ( 0, count ( $result ) );

		$exception = null;
		try {
			// delete file twice
			unlink ( $fileName );
		} catch ( Exception $e ) {
			$exception = $e;
		}
		$this->_expectException ( $exception, "The specified blob does not exist." );
		$storageClient->unregisterStreamWrapper ();
	}

	/**
	 * Mkdir operation mock
	 *
	 */
	public function testMkdir() {
		$storageClient = $this->_createStorageClient ();
		$storageClient->registerStreamWrapper ();

		$containerName = $this->getContainerName ();
		try {
			mkdir ( 'azure://' . $containerName );
			$resultContainer = $storageClient->getContainer ( $containerName );
			$this->assertNotNull ( $resultContainer );
			$this->assertTrue ( sizeof ( $resultContainer ) == 1 );
		} catch ( Exception $e ) {
			$this->fail ( $e->getMessage () );
		}
	}

	public function testMkdirMultiLevel() {
		$storageClient = $this->_createStorageClient ();
		$storageClient->registerStreamWrapper ();

		$containerName = $this->getContainerName ();

		$thrownException = false;
		try {
			mkdir ( 'azure://' . $containerName . "/" . "childDir" );
		} catch ( Exception $e ) {
			$thrownException = true;
		}

		$this->assertTrue ( $thrownException, "Maybe prompt user 'Not allow path like a/b/c ...'" ); // Maybe prompt user "Not allow path like a/b/c ..."
	}

	/**
	 * Rmdir operation mock
	 *
	 */
	public function testRmdir() {
		$storageClient = $this->_createStorageClient ();
		$storageClient->registerStreamWrapper ();

		$containerName = $this->getContainerName ();
		try {
			$storageClient->createContainer ( $containerName );
			$resultContainer = $storageClient->getContainer ( $containerName );
			$this->assertNotNull ( $resultContainer );
			$this->assertTrue ( sizeof ( $resultContainer ) == 1 );

			// Rmdir
			rmdir ( 'azure://' . $containerName );
			$resultContainer = $storageClient->getContainer ( $containerName );
		} catch ( Exception $e ) {
			$this->assertNotNull ( $e );
			$this->_assertExceptionMessageContain ( $e, "The specified container does not exist." );
		}
	}

	/**
	 * ListDir operation mock. List a dir means list blobs in a container
	 *
	 */
	public function testOpenDir() {
		$storageClient = $this->_createStorageClient ();
		$storageClient->registerStreamWrapper ();

		$containerName = $this->getContainerName ();

		$content = "I love hello ketty.";
		$blobName = "blobfile";

		//prepare resources
		mkdir ( 'azure://' . $containerName );
		for($i = 0; $i < 10; $i ++) {
			file_put_contents ( 'azure://' . $containerName . "/" . $blobName . $i, $content );
		}

		$blobs = $storageClient->listBlobs ( $containerName );
		$this->assertEquals ( 10, sizeof ( $blobs ) );

		// test assert
		$dh = opendir ( 'azure://' . $containerName );

		// Fetch blob as they are children of the directory
		while ( ($file_as_blob = readdir ( $dh )) !== false ) {
			$this->assertEquals ( $content, file_get_contents ( 'azure://' . $containerName . "/" . $file_as_blob ) );
		}
		closedir ( $dh );
	}

	//Test read directory
	public function testReadDirectory() {
		$storageClient = $this->_createStorageClient ();
		$storageClient->registerStreamWrapper ();

		$containerName = $this->getContainerName ();

		$content = "I love hello kitty.";
		$blobName = "blobfile";

		//prepare resources
		mkdir ( 'azure://' . $containerName );
		for($i = 0; $i < 10; $i ++) {
			file_put_contents ( 'azure://' . $containerName . "/" . $blobName . $i, $content );
		}

		$dh = opendir ( 'azure://' . $containerName );

		//return the filename items opened by opendir()
		$i = 0;
		while ( ($file_dir = readdir ( $dh )) !== false ) {
			//the filenames are returned in the order in which they are stored by the filesystem.
			$this->assertEquals ( $blobName . $i ++, $file_dir );
		}
		closedir ( $dh );
	}

	//Test rewind directory
	public function testRewindDirectory() {
		$storageClient = $this->_createStorageClient ();
		$storageClient->registerStreamWrapper ();

		$containerName = $this->getContainerName ();

		$content = "I love hello kitty.";
		$blobName = "blobfile";

		//prepare resources
		mkdir ( 'azure://' . $containerName );
		for($i = 0; $i < 10; $i ++) {
			file_put_contents ( 'azure://' . $containerName . "/" . $blobName . $i, $content );
		}

		$dh = opendir ( 'azure://' . $containerName );

		while ( ($file_dir = readdir ( $dh )) !== false ) {
		}
		$this->assertFalse ( readdir ( $dh ) );

		//reset the directory
		rewind ( $dh );
		$this->assertEquals ( readdir ( $dh ), $blobName . 0 );

		closedir ( $dh );
	}

	//Test close directory
	//Close directory not effect file read operation.(You can also get blob from container.)
	public function testCloseDirectory() {
		$storageClient = $this->_createStorageClient ();
		$storageClient->registerStreamWrapper ();

		$containerName = $this->getContainerName ();

		$content = "I love hello kitty.";
		$blobName = "blobfile";

		//prepare resources
		mkdir ( 'azure://' . $containerName );
		file_put_contents ( 'azure://' . $containerName . "/" . $blobName, $content );

		$dh = opendir ( 'azure://' . $containerName );

		$result = file_get_contents ( 'azure://' . $containerName . "/" . $blobName );
		$this->assertEquals ( $result, $content );
		closedir ( $dh );
		$exception = null;
		try {
			$result = file_get_contents ( 'azure://' . $containerName . "/" . $blobName );
		} catch ( Exception $e ) {
			$exception = $e;
		}
		$this->assertNull ( $exception );
	}

	public function testRenameBlob() {
		$containerName = $this->getContainerName ();
		$sourceFileName = 'azure://' . $containerName . '/test.txt';
		$destinationFileName = 'azure://' . $containerName . '/test2.txt';

		$storageClient = $this->_createStorageClient ();
		$storageClient->registerStreamWrapper ();

		$fh = fopen ( $sourceFileName, 'w' );
		fwrite ( $fh, "Hello world!" );
		fclose ( $fh );

		rename ( $sourceFileName, $destinationFileName );

		$storageClient->unregisterStreamWrapper ();

		$instance = $storageClient->getBlobInstance ( $containerName, 'test2.txt' );
		$this->assertEquals ( 'test2.txt', $instance->Name );
	}

	//Not support rename container.
	public function testRenameContainer() {
		$containerName1 = $this->getContainerName ();
		$containerName2 = $this->getContainerName ();

		$sourceFileName = 'azure://' . $containerName1;
		$destinationFileName = 'azure://' . $containerName2;

		$storageClient = $this->_createStorageClient ();
		$storageClient->registerStreamWrapper ();

		mkdir ( 'azure://' . $containerName1 );
		try {
			rename ( $sourceFileName, $destinationFileName );
			$storageClient->unregisterStreamWrapper ();

			$instance = $storageClient->getContainer ( $containerName2 );
			$this->assertEquals ( $containerName2, $instance->Name );
		} catch ( Exception $ex ) {
			$this->fail ( "Rename on container is not supportted." );
		}

	}
}

// Call Microsoft_WindowsAzure_BlobStreamTest::main() if this source file is executed directly.
if (PHPUnit_MAIN_METHOD == "Microsoft_WindowsAzure_BlobStreamTest::main") {
	Microsoft_WindowsAzure_BlobStreamTest::main ();
}

?>


text:
<!doctype html public "library">
<meta charset=utf-8/>
<title>Auto Curry Functional Concepts</title>
<link rel="stylesheet" href="../shared.css"/>
<body>
<script src="/__build__/shared.js"></script>
<script src="/__build__/2-auto-curry.js"></script>


text:
export function appendInput(char) {
  return {
    type: 'APPEND_INPUT',
    payload: char
  };
}

export function backSpace() {
  return {
    type: 'BACK_SPACE'
  };
}

export function appendEquation(oper) {
  return {
    type: 'APPEND_EQUATION',
    payload: oper
  };
}

export function clearInput() {
  return {
    type: 'CLEAR_INPUT'
  };
}

export function clearEquation() {
  return {
    type: 'CLEAR_EQUATION'
  };
}

export function total() {
  return {
    type: 'TOTAL'
  };
}


text:
/**
 * Class ReverseVectorEnumerator [implementation of Enumeration interface]
 *
 * {Comments are copied from the Java Implementation of HotDraw,..}
 *
 * An Enumeration that enumerates a vector back (size-1) to front (0).
 *
 */

ReverseVectorEnumerator.prototype = new Enumeration();

function ReverseVectorEnumerator( /* Vector */ v) { /* implements Enumeration */
        var argv = ReverseVectorEnumerator.arguments;
        var argc = ReverseVectorEnumerator.length;
        this.className = "ReverseVectorEnumerator";

        this.vector = new Vector();
        this.count = 0;

        if (argv.length > 0)
        	this.initReverseVectorEnumerator(v);
    }

ReverseVectorEnumerator.prototype.initReverseVectorEnumerator = function(v) {
        this.vector = v;
        this.count = this.vector.size() - 1;
    }

ReverseVectorEnumerator.prototype.hasMoreElements = function() {
    // Summary
    // Returns true if the Renumeration contains more elements; false if its empty.
        return this.count >= 0;
    }

ReverseVectorEnumerator.prototype.nextElement = function() {
    // Summary
    // Returns the next element of the Renumeration.
    if (this.count >= 0) {
        return this.vector.elementAt(this.count--);
    }
}


text:
body{ width:900px; ;  margin:0 auto; font-family:"Trebuchet MS", Arial, Helvetica, sans-serif; font-size:13px;  }

*{ padding:0; margin:0;}
#LZW > div {padding:20px 0;}
#LZW #form{padding:20px 0; border-bottom:#000 dotted 1px;}
#LZW .bt{ background:#222; border-radius:3px; color:#fff; text-decoration:none; width:100px; text-align:center; line-height:35px; height:35px; display:block; margin-top:10px;    box-shadow: 0 1px 0 rgba(255, 255, 255, 0.2) inset; border-color: #151515 #151515 #000000;  border-width:1px; border-style:solid; }
#LZW h1{ margin-bottom:20px; font-size:25px;}
#LZW .valCompresse{ width:880px;; display:block; border:#000 solid 1px;  padding:10px; height:100px;  }


text:
module Azure::ImportExport::Mgmt::V2016_11_01
  module Models
    #
    # BitLocker recovery key or password to the specified drive
    #
    class DriveBitLockerKey

      include MsRestAzure

      # @return [String] BitLocker recovery key or password
      attr_accessor :bit_locker_key

      # @return [String] Drive ID
      attr_accessor :drive_id

      #
      # Mapper for DriveBitLockerKey class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'DriveBitLockerKey',
          type: {
            name: 'Composite',
            class_name: 'DriveBitLockerKey',
            model_properties: {
              bit_locker_key: {
                client_side_validation: true,
                required: false,
                serialized_name: 'bitLockerKey',
                type: {
                  name: 'String'
                }
              },
              drive_id: {
                client_side_validation: true,
                required: false,
                serialized_name: 'driveId',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
import m = require("mithril");
import IKeyed from "../data/keyed";

export default class Category implements IKeyed {

    public id: _mithril.MithrilProperty<number>;
    public name: _mithril.MithrilProperty<string>;
    public description: _mithril.MithrilProperty<string>;

    constructor() {
        this.id = m.prop(0);
        this.name = m.prop("");
        this.description = m.prop("");
    }

    public toJSON = () => {
        return {
            id: this.id(),
            name: this.name(),
            description: this.description()
        };
    };

    public clone = () => {
        let clone = new Category();
        clone.id(this.id());
        clone.name(this.name());
        clone.description(this.description());
        return clone;
    };

    public update = (modified: Category) => {
        this.name(modified.name());
        this.description(modified.description());
    };
}


text:
ua = function() {
  var version;
  var ua  = navigator.userAgent.toLowerCase(); // should avoid user agent sniffing... but sometimes you just gotta do what you gotta do
  var key =        ((ua.indexOf("opera")   > -1) ? "opera"   : null);
      key = key || ((ua.indexOf("firefox") > -1) ? "firefox" : null);
      key = key || ((ua.indexOf("chrome")  > -1) ? "chrome"  : null);
      key = key || ((ua.indexOf("safari")  > -1) ? "safari"  : null);
      key = key || ((ua.indexOf("msie")    > -1) ? "ie"      : null);

  try {
    var re      = (key == "ie") ? "msie ([\\d\\.]*)" : key + "\\/([\\d\\.]*)";
    var matches = ua.match(new RegExp(re, "i"));
    version = matches ? matches[1] : null;
  } catch (e) {}

  return {
    full:    ua,
    name:    key + (version ? " " + version : ""),
    version: version,
    major:   version ? parseInt(version,10) : null,
    is: {
      firefox: (key == "firefox"),
      chrome:  (key == "chrome"),
      safari:  (key == "safari"),
      opera:   (key == "opera"),
      ie:      (key == "ie")
    },
    has: {
      audio:  AudioFX && AudioFX.enabled,
      canvas: (document.createElement('canvas').getContext),
      touch:  ('ontouchstart' in window)
    }
  };
}();

//=============================================================================
// type detection
//=============================================================================

is = {
  'string':         function(obj) { return (typeof obj === 'string');                 },
  'number':         function(obj) { return (typeof obj === 'number');                 },
  'bool':           function(obj) { return (typeof obj === 'boolean');                },
  'array':          function(obj) { return (obj instanceof Array);                    },
  'undefined':      function(obj) { return (typeof obj === 'undefined');              },
  'func':           function(obj) { return (typeof obj === 'function');               },
  'null':           function(obj) { return (obj === null);                            },
  'notNull':        function(obj) { return (obj !== null);                            },
  'invalid':        function(obj) { return ( is['null'](obj) ||  is.undefined(obj));  },
  'valid':          function(obj) { return (!is['null'](obj) && !is.undefined(obj));  },
  'emptyString':    function(obj) { return (is.string(obj) && (obj.length === 0));     },
  'nonEmptyString': function(obj) { return (is.string(obj) && (obj.length > 0));      },
  'emptyArray':     function(obj) { return (is.array(obj) && (obj.length === 0));      },
  'nonEmptyArray':  function(obj) { return (is.array(obj) && (obj.length > 0));       },
  'document':       function(obj) { return (obj === document);                        },
  'window':         function(obj) { return (obj === window);                          },
  'element':        function(obj) { return (obj instanceof HTMLElement);              },
  'event':          function(obj) { return (obj instanceof Event);                    },
  'link':           function(obj) { return (is.element(obj) && (obj.tagName === 'A')); }
};

//=============================================================================
// type coersion
//=============================================================================

to = {
  'bool':   function(obj, def) { if (is.valid(obj)) return ((obj === 1) || (obj === true) || (obj === "1") || (obj === "y") || (obj === "Y") || (obj.toString().toLowerCase() === "true") || (obj.toString().toLowerCase() === 'yes')); else return (is.bool(def) ? def : false); },
  'number': function(obj, def) { if (is.valid(obj)) { var x = parseFloat(obj); if (!isNaN(x)) return x; } return (is.number(def) ? def : 0); },
  'string': function(obj, def) { if (is.valid(obj)) return obj.toString(); return (is.string(def) ? def : ''); }
};

//=============================================================================
//
// Compatibility for older browsers (compatibility: http://kangax.github.com/es5-compat-table/)
//
//  Function.bind:        https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
//  Object.create:        http://javascript.crockford.com/prototypal.html
//  Object.extend:        (defacto standard like jquery $.extend or prototype's Object.extend)
//  Class.create:         create a simple javascript 'class' (a constructor function with a prototype and optional class methods)
//
//=============================================================================

if (!Function.prototype.bind) {
  Function.prototype.bind = function(obj) {
    var slice = [].slice,
        args  = slice.call(arguments, 1),
        self  = this,
        nop   = function () {},
        bound = function () {
          return self.apply(this instanceof nop ? this : (obj || {}), args.concat(slice.call(arguments)));
        };
    nop.prototype   = self.prototype;
    bound.prototype = new nop();
    return bound;
  };
}

if (!Object.create) {
  Object.create = function(base) {
    function F() {}
    F.prototype = base;
    return new F();
  };
}

if (!Object.extend) {
  Object.extend = function(destination, source) {
    for (var property in source) {
      if (source.hasOwnProperty(property))
        destination[property] = source[property];
    }
    return destination;
  };
}

var Class = {
  create: function(prototype, extensions) {
    var ctor = function() { if (this.initialize) return this.initialize.apply(this, arguments); };
    ctor.prototype = prototype || {};      // instance methods
    Object.extend(ctor, extensions || {}); // class methods
    return ctor;
  }
};

if (!window.requestAnimationFrame) {// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  window.requestAnimationFrame = window.webkitRequestAnimationFrame ||
                                 window.mozRequestAnimationFrame    ||
                                 window.oRequestAnimationFrame      ||
                                 window.msRequestAnimationFrame     ||
                                 function(callback, element) {
                                   window.setTimeout(callback, 1000 / 60);
                                 };
}


text:
require 'test_helper'

class TestSetTest < Test::Unit::TestCase
  include TestHelpers
  include Tack

  class FakeAdapter1

    def self.tests
      [
       ["foo_test.rb", ["Foo", "sometimes"], "should test something"],
       ["foo_test.rb", ["Foo", "in certain cases"], "should do something"],
       ["bar_test.rb", ["Bar", "context"], "description"]
      ]
    end

    def tests_for(path)
      self.class.tests
    end

  end

  should "grab all tests by default" do
    test_set = TestSet.new(FakeAdapter1.new)
    assert_equal FakeAdapter1.tests, test_set.tests_for("foo_test.rb")
  end

  should "filter description based on string" do
    test_set = TestSet.new(FakeAdapter1.new)
    assert_equal [["foo_test.rb", ["Foo", "in certain cases"], "should do something"]],
    test_set.tests_for("foo_test.rb", "do something")
  end

  should "filter description based on regexp" do
    test_set = TestSet.new(FakeAdapter1.new)
    assert_equal [["foo_test.rb", ["Foo", "in certain cases"], "should do something"]],
    test_set.tests_for("foo_test.rb", /do/)
  end

  should "filter context based on string" do
    test_set = TestSet.new(FakeAdapter1.new)
    assert_equal [["foo_test.rb", ["Foo", "sometimes"], "should test something"]],
    test_set.tests_for("foo_test.rb", 'times')
  end

  should "filter context based on regexp" do
    test_set = TestSet.new(FakeAdapter1.new)
    assert_equal [["foo_test.rb", ["Foo", "sometimes"], "should test something"]],
    test_set.tests_for("foo_test.rb", /times/)
  end

  should "filter test if context + description matches string" do
    test_set = TestSet.new(FakeAdapter1.new)
    assert_equal [['foo_test.rb', ['Foo', 'sometimes'], 'should test something']],
    test_set.tests_for('foo_test.rb', 'sometimes should test something')
  end

  should "filter test if context + description matches regexp" do
    test_set = TestSet.new(FakeAdapter1.new)
    assert_equal [['foo_test.rb', ['Foo', 'sometimes'], 'should test something']],
    test_set.tests_for('foo_test.rb', /sometimes should test something/)
  end

  class FakeAdapter2

    def tests_for(path)
      case path
      when /foo_test\.rb/
        [["foo_test.rb", ["Foo"], "test foo"]]
      when /bar_test\.rb/
        [["bar_test.rb", ["Bar"], "test bar"]]
      end
    end

  end

  context "with x_test.rb files" do

    should "get tests from all test files within directory" do
      within_construct(false) do |c|
        c.directory 'test_dir' do |d|
          d.file 'bar_test.rb'
          d.file 'foo_test.rb'
        end
        test_set = TestSet.new(FakeAdapter2.new)
        tests = test_set.tests_for(c+'test_dir')
        assert_equal [["bar_test.rb", ["Bar"], "test bar"],
                      ["foo_test.rb", ["Foo"], "test foo"]], tests
      end
    end

    should "skip over non-test files" do
      within_construct(false) do |c|
        c.directory 'test_dir' do |d|
          d.file 'foo.rb' # not a test file
        end
        adapter = stub_everything(:tests_for => [["foo_test.rb", ["Foo"], "test foo"]])
        test_set = TestSet.new(adapter)
        tests = test_set.tests_for(c+'test_dir')
        assert_equal [], tests
      end

    end

  end

  class FakeAdapter3

    def tests_for(path)
      case path
      when /test_foo\.rb/
        [["test_foo.rb", ["Foo"], "test foo"]]
      when /test_bar\.rb/
        [["test_bar.rb", ["Bar"], "test bar"]]
      end
    end

  end

  context "with test_x.rb files" do

    should "get tests from all test files within directory" do
      within_construct(false) do |c|
        c.directory 'test_dir' do |d|
          d.file 'test_bar.rb'
          d.file 'test_foo.rb'
        end
        test_set = TestSet.new(FakeAdapter3.new)
        tests = test_set.tests_for(c+'test_dir')
        assert_equal [["test_bar.rb", ["Bar"], "test bar"],
                      ["test_foo.rb", ["Foo"], "test foo"]], tests
      end
    end

  end

  class FakeRSpecAdapter

    def tests_for(path)
      case path
      when /foo_spec\.rb/
        [["foo_spec.rb", ["Foo"], "test foo"]]
      when /bar_spec\.rb/
        [["bar_spec.rb", ["Bar"], "test bar"]]
      end
    end

  end

  context "with x_spec.rb files" do

    should "get tests from all test files within directory" do
      within_construct(false) do |c|
        c.directory 'test_dir' do |d|
          d.file 'bar_spec.rb'
          d.file 'foo_spec.rb'
        end
        test_set = TestSet.new(FakeRSpecAdapter.new)
        tests = test_set.tests_for(c+'test_dir')
        assert_equal [["bar_spec.rb", ["Bar"], "test bar"],
                      ["foo_spec.rb", ["Foo"], "test foo"]], tests
      end
    end

    should "skip over non-test files" do
      within_construct(false) do |c|
        c.directory 'test_dir' do |d|
          d.file 'spec.rb' # not a test file
        end
        adapter = stub_everything(:tests_for => [["foo_spec.rb", ["Foo"], "test foo"]])
        test_set = TestSet.new(adapter)
        tests = test_set.tests_for(c+'test_dir')
        assert_equal [], tests
      end

    end

  end

end


text:
namespace SecurePages.WebForms.Tests.Account {
    using System;
    using System.Web.Security;
    using System.Web.UI;

    using Microsoft.AspNet.Membership.OpenAuth;

    public partial class Register : Page {
        #region Methods

        protected void Page_Load(object sender, EventArgs e) {
            this.RegisterUser.ContinueDestinationPageUrl = this.Request.QueryString["ReturnUrl"];
        }

        protected void RegisterUser_CreatedUser(object sender, EventArgs e) {
            FormsAuthentication.SetAuthCookie(this.RegisterUser.UserName, createPersistentCookie: false);

            string continueUrl = this.RegisterUser.ContinueDestinationPageUrl;
            if (!OpenAuth.IsLocalUrl(continueUrl)) {
                continueUrl = "~/";
            }
            this.Response.Redirect(continueUrl);
        }

        #endregion
    }
}


text:
An easy to understand guide on how to convert protected PDF document to XLS with PDF extractor SDK in C# with this source code sample. ByteScout PDF Suite is the set that includes 6 SDK products to work with PDF from generating rich PDF reports to extracting data from PDF documents and converting them to HTML. This bundle includes PDF (Generator) SDK, PDF Renderer SDK, PDF Extractor SDK, PDF to HTML SDK, PDF Viewer SDK and PDF Generator SDK for Javascript. It can convert protected PDF document to XLS with PDF extractor SDK in C#.

The following code snippet for ByteScout PDF Suite works best when you need to quickly convert protected PDF document to XLS with PDF extractor SDK in your C# application. This C# sample code is all you need for your app. Just copy and paste the code, add references (if needs to) and you are all set! Use of ByteScout PDF Suite in C# is also described in the documentation included along with the product.

You can download free trial version of ByteScout PDF Suite from our website with this and other source code samples for C#.

## REQUEST FREE TECH SUPPORT

[Click here to get in touch](https://bytescout.zendesk.com/hc/en-us/requests/new?subject=ByteScout%20PDF%20Suite%20Question)

or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=ByteScout%20PDF%20Suite%20Question)

## ON-PREMISE OFFLINE SDK

[Get Your 60 Day Free Trial](https://bytescout.com/download/web-installer?utm_source=github-readme)
[Explore SDK Docs](https://bytescout.com/documentation/index.html?utm_source=github-readme)
[Sign Up For Online Training](https://academy.bytescout.com/)

## ON-DEMAND REST WEB API

[Get your API key](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Documentation](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/tree/master/PDF.co%20Web%20API)

## VIDEO REVIEW

[https://www.youtube.com/watch?v=NEwNs2b9YN8](https://www.youtube.com/watch?v=NEwNs2b9YN8)

<!-- code block begin -->

##### ****PDF2XLS.NETCore.csproj:**

```
<?xml version="1.0" encoding="utf-8"?>
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    <EnableDefaultCompileItems>false</EnableDefaultCompileItems>
    <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
    <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
    <GenerateAssemblyFileVersionAttribute>false</GenerateAssemblyFileVersionAttribute>
    <GenerateAssemblyInformationalVersionAttribute>false</GenerateAssemblyInformationalVersionAttribute>
    <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
    <GenerateAssemblyTitleAttribute>false</GenerateAssemblyTitleAttribute>
    <GenerateAssemblyVersionAttribute>false</GenerateAssemblyVersionAttribute>
    <GenerateAssemblyCopyrightAttribute>false</GenerateAssemblyCopyrightAttribute>
    <GenerateAssemblyTrademarkAttribute>false</GenerateAssemblyTrademarkAttribute>
    <GenerateAssemblyCultureAttribute>false</GenerateAssemblyCultureAttribute>
    <GenerateAssemblyDescriptionAttribute>false</GenerateAssemblyDescriptionAttribute>
  </PropertyGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
    <None Include="encrypted %28password is %27password%27%29.pdf">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Windows.Compatibility" Version="2.0.0" />
  </ItemGroup>
  <ItemGroup>
    <Reference Include="Bytescout.PDFExtractor">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>c:\Program Files\Bytescout PDF Extractor SDK\netcoreapp2.0\Bytescout.PDFExtractor.dll</HintPath>
    </Reference>
    <Reference Include="Bytescout.PDFExtractor.OCRExtension">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>c:\Program Files\Bytescout PDF Extractor SDK\netcoreapp2.0\Bytescout.PDFExtractor.OCRExtension.dll</HintPath>
    </Reference>
  </ItemGroup>
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****PDF2XLS.VS2005.csproj:**

```
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>8.0.50727</ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{5FD39006-92D8-4ACC-B2EB-A43ECBC67F99}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>PDF2XLS</RootNamespace>
    <AssemblyName>PDF2XLS</AssemblyName>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Bytescout.PDFExtractor, Version=2.0.0.186, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <None Include="encrypted %28password is %27password%27%29.pdf">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****PDF2XLS.VS2008.csproj:**

```
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>9.0.21022</ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{5FD39006-92D8-4ACC-B2EB-A43ECBC67F99}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>PDF2XLS</RootNamespace>
    <AssemblyName>PDF2XLS</AssemblyName>
    <OldToolsVersion>2.0</OldToolsVersion>
    <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Bytescout.PDFExtractor, Version=2.0.0.186, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <None Include="encrypted %28password is %27password%27%29.pdf">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****PDF2XLS.VS2010.csproj:**

```
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>
    </ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{5FD39006-92D8-4ACC-B2EB-A43ECBC67F99}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>PDF2XLS</RootNamespace>
    <AssemblyName>PDF2XLS</AssemblyName>
    <OldToolsVersion>3.5</OldToolsVersion>
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Bytescout.PDFExtractor, Version=2.0.0.186, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <None Include="encrypted %28password is %27password%27%29.pdf">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****Program.cs:**

```
using System.IO;
using Bytescout.PDFExtractor;
using System.Diagnostics;

namespace PDF2XLS
{
    //
    // This example demonstrates how to provide password for protected PDF files.
    //
    class Program
    {
        static void Main(string[] args)
        {
            // Create Bytescout.PDFExtractor.XLSExtractor instance
            XLSExtractor extractor = new XLSExtractor();
            extractor.RegistrationName = "demo";
            extractor.RegistrationKey = "demo";

            File.Delete("output.xls");

            // Document Password Can be set in two ways
            // 1. Using Property
            // 2. Using Events

            // 1. Handle document password using Property
            // extractor.Password = "password"

            // 2. Handle document password using Event
            extractor.PasswordRequired += new System.EventHandler(extractor_PasswordRequired);

            // Load sample PDF document
            extractor.LoadDocumentFromFile(@".\encrypted (password is 'password').pdf");

            // Set the output format to XLS
            extractor.OutputFormat = SpreadseetOutputFormat.XLS;

            // Save the spreadsheet to file
            extractor.SaveToXLSFile("output.xls");

            // Cleanup
            extractor.Dispose();

            // Open result document in default associated application (for demo purpose)
            ProcessStartInfo processStartInfo = new ProcessStartInfo("output.xls");
            processStartInfo.UseShellExecute = true;
            Process.Start(processStartInfo);
        }

        static void extractor_PasswordRequired(object sender, System.EventArgs e)
        {
            // Ask user for password and put it to `Password` property.
            ((XLSExtractor) sender).Password = "password";
        }
    }
}

```

<!-- code block end -->


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN">

		<meta charset="UTF8">

		<title>Indice</title>

	<input type="button" value="Reporte Domingo" onclick="window.open('reportes/reporte_cofradia.php?did=1');"/>
	<input type="button" value="Reporte Viernes" onclick="window.open('reportes/reporte_cofradia.php?did=2');"/>
	REPORTES
		<form>

				Nombre:<input type="text" id='INnombre' value="" onkeyup="buscar();"/>

				Apellidos:<input type="text" id='INapellidos' value="" onkeyup="buscar();"/>

				<select id="selHermano" size=5 onchange="loadHermano()">
				</select>

		</form>


text:
import sys

def get_version():
    from os.path import dirname, join
    for line in open(join(dirname(__file__), "code", "png.py")):
        if '__version__' in line:
            version = line.split('"')[1]
            break
    return version

conf = dict(
    name='pypng',
    version=get_version(),
    description='Pure Python PNG image encoder/decoder',
    long_description="""
PyPNG allows PNG image files to be read and written using pure Python.

It's available from github.com
https://github.com/drj11/pypng

Documentation is kindly hosted by PyPI
http://pythonhosted.org/pypng/
(and also available in the download tarball).
""",
    author='David Jones',
    author_email='drj@pobox.com',
    url='https://github.com/drj11/pypng',
    package_dir={'':'code'},
    py_modules=['png'],
    classifiers=[
      'Topic :: Multimedia :: Graphics',
      'Topic :: Software Development :: Libraries :: Python Modules',
      'Programming Language :: Python',
      'Programming Language :: Python :: 2.3',
      'Programming Language :: Python :: 3',
      'License :: OSI Approved :: MIT License',
      'Operating System :: OS Independent',
      ],
    )
conf['download_url'] = \
  'https://github.com/drj11/pypng/archive/%(name)s-%(version)s.tar.gz' % conf

def prepare3():
    """Prepare files for installing on Python 3.  If you have
    distribute for Python 3, then we don't need to run this.
    """
    import os

    try:
        os.mkdir('code3')
    except OSError:
        pass
    # Note: -W was added in 2.7.3.
    from lib2to3.main import main
    main("lib2to3.fixes", ["-w", "-W", "-n", "-o", "code3",
                           conf['package_dir']['']])

    conf['package_dir'] = {'':'code3'}

if __name__ == '__main__':
    try:
        # http://peak.telecommunity.com/DevCenter/setuptools#basic-use
        from setuptools import setup
        # distribute is probably installed, so use_2to3 should work
        conf['use_2to3'] = True
    except ImportError:
        # http://docs.python.org/release/2.4.4/dist/setup-script.html
        from distutils.core import setup
        if sys.version_info >= (3,):
            prepare3()
    setup(**conf)


text:
var EaseMap = require('../../math/easing/EaseMap');
var UppercaseFirst = require('../../utils/string/UppercaseFirst');

/**
 * This internal function is used to return the correct ease function for a Tween.
 *
 * It can take a variety of input, including an EaseMap based string, or a custom function.
 *
 * @function Phaser.Tweens.Builders.GetEaseFunction
 * @since 3.0.0
 *
 * @param {(string|function)} ease - The ease to find. This can be either a string from the EaseMap, or a custom function.
 * @param {number[]} [easeParams] - An optional array of ease parameters to go with the ease.
 *
 * @return {function} The ease function.
 */
var GetEaseFunction = function (ease, easeParams)
{
    //  Default ease function
    var easeFunction = EaseMap.Power0;

    //  Prepare ease function
    if (typeof ease === 'string')
    {
        //  String based look-up

        //  1) They specified it correctly
        if (EaseMap.hasOwnProperty(ease))
        {
            easeFunction = EaseMap[ease];
        }
        else
        {
            //  Do some string manipulation to try and find it
            var direction = '';

            if (ease.indexOf('.'))
            {
                //  quad.in = Quad.easeIn
                //  quad.out = Quad.easeOut
                //  quad.inout = Quad.easeInOut

                direction = ease.substring(ease.indexOf('.') + 1);

                var directionLower = direction.toLowerCase();

                if (directionLower === 'in')
                {
                    direction = 'easeIn';
                }
                else if (directionLower === 'out')
                {
                    direction = 'easeOut';
                }
                else if (directionLower === 'inout')
                {
                    direction = 'easeInOut';
                }
            }

            ease = UppercaseFirst(ease.substring(0, ease.indexOf('.') + 1) + direction);

            if (EaseMap.hasOwnProperty(ease))
            {
                easeFunction = EaseMap[ease];
            }
        }
    }
    else if (typeof ease === 'function')
    {
        //  Custom function
        easeFunction = ease;
    }

    //  No custom ease parameters?
    if (!easeParams)
    {
        //  Return ease function
        return easeFunction;
    }

    var cloneParams = easeParams.slice(0);

    cloneParams.unshift(0);

    //  Return ease function with custom ease parameters
    return function (v)
    {
        cloneParams[0] = v;

        return easeFunction.apply(this, cloneParams);
    };
};

module.exports = GetEaseFunction;


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Tabl. encycl. 2:17. 1794

#### Original name
null

### Remarks
null


text:
package org.rpwf.controller;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.BDDMockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.rpwf.action.DefaultActionContext;
import org.rpwf.action.TemplateActionResult;
import org.rpwf.controller.standard.MainPageController;
import org.rpwf.model.ModelClass;
import org.rpwf.model.ORMModelFinder;

import java.util.HashSet;
import java.util.Set;

import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;

/**
 * Created by Fabian on 11.01.2015.
 */

@RunWith(PowerMockRunner.class)
@PrepareForTest(ORMModelFinder.class)

public class MainPageControllerTest {

  @Test
  public void testMainPageController() throws Exception {
    PowerMockito.mockStatic(ORMModelFinder.class);
    Set<Class<? extends ModelClass>> modelClasses = new HashSet<>();
    modelClasses.add(ControllerTestUtil.Book.class);
    BDDMockito.given(ORMModelFinder.findAllModelClasses())
		    .willReturn(modelClasses);

    DefaultActionContext ctx = mock(DefaultActionContext.class);
    TemplateActionResult templateActionResult = mock(
		    TemplateActionResult.class);
    when(ctx.createTemplateActionResult("/generic/controllers.html"))
		    .thenReturn(templateActionResult);

    MainPageController mainPageController = new MainPageController();
    mainPageController.controllerList(ctx);

    verify(templateActionResult).put("modelClasses", modelClasses);
  }

}


text:
from django.contrib.contenttypes.models import ContentType
from django.db import models

from .utils import week_for_date, month_for_date, quarter_for_date, year_for_date

class MetricAbstractQuerySet(models.query.QuerySet):
    def filter_for_object(self, object):
        object_content_type = ContentType.objects.get_for_model(object)
        return self.filter(content_type__pk=object_content_type.id, object_id=object.id)

class MetricItemQuerySet(MetricAbstractQuerySet):
    pass

class DayMetricQuerySet(MetricAbstractQuerySet):
    def filter_by_date(self, date):
        return self.filter(date_up=date)

class WeekMetricQuerySet(MetricAbstractQuerySet):
    def filter_by_date(self, date):
        return self.filter(date_up=week_for_date(date))

class MonthMetricQuerySet(MetricAbstractQuerySet):
    def filter_by_date(self, date):
        return self.filter(date_up=month_for_date(date))

class QuarterMetricQuerySet(MetricAbstractQuerySet):
    def filter_by_date(self, date):
        return self.filter(date_up=quarter_for_date(date))

class YearMetricQuerySet(MetricAbstractQuerySet):
    def filter_by_date(self, date):
        return self.filter(date_up=year_for_date(date))


text:
/**
 * @depends {nrs.js}
 */
 var NRS = (function(NRS, $, undefined) {
	NRS.subscriptionPageType = null;

	NRS.pages.subscription = function() {
		NRS.sendRequest("getAccountSubscriptions", {
			"account": NRS.account
		}, function(response) {
			if(response.subscriptions && response.subscriptions.length) {
				var subscriptions = {};
				var rows = "";

				for(var i = 0; i < response.subscriptions.length; i++) {
					rows += "
" + String(response.subscriptions[i].id).escapeHTML() + "	" + String(response.subscriptions[i].senderRS).escapeHTML() + "	" + String(response.subscriptions[i].recipientRS).escapeHTML() + "	" + NRS.formatAmount(response.subscriptions[i].amountNQT) + "	" + response.subscriptions[i].frequency + "	" + NRS.formatTimestamp(response.subscriptions[i].timeNext) + "
";
				}
			}
			NRS.dataLoaded(rows);
		});
	}

	return NRS;
}(NRS || {}, jQuery));


text:
import os
import mimetypes
from functools import partial
import eyeD3

noextract = False

trysplit = lambda s, *args:None if s == None else s.split(*args)

def ismime(filename,mmtype):
	mtype = mimetypes.guess_type(filename)[0]
	if mtype == None:
		return False
	return mtype.split('/')[0] == mmtype

isaudio = partial(ismime, mmtype='audio')
isimage = partial(ismime, mmtype='image')

def mainfunc(pat):
	tag = eyeD3.Tag()
	for dpath, dnames, filenames in os.walk(pat):
		if not any(isaudio(filename) for filename in filenames):
			continue
		if any(isimage(filename) for filename in filenames):
			continue
		if noextract:
			print dpath
			continue

		madefile = False
		for f in (os.path.join(dpath,f) for f in filenames if isaudio(os.path.join(dpath,f))):
			tag.link(f)
			imgs = tag.getImages()
			if imgs == None or len(imgs) <=0:
				continue
			imgs = imgs[0]
			imgs.writeFile(path=dpath,name="folder."+imgs.mimeType.split("/")[1].lower())
			madefile = True
			break
		if not madefile:
			print dpath

if __name__ == "__main__":
	import argparse

	parser = argparse.ArgumentParser(description="checks if an image is in a directory with an audio format")
	parser.add_argument('paths', metavar='path', type=unicode, nargs='*',
					   help='paths', default=['.'])
	parser.add_argument('--noextract', dest='noextract', default=False, action='store_const', const=True)

	args = parser.parse_args()
	noextract = args.noextract
	for pat in args.paths:
		mainfunc(pat)