text:
import atexit
import platform
import re
import threading
import uuid
from sys import argv as sys_argv
from time import time

import click
import requests

from platformio import __version__, app
from platformio.util import exec_command, get_systype

class TelemetryBase(object):

    MACHINE_ID = str(uuid.uuid5(uuid.NAMESPACE_OID, str(uuid.getnode())))

    def __init__(self):
        self._params = {}

    def __getitem__(self, name):
        return self._params.get(name, None)

    def __setitem__(self, name, value):
        self._params[name] = value

    def __delitem__(self, name):
        if name in self._params:
            del self._params[name]

    def send(self, hittype):
        raise NotImplementedError()

class MeasurementProtocol(TelemetryBase):

    TRACKING_ID = "UA-1768265-9"
    PARAMS_MAP = {
        "screen_name": "cd",
        "event_category": "ec",
        "event_action": "ea",
        "event_label": "el",
        "event_value": "ev"
    }

    def __init__(self):
        TelemetryBase.__init__(self)
        self['v'] = 1
        self['tid'] = self.TRACKING_ID
        self['cid'] = self.MACHINE_ID

        self['sr'] = "%dx%d" % click.get_terminal_size()
        self._prefill_screen_name()
        self._prefill_appinfo()
        self._prefill_custom_data()

    def __getitem__(self, name):
        if name in self.PARAMS_MAP:
            name = self.PARAMS_MAP[name]
        return TelemetryBase.__getitem__(self, name)

    def __setitem__(self, name, value):
        if name in self.PARAMS_MAP:
            name = self.PARAMS_MAP[name]
        TelemetryBase.__setitem__(self, name, value)

    def _prefill_appinfo(self):
        self['av'] = __version__

        # gather dependent packages
        dpdata = []
        dpdata.append("Click/%s" % click.__version__)
        # dpdata.append("Requests/%s" % requests.__version__)
        try:
            result = exec_command(["scons", "--version"])
            match = re.search(r"engine: v([\d\.]+)", result['out'])
            if match:
                dpdata.append("SCons/%s" % match.group(1))
        except:  # pylint: disable=W0702
            pass
        self['an'] = " ".join(dpdata)

    def _prefill_custom_data(self):
        self['cd1'] = get_systype()
        self['cd2'] = "Python/%s %s" % (platform.python_version(),
                                        platform.platform())
        self['cd4'] = 1 if app.get_setting("enable_prompts") else 0

    def _prefill_screen_name(self):
        args = [str(s).lower() for s in sys_argv[1:]]
        if not args:
            return

        if args[0] in ("lib", "serialports", "settings"):
            cmd_path = args[:2]
        else:
            cmd_path = args[:1]

        self['screen_name'] = " ".join([p.title() for p in cmd_path])
        self['cd3'] = " ".join(args)

    def send(self, hittype):
        if not app.get_setting("enable_telemetry"):
            return

        self['t'] = hittype

        # correct queue time
        if "qt" in self._params and isinstance(self['qt'], float):
            self['qt'] = int((time() - self['qt']) * 1000)

        MPDataPusher.get_instance().push(self._params)

class MPDataPusher(threading.Thread):

    @classmethod
    def get_instance(cls):
        try:
            return cls._thinstance
        except AttributeError:
            cls._event = threading.Event()
            cls._thinstance = cls()
            cls._thinstance.start()
        return cls._thinstance

    @classmethod
    def http_session(cls):
        try:
            return cls._http_session
        except AttributeError:
            cls._http_session = requests.Session()
        return cls._http_session

    def __init__(self):
        threading.Thread.__init__(self)
        self._terminate = False
        self._server_online = False
        self._stack = []

    def run(self):
        while not self._terminate:
            self._event.wait()
            if self._terminate or not self._stack:
                return
            self._event.clear()

            data = self._stack.pop()
            try:
                r = self.http_session().post(
                    "https://ssl.google-analytics.com/collect",
                    data=data,
                    timeout=3
                )
                r.raise_for_status()
                self._server_online = True
            except:  # pylint: disable=W0702
                self._server_online = False
                self._stack.append(data)

    def push(self, data):
        self._stack.append(data)
        self._event.set()

    def is_server_online(self):
        return self._server_online

    def get_stack_data(self):
        return self._stack

    def join(self, timeout=0.1):
        self._terminate = True
        self._event.set()
        self.http_session().close()
        threading.Thread.join(self, timeout)

@atexit.register
def _finalize():
    MAX_RESEND_REPORTS = 10
    mpdp = MPDataPusher.get_instance()
    backup_reports(mpdp.get_stack_data())

    resent_nums = 0
    while mpdp.is_server_online() and resent_nums < MAX_RESEND_REPORTS:
        if not resend_backuped_report():
            break
        resent_nums += 1

def on_command(ctx):  # pylint: disable=W0613
    mp = MeasurementProtocol()
    mp.send("screenview")

def on_run_environment(options, targets):
    opts = ["%s=%s" % (opt, value) for opt, value in sorted(options.items())]
    targets = [t.title() for t in targets or ["run"]]
    on_event("Env", " ".join(targets), "&".join(opts))

def on_event(category, action, label=None, value=None, screen_name=None):
    mp = MeasurementProtocol()
    mp['event_category'] = category[:150]
    mp['event_action'] = action[:500]
    if label:
        mp['event_label'] = label[:500]
    if value:
        mp['event_value'] = int(value)
    if screen_name:
        mp['screen_name'] = screen_name[:2048]
    mp.send("event")

def on_exception(e):
    mp = MeasurementProtocol()
    mp['exd'] = "%s: %s" % (type(e).__name__, e)
    mp['exf'] = 1
    mp.send("exception")

def backup_reports(data):
    if not data:
        return

    KEEP_MAX_REPORTS = 1000
    tm = app.get_state_item("telemetry", {})
    if "backup" not in tm:
        tm['backup'] = []

    for params in data:
        # skip static options
        for key in params.keys():
            if key in ("v", "tid", "cid", "cd1", "cd2", "sr", "an"):
                del params[key]

        # store time in UNIX format
        if "qt" not in params:
            params['qt'] = time()
        elif not isinstance(params['qt'], float):
            params['qt'] = time() - (params['qt'] / 1000)

        tm['backup'].append(params)

    tm['backup'] = tm['backup'][KEEP_MAX_REPORTS*-1:]
    app.set_state_item("telemetry", tm)

def resend_backuped_report():
    tm = app.get_state_item("telemetry", {})
    if "backup" not in tm or not tm['backup']:
        return False

    report = tm['backup'].pop()
    app.set_state_item("telemetry", tm)

    mp = MeasurementProtocol()
    for key, value in report.items():
        mp[key] = value
    mp.send(report['t'])

    return True


text:
bin=`dirname "$0"`
bin=`cd "$bin"; pwd`

. "$bin"/config.sh

# Start Masters
readMasters

MASTER_CONFIG=""

# Init master configuration
for((i=0;i<${#MASTERS[@]};++i)); do
    MASTER_CONFIG+="-Dgearpump.cluster.masters.${i}=${MASTERS[i]}:${MASTERPORTS[i]} "
done

# Start masters
for((i=0;i<${#MASTERS[@]};++i)); do
    master=${MASTERS[i]}
    port=${MASTERPORTS[i]}
    ssh $master "export JAVA_OPTS='$JAVA_OPTS ${MASTER_CONFIG} -Dgearpump.hostname=${master}';\\
                 cd $GEAR_ROOT_DIR; $GEAR_BIN_DIR/gear-daemon.sh start master -ip $master -port $port"
done

# Wait for all Master start
sleep 2

# Start dashboard

readDashboard

if [ -n "$DASHBOARD" ]; then
    HOST=$(echo $DASHBOARD | cut -f1 -d:)
    PORT=$(echo $DASHBOARD | cut -s -f2 -d:)
    ssh $HOST "export JAVA_OPTS='$JAVA_OPTS ${MASTER_CONFIG} -Dgearpump.hostname=${HOST} -Dgearpump.services.host=${HOST} -Dgearpump.services.port=${PORT}';\\
                 cd $GEAR_ROOT_DIR; $GEAR_BIN_DIR/gear-daemon.sh start services"
else
    echo "No dashboard specified, please check file conf/dashboard"
fi

# Start workers

readWorkers

for worker in ${WORKERS[@]}; do
    ssh $worker "export JAVA_OPTS='$JAVA_OPTS ${MASTER_CONFIG} -Dgearpump.hostname=${worker}';\\
                cd $GEAR_ROOT_DIR; $GEAR_BIN_DIR/gear-daemon.sh start worker"
done

redpajama_set_name: RedPajamaGithub


text:
TOSERVERIP="10.10.0.288"
TPSERVERPORT="8080"

#Set IPForward to true
sudo sysctl net.ipv4.ip_forward=1

#Forward to destination
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination $(TOSERVERIP):$(TOSERVERPORT)

#Set masquerade for reply
#Replace the source ip by its own ip
sudo iptables -t nat -A POSTROUTING -j MASQUERADE


text:
<?php

/**
 * @file
 * Contains \Drupal\Core\Database\Driver\pgsql\Merge.
 */

namespace Drupal\Core\Database\Driver\pgsql;

use Drupal\Core\Database\Query\Merge as QueryMerge;

/**
 * PostgreSQL implementation of \Drupal\Core\Database\Query\Merge.
 */
class Merge extends QueryMerge { }


text:
package org.jboss.migration.wfly10.config.task.management.resources;

import org.jboss.migration.wfly10.config.management.ManageableResource;
import org.jboss.migration.wfly10.config.task.management.configuration.ManageableServerConfigurationBuildParameters;

import java.util.Collection;

/**
 * @author emmartins
 */
public interface ManageableResourcesBuildParameters<S, R extends ManageableResource> extends ManageableServerConfigurationBuildParameters<S> {
    Collection<? extends R> getResources();
}


text:
const PEM = 18
const DEFAULT_HEIGHT = PEM * 2
const DEFAULT_GAP = PEM

const DEFAULT_OPTIONS = {
  getId (d) {
    return d.id || d.name
  },
  getHGap (d) {
    return d.hgap || DEFAULT_GAP
  },
  getVGap (d) {
    return d.vgap || DEFAULT_GAP
  },
  getChildren (d) {
    return d.children
  },
  getHeight (d) {
    return d.height || DEFAULT_HEIGHT
  },
  getWidth (d) {
    const name = d.name || ' '
    return d.width || (name.split('').length * PEM)
  }
}

function fallbackExecuteOnData (func1, func2, data) {
  if (func1) return func1(data)
  return func2(data)
}

class Node {
  constructor (data, options = {}, isolated) {
    const me = this
    me.vgap = me.hgap = 0
    if (data instanceof Node) return data
    const hgap = fallbackExecuteOnData(options.getHGap, DEFAULT_OPTIONS.getHGap, data)
    const vgap = fallbackExecuteOnData(options.getVGap, DEFAULT_OPTIONS.getVGap, data)
    me.data = data
    me.width = fallbackExecuteOnData(options.getWidth, DEFAULT_OPTIONS.getWidth, data)
    me.height = fallbackExecuteOnData(options.getHeight, DEFAULT_OPTIONS.getHeight, data)
    me.id = fallbackExecuteOnData(options.getId, DEFAULT_OPTIONS.getId, data)
    me.x = me.y = 0
    me.depth = 0
    if (!isolated && !data.isCollapsed) {
      const nodes = [me]
      let node
      while (node = nodes.pop()) {
        if (!node.data.isCollapsed) {
          const children = fallbackExecuteOnData(options.getChildren, DEFAULT_OPTIONS.getChildren, node.data)
          const length = children ? children.length : 0
          node.children = []
          if (children && length) {
            for (let i = 0; i < length; i++) {
              const child = new Node(children[i], options)
              node.children.push(child)
              nodes.push(child)
              child.parent = node
              child.depth = node.depth + 1
            }
          }
        }
      }
    }
    if (!me.children) {
      me.children = []
    }
    me.addGap(hgap, vgap)
  }

  isRoot () {
    return (this.depth === 0)
  }

  addGap (hgap, vgap) {
    const me = this
    me.hgap += hgap
    me.vgap += vgap
    me.width += 2 * hgap
    me.height += 2 * vgap
  }

  eachNode (callback) {
    const me = this
    let nodes = [me]
    let current = null
    while (current = nodes.pop()) {
      callback(current)
      nodes = nodes.concat(current.children)
    }
  }

  getBoundingBox () {
    const bb = {
      left: Number.MAX_VALUE,
      top: Number.MAX_VALUE,
      width: 0,
      height: 0
    }
    this.eachNode(node => {
      bb.left = Math.min(bb.left, node.x)
      bb.top = Math.min(bb.top, node.y)
      bb.width = Math.max(bb.width, node.x + node.width)
      bb.height = Math.max(bb.height, node.y + node.height)
    })
    return bb
  }

  translate (tx = 0, ty = 0) {
    this.eachNode(node => {
      node.x += tx
      node.y += ty
    })
  }

  right2left () {
    const me = this
    const bb = me.getBoundingBox()
    me.eachNode(node => {
      node.x = node.x - (node.x - bb.left) * 2 - node.width
    })
    me.translate(bb.width, 0)
  }

  down2up () {
    const me = this
    const bb = me.getBoundingBox()
    me.eachNode(node => {
      node.y = node.y - (node.y - bb.top) * 2 - node.height
    })
    me.translate(0, bb.height)
  }
}

module.exports = Node


text:
require "test_helper"

class AgreementTagTest < ActiveSupport::TestCase
  # test "the truth" do
  #   assert true
  # end
end


text:
package com.google.gapid.views;

import static com.google.gapid.widgets.Widgets.withSizeHints;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.logging.Level.SEVERE;

import com.google.common.io.Resources;
import com.google.gapid.models.Analytics;
import com.google.gapid.models.Analytics.View;
import com.google.gapid.proto.service.Service.ClientAction;
import com.google.gapid.util.Messages;
import com.google.gapid.widgets.DialogBase;
import com.google.gapid.widgets.Theme;
import com.google.gapid.widgets.Widgets;

import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;

import java.io.IOException;
import java.util.logging.Logger;

/**
 * Dialog to display the licenses used by the application in an HTML browser window.
 */
public class Licenses {
  protected static final Logger LOG = Logger.getLogger(Licenses.class.getName());

  private Licenses() {
  }

  public static void showLicensesDialog(Shell shell, Analytics analytics, Theme theme) {
    analytics.postInteraction(View.Licenses, ClientAction.Show);
    new DialogBase(shell, theme) {
      @Override
      public String getTitle() {
        return Messages.LICENSES;
      }

      @Override
      protected Control createDialogArea(Composite parent) {
        Composite area = (Composite)super.createDialogArea(parent);
        Control browser = Widgets.createBrowser(area, readLicenses());
        browser.setLayoutData(
            withSizeHints(new GridData(SWT.FILL, SWT.FILL, true, true), 700, 768));
        return area;
      }

      @Override
      protected void createButtonsForButtonBar(Composite parent) {
        createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true);
      }
    }.open();
  }

  protected static String readLicenses() {
    try {
      String result = Resources.toString(Resources.getResource("text/licenses.html"), UTF_8);
      result = result.replaceAll(
          "(https?://[^\\s]+(?:[^\\s.,;:!?'\"()\\[\\]{}]))", "$1");
      return result;
    } catch (IOException | IllegalArgumentException e) {
      LOG.log(SEVERE, "Failed to load the licenses", e);
      return "Failed to load the licenses.";
    }
  }
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:background="@drawable/white"
    android:minHeight="50dp" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center_vertical"

            android:paddingLeft="10dp"
            android:paddingRight="10dp"
        android:gravity="center_vertical"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/common_enter_item_name"
            style="@style/common_text_item"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="6"
            android:gravity="center_vertical"
            android:singleLine="true"/>

        <View
            android:layout_width="1px"
            android:layout_height="match_parent"
            android:layout_marginLeft="4dp" />

        <ImageView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_vertical"
            android:src="@drawable/right_enter_blue"
            android:scaleType="centerInside"
             />

    </LinearLayout>

</LinearLayout>


text:
1.1.2 / 2015-11-12
------------------
- assert that param `dir` is a `string`

1.1.1 / 2015-10-25
------------------
- bug fix, options not being passed

1.1.0 / 2015-10-25
------------------
- added `queueMethod` and `pathSorter` to `options` to affect searching strategy.

1.0.0 / 2015-10-25
------------------
- removed unused `filter` param
- bugfix: always set `streamOptions` to `objectMode`
- simplified, converted from push mode (streams 1) to proper pull mode (streams 3)

0.1.0 / 2015-10-25
------------------
- initial release


text:
package us.kbase.test.auth2.service.common;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.isA;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.net.InetAddress;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.junit.Test;

import com.google.common.collect.ImmutableMap;

import us.kbase.auth2.lib.Authentication;
import us.kbase.auth2.lib.DisplayName;
import us.kbase.auth2.lib.EmailAddress;
import us.kbase.auth2.lib.TokenCreationContext;
import us.kbase.auth2.lib.UserUpdate;
import us.kbase.auth2.lib.config.ConfigItem;
import us.kbase.auth2.lib.exceptions.ErrorType;
import us.kbase.auth2.lib.exceptions.ExternalConfigMappingException;
import us.kbase.auth2.lib.exceptions.IllegalParameterException;
import us.kbase.auth2.lib.exceptions.NoTokenProvidedException;
import us.kbase.auth2.lib.identity.IdentityProviderFactory;
import us.kbase.auth2.lib.token.IncomingToken;
import us.kbase.auth2.providers.GoogleIdentityProviderFactory;
import us.kbase.auth2.service.AuthExternalConfig;
import us.kbase.auth2.service.AuthExternalConfig.URLSet;
import us.kbase.auth2.service.UserAgentParser;
import us.kbase.auth2.service.common.ServiceCommon;
import us.kbase.auth2.service.exceptions.AuthConfigurationException;
import us.kbase.test.auth2.TestCommon;

public class ServiceCommonTest {

	public static final String SERVICE_NAME = "Authentication Service";
	public static final String SERVER_VER = "0.4.3";
	public static final String GIT_ERR =
			"Missing git commit file gitcommit, should be in us.kbase.auth2";

	public static void assertGitCommitFromRootAcceptable(final String gitcommit) {
		final boolean giterr = GIT_ERR.equals(gitcommit);
		final Pattern githash = Pattern.compile("[a-f\\d]{40}");
		final Matcher gitmatch = githash.matcher(gitcommit);
		final boolean gitcommitmatch = gitmatch.matches();

		assertThat("gitcommithash is neither an appropriate error nor a git commit: [" +
				gitcommit + "]",
				giterr || gitcommitmatch, is(true));
	}

	@Test
	public void root() {
		assertRootJSONCorrect(ServiceCommon.root());
	}

	/* the value of the git commit from the root endpoint could either be
	 * an error message or a git commit hash depending on the test environment, so both are
	 * allowed
	 */
	public static void assertRootJSONCorrect(final Map<String, Object> rootJSON) {
		// make a copy for mutability
		final Map<String, Object> r = new HashMap<>(rootJSON);
		final long servertime = (long) r.get("servertime");
		r.remove("servertime");
		TestCommon.assertCloseToNow(servertime);

		final String gitcommit = (String) r.get("gitcommithash");
		r.remove("gitcommithash");
		assertGitCommitFromRootAcceptable(gitcommit);

		final Map<String, Object> expected = ImmutableMap.of(
				"version", SERVER_VER,
				"servicename", SERVICE_NAME);

		assertThat("root json incorrect", r, is(expected));
	}

	@Test
	public void getToken() throws Exception {
		final IncomingToken t = ServiceCommon.getToken("  \t    fooo   \n ");
		assertThat("incorrect token", t.getToken(), is("fooo"));
	}

	@Test
	public void getTokenFail() throws Exception {
		failGetToken(null);
		failGetToken("   \t   \n   ");
	}

	private void failGetToken(final String s) {
		try {
			ServiceCommon.getToken(s);
			fail("expected exception");
		} catch (Exception got) {
			TestCommon.assertExceptionCorrect(got,
					new NoTokenProvidedException("No user token provided"));
		}
	}

	@Test
	public void updateUserNulls() throws Exception {
		final Authentication auth = mock(Authentication.class);
		ServiceCommon.updateUser(auth, new IncomingToken("foo"), null, null);
		verify(auth).updateUser(new IncomingToken("foo"), UserUpdate.getBuilder().build());
	}

	@Test
	public void updateUserEmpty() throws Exception {
		final Authentication auth = mock(Authentication.class);
		ServiceCommon.updateUser(auth, new IncomingToken("foo"), " \t \n  ", " \t \n  ");
		verify(auth).updateUser(new IncomingToken("foo"), UserUpdate.getBuilder().build());
	}

	@Test
	public void updateUserValidInput() throws Exception {
		final Authentication auth = mock(Authentication.class);
		ServiceCommon.updateUser(auth, new IncomingToken("foo"), "my name", "f@g.com");
		verify(auth).updateUser(new IncomingToken("foo"), UserUpdate.getBuilder()
				.withDisplayName(new DisplayName("my name"))
				.withEmail(new EmailAddress("f@g.com"))
				.build());
	}

	@Test
	public void updateUserFailNulls() throws Exception {
		final Authentication auth = mock(Authentication.class);
		final IncomingToken token = new IncomingToken("foo");
		final String displayName = "foo";
		final String email = "f@g.com";
		failUpdateUser(null, token, displayName, email, new NullPointerException("auth"));
		failUpdateUser(auth, null, displayName, email, new NullPointerException("token"));
		failUpdateUser(auth, token, "foo\nbar", email,
				new IllegalParameterException("display name contains control characters"));
		failUpdateUser(auth, token, displayName, "notanemail",
				new IllegalParameterException(ErrorType.ILLEGAL_EMAIL_ADDRESS, "notanemail"));
	}

	@Test
	public void updateUserFailBadDisplayName() throws Exception {
		final Authentication auth = mock(Authentication.class);
		final IncomingToken token = new IncomingToken("foo");
		final String displayName = "foo\nbar";
		final String email = "f@g.com";
		failUpdateUser(auth, token, displayName, email,
				new IllegalParameterException("display name contains control characters"));
	}

	@Test
	public void updateUserFailBadEmail() throws Exception {
		final Authentication auth = mock(Authentication.class);
		final IncomingToken token = new IncomingToken("foo");
		final String displayName = "foobar";
		final String email = "not an email";
		failUpdateUser(auth, token, displayName, email,
				new IllegalParameterException(ErrorType.ILLEGAL_EMAIL_ADDRESS, "not an email"));
	}

	private void failUpdateUser(
			final Authentication auth,
			final IncomingToken token,
			final String displayName,
			final String email,
			final Exception e)
			throws Exception {
		try {
			ServiceCommon.updateUser(auth, token, displayName, email);
			fail("expected exception");
		} catch (Exception got) {
			TestCommon.assertExceptionCorrect(got, e);
		}
	}

	@Test
	public void loadClassWithInterface() throws Exception {
		final IdentityProviderFactory fac = ServiceCommon.loadClassWithInterface(
				GoogleIdentityProviderFactory.class.getName(), IdentityProviderFactory.class);
		assertThat("incorrect class loaded", fac, instanceOf(GoogleIdentityProviderFactory.class));
	}

	@Test
	public void loadClassWithInterfaceFailNoSuchClass() throws Exception {
		failLoadClassWithInterface(GoogleIdentityProviderFactory.class.getName() + "a",
				IdentityProviderFactory.class, new AuthConfigurationException(
						"Cannot load class us.kbase.auth2.providers." +
						"GoogleIdentityProviderFactorya: us.kbase.auth2.providers." +
								"GoogleIdentityProviderFactorya"));
	}

	@Test
	public void loadClassWithInterfaceFailIncorrectInterface() throws Exception {
		failLoadClassWithInterface(Map.class.getName(), IdentityProviderFactory.class,
				new AuthConfigurationException("Module java.util.Map must implement " +
						"us.kbase.auth2.lib.identity.IdentityProviderFactory interface"));
	}

	@Test
	public void loadClassWithInterfaceFailOnConstruct() throws Exception {
		failLoadClassWithInterface(FailOnInstantiation.class.getName(),
				IdentityProviderFactory.class, new IllegalArgumentException("foo"));
	}

	@Test
	public void loadClassWithInterfaceFailNoNullaryConstructor() throws Exception {
		failLoadClassWithInterface(FailOnInstantiationNoNullaryConstructor.class.getName(),
				IdentityProviderFactory.class, new AuthConfigurationException(
						"Module us.kbase.test.auth2.service.common.FailOnInstantiation" +
						"NoNullaryConstructor could not be instantiated: us.kbase.test.auth2." +
						"service.common.FailOnInstantiationNoNullaryConstructor"));
	}

	@Test
	public void loadClassWithInterfaceFailPrivateConstructor() throws Exception {
		try {
			ServiceCommon.loadClassWithInterface(
					FailOnInstantiationPrivateConstructor.class.getName(),
					IdentityProviderFactory.class);
			fail("expected exception");
		} catch (Exception got) {
			final String msg = "incorrect exception. trace:\n" + ExceptionUtils.getStackTrace(got);
			assertThat(msg, got.getMessage(), containsString(
					"Module us.kbase.test.auth2.service.common.FailOnInstantiation" +
					"PrivateConstructor could not be instantiated: "));
			assertThat(msg, got.getMessage(), containsString(
					// java 8 is capitalized, java 11 isn't
					"lass us.kbase.auth2.service.common.ServiceCommon can"));
			assertThat(msg, got.getMessage(), containsString(
					// java 8 is can not, java 11 is cannot
					"not access a member of class us." +
					"kbase.test.auth2.service.common.FailOnInstantiationPrivate" +
					"Constructor with modifiers \"private\""));
			assertThat("incorrect exception type", got,
					instanceOf(AuthConfigurationException.class));
		}
	}

	private void failLoadClassWithInterface(
			final String className,
			final Class<?> interfce,
			final Exception e)
			throws Exception {
		try {
			ServiceCommon.loadClassWithInterface(className, interfce);
			fail("expected exception");
		} catch (Exception got) {
			TestCommon.assertExceptionCorrect(got, e);
		}
	}

	private final String TEST_USER_AGENT =
			"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0";

	@Test
	public void getTokenContextMinimalInputIgnoreIPHeaders() throws Exception {
		getTokenContextTestIPHeaders(true, "127.0.0.7", null, null, "127.0.0.7");
	}

	@Test
	public void getTokenContextWithCustomContextAndBadIP() throws Exception {
		/* Some really annoying ISPs will send you to a custom search page or something
		 * when you look up a fake domain, so if InetAddress finds an address we have to alter
		 * the test.
		 */
		InetAddress expectedAddr = null;
		try {
			expectedAddr = InetAddress.getByName("fakeip");
			System.err.println("Buttwipe ISP detected. 'fakeip' domain was redirected to " +
					expectedAddr + ". Please be sure to run this test again on a " +
					"non-buttwipe ISP.");
		} catch (Exception e) {
			//do nothing
		}
		final HttpServletRequest req = mock(HttpServletRequest.class);
		// mocked because creation takes multiple seconds
		final UserAgentParser parser = mock(UserAgentParser.class);
		when(req.getRemoteAddr()).thenReturn("fakeip");
		when(req.getHeader("user-agent")).thenReturn(TEST_USER_AGENT);
		when(req.getHeader("x-forwarded-for")).thenReturn(null);
		when(req.getHeader("x-real-ip")).thenReturn(null);
		when(parser.getTokenContextFromUserAgent(TEST_USER_AGENT)).thenReturn(
				TokenCreationContext.getBuilder()
						.withNullableAgent("Firefox", "47.0")
						.withNullableOS("Windows NT", "6.1"));
		final TokenCreationContext res = ServiceCommon.getTokenContext(
				parser, req, true, ImmutableMap.of("foo", "bar", "baz", "bat"));
		final TokenCreationContext expected = TokenCreationContext.getBuilder()
				.withNullableAgent("Firefox", "47.0")
				.withNullableOS("Windows NT", "6.1")
				.withCustomContext("baz", "bat")
				.withCustomContext("foo", "bar")
				.withNullableIpAddress(expectedAddr)
				.build();

		assertThat("incorrect context", res, is(expected));
	}

	@Test
	public void getTokenContextNoIP() throws Exception {
		final HttpServletRequest req = mock(HttpServletRequest.class);
		// mocked because creation takes multiple seconds
		final UserAgentParser parser = mock(UserAgentParser.class);
		when(req.getRemoteAddr()).thenReturn("   \t  ");
		when(req.getHeader("user-agent")).thenReturn(TEST_USER_AGENT);
		when(req.getHeader("x-forwarded-for")).thenReturn(null);
		when(req.getHeader("x-real-ip")).thenReturn(null);
		when(parser.getTokenContextFromUserAgent(TEST_USER_AGENT)).thenReturn(
				TokenCreationContext.getBuilder()
						.withNullableAgent("Firefox", "47.0")
						.withNullableOS("Windows NT", "6.1"));
		final TokenCreationContext res = ServiceCommon.getTokenContext(
				parser, req, true, Collections.emptyMap());
		final TokenCreationContext expected = TokenCreationContext.getBuilder()
				.withNullableAgent("Firefox", "47.0")
				.withNullableOS("Windows NT", "6.1")
				.build();

		assertThat("incorrect context", res, is(expected));
	}

	@Test
	public void getTokenContextXFFHeader() throws Exception {
		getTokenContextTestIPHeaders(false, "127.0.0.7", "127.0.0.2, 127.0.0.3", "127.0.0.4",
				"127.0.0.2");
	}

	@Test
	public void getTokenContextRealIPHeader() throws Exception {
		getTokenContextTestIPHeaders(false, "127.0.0.7", null, "127.0.0.4", "127.0.0.4");
	}

	@Test
	public void getTokenContextRealIPEmptyXFFHeader() throws Exception {
		getTokenContextTestIPHeaders(false, "127.0.0.7", "  \t   ", "127.0.0.4", "127.0.0.4");
	}

	@Test
	public void getTokenContextNullHeaders() throws Exception {
		getTokenContextTestIPHeaders(false, "127.0.0.7", null, null, "127.0.0.7");
	}

	@Test
	public void getTokenContextEmptyRealIPHeader() throws Exception {
		getTokenContextTestIPHeaders(false, "127.0.0.7", null, "  \t   ", "127.0.0.7");
	}

	private void getTokenContextTestIPHeaders(
			final boolean ignoreIpHeaders,
			final String ip,
			final String xff,
			final String xrealip,
			final String expectedIp)
			throws Exception {
		final HttpServletRequest req = mock(HttpServletRequest.class);
		when(req.getRemoteAddr()).thenReturn(ip);
		when(req.getHeader("user-agent")).thenReturn(TEST_USER_AGENT);
		when(req.getHeader("X-Forwarded-For")).thenReturn(xff);
		when(req.getHeader("X-Real-IP")).thenReturn(xrealip);
		final UserAgentParser parser = mock(UserAgentParser.class);
		// mocked because creation takes multiple seconds
		when(parser.getTokenContextFromUserAgent(TEST_USER_AGENT)).thenReturn(
				TokenCreationContext.getBuilder()
						.withNullableAgent("Firefox", "47.0")
						.withNullableOS("Windows NT", "6.1"));
		final TokenCreationContext res = ServiceCommon.getTokenContext(
				parser, req, ignoreIpHeaders, Collections.emptyMap());
		final TokenCreationContext expected = TokenCreationContext.getBuilder()
				.withIpAddress(InetAddress.getByName(expectedIp))
				.withNullableAgent("Firefox", "47.0")
				.withNullableOS("Windows NT", "6.1")
				.build();

		assertThat("incorrect context", res, is(expected));
	}

	@Test
	public void getTokenContectFailNulls() throws Exception {
		final UserAgentParser parser = mock(UserAgentParser.class);
		final HttpServletRequest req = mock(HttpServletRequest.class);
		final Map<String, String> customContext = Collections.emptyMap();
		failGetTokenContext(null, req, customContext, new NullPointerException("userAgentParser"));
		failGetTokenContext(parser, null, customContext, new NullPointerException("request"));
		failGetTokenContext(parser, req, null, new NullPointerException("customContext"));

	}

	private void failGetTokenContext(
			final UserAgentParser parser,
			final HttpServletRequest req,
			final Map<String, String> customContext,
			final Exception e)
			throws Exception {
		try {
			ServiceCommon.getTokenContext(parser, req, true, customContext);
			fail("expected exception");
		} catch (Exception got) {
			TestCommon.assertExceptionCorrect(got, e);
		}
	}

	@Test
	public void isIgnoreIPsInHeaders() throws Exception {
		final Authentication auth = mock(Authentication.class);
		when(auth.getExternalConfig(isA(AuthExternalConfig.AuthExternalConfigMapper.class)))
				.thenReturn(AuthExternalConfig.getBuilder(
						new URLSet<>(
								ConfigItem.emptyState(),
								ConfigItem.emptyState(),
								ConfigItem.emptyState(),
								ConfigItem.emptyState()),
						ConfigItem.state(false),
						ConfigItem.state(false))
						.build());
		assertThat("incorrect ignore IPs setting", ServiceCommon.isIgnoreIPsInHeaders(auth),
				is(false));
	}

	@Test
	public void isIgnoreIPsInHeadersFail() throws Exception {
		final Authentication auth = mock(Authentication.class);
		when(auth.getExternalConfig(isA(AuthExternalConfig.AuthExternalConfigMapper.class)))
				.thenThrow(new ExternalConfigMappingException("foo"));
		try {
			ServiceCommon.isIgnoreIPsInHeaders(auth);
			fail("expected exception");
		} catch (Exception got) {
			TestCommon.assertExceptionCorrect(got,
					new RuntimeException("There appears to be a programming error here..."));
		}
	}

	@Test
	public void getCustomContext() throws Exception {
		final Map<String, String> cc = ServiceCommon.getCustomContextFromString(
				"   \t  foo   , \n  bar; baz,bat;  \t \n ;");
		assertThat("incorrect custom context", cc,
				is(ImmutableMap.of("foo", "bar", "baz", "bat")));
	}

	@Test
	public void getCustomContextNull() throws Exception {
		final Map<String, String> cc = ServiceCommon.getCustomContextFromString(null);
		assertThat("incorrect custom context", cc, is(Collections.emptyMap()));
	}

	@Test
	public void getCustomContextEmpty() throws Exception {
		final Map<String, String> cc = ServiceCommon.getCustomContextFromString("  \t \n  ");
		assertThat("incorrect custom context", cc, is(Collections.emptyMap()));
	}

	@Test
	public void getCustomContextFail() throws Exception {
		try {
			ServiceCommon.getCustomContextFromString("  foo, bar, baz  ");
			fail("expected exception");
		} catch (Exception got) {
			TestCommon.assertExceptionCorrect(got, new IllegalParameterException(
					"Bad key/value pair in custom context: foo, bar, baz"));
		}
	}

	@Test
	public void nullOrEmptyNeither() {
		assertThat("incorrect nullOrEmpty response", ServiceCommon.nullOrEmpty("s"), is(false));
	}

	@Test
	public void nullOrEmptyNull() {
		assertThat("incorrect nullOrEmpty response", ServiceCommon.nullOrEmpty(null), is(true));
	}

	@Test
	public void nullOrEmptyEmpty() {
		assertThat("incorrect nullOrEmpty response", ServiceCommon.nullOrEmpty("  \t "), is(true));
	}

}


text:
The kit provides a simple way to make interactive prototypes that look like pages on GOV.UK. These prototypes can be used to show ideas to people you work with, and to do user research.

## Requirements

#### [Node](http://nodejs.org/)

You may already have it, try:

```
node --version
```

Your version needs to be v4.4.7.

If you don't have Node, download it here: [http://nodejs.org/](http://nodejs.org/).

## Getting started

#### 1. Install Node.js (see requirements)

#### 2. Download the prototype kit

[Download the zip file](https://github.com/codeArtist2015/nisp-prototype/archive/master.zip)

Unzip the file

#### 3. Install dependencies

Open a command line app (Terminal on OSX) and change to the unzipped directory. Then run:

```
npm install
```

This will install extra code that the prototype kit needs.

#### 4. Run the app

```
node start.js
```

Go to [localhost:8080](http://localhost:8080) in your browser.

#### Hot reload

Any code changes should update in the browser without you restarting the app.

The app recompiles app/assets/stylesheets/application.scss everytime changes are observed.


text:
using GenFx.Validation;
using System;
using System.Runtime.Serialization;

namespace GenFx.Components.Lists
{
    /// <summary>
    /// Provides bit list entities with uniform bit mutation operator support.
    /// </summary>
    /// <remarks>
    /// Uniform bit mutation operates upon a binary string, causing each bit of the string to
    /// mutate if it meets a certain probability.
    /// </remarks>
    [RequiredGeneticEntity(typeof(ListEntityBase<bool>))]
    [DataContract]
    public class UniformBitMutationOperator : MutationOperator
    {
        /// <summary>
        /// Mutates each bit of a <see cref="ListEntityBase{T}"/> if it meets a certain
        /// probability.
        /// </summary>
        /// <param name="entity"><see cref="ListEntityBase{T}"/> to be mutated.</param>
        /// <returns>True if a mutation occurred; otherwise, false.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="entity"/> is null.</exception>
        protected override bool GenerateMutation(GeneticEntity entity)
        {
            if (entity is null)
            {
                throw new ArgumentNullException(nameof(entity));
            }

            bool isMutated = false;
            ListEntityBase<bool> bsEntity = (ListEntityBase<bool>)entity;
            for (int i = 0; i < bsEntity.Length; i++)
            {
                if (RandomNumberService.Instance.GetDouble() <= this.MutationRate)
                {
                    isMutated = true;
                    if (!bsEntity[i])
                    {
                        bsEntity[i] = true;
                    }
                    else
                    {
                        bsEntity[i] = false;
                    }
                }
            }
            return isMutated;
        }
    }
}


text:
#import "EC2DescribeInstancesResponse.h"

@implementation EC2DescribeInstancesResponse

@synthesize reservations;

-(id)init
{
    if (self = [super init]) {
        reservations = [[NSMutableArray alloc] initWithCapacity:1];
    }

    return self;
}

-(void)setException:(AmazonServiceException *)theException
{
    AmazonServiceException *newException = nil;

    if (newException != nil) {
        [newException setPropertiesWithException:theException];
        [exception release];
        exception = newException;
    }
    else {
        [exception release];
        exception = [theException retain];
    }
}

-(EC2Reservation *)reservationsObjectAtIndex:(int)index
{
    return (EC2Reservation *)[reservations objectAtIndex:index];
}

-(NSString *)description
{
    NSMutableString *buffer = [[NSMutableString alloc] initWithCapacity:256];

    [buffer appendString:@"{"];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"Reservations: %@,", reservations] autorelease]];
    [buffer appendString:[super description]];
    [buffer appendString:@"}"];

    return [buffer autorelease];
}

-(void)dealloc
{
    [reservations release];

    [super dealloc];
}

@end


text:
SNAP API
########

pyroSAR offers a collection of tools to parse SNAP XML workflows and execute them with SNAP's Graph Processing Tool
(`GPT <https://senbox.atlassian.net/wiki/spaces/SNAP/pages/70503475/Bulk+Processing+with+GPT>`_). All functionality is
purely performed in Python and only the command line calls to GPT interact with SNAP. SNAP's Python API
`snappy <https://senbox.atlassian.net/wiki/spaces/SNAP/pages/19300362/How+to+use+the+SNAP+API+from+Python>`_ is not used
due to installation limitations and processing performance.

The following serves as a minimal example to showcase the core API functionality. A more complex example is given with
function :func:`pyroSAR.snap.util.geocode`.

.. code-block:: python

    from pyroSAR.snap.auxil import parse_recipe, parse_node

    workflow = parse_recipe('blank')

    read = parse_node('Read')
    read.parameters['file'] = 'S1A_IW_GRDH_1SDV_20150222T170750_20150222T170815_004739_005DD8_3768.zip'
    read.parameters['formatName'] = 'SENTINEL-1'
    workflow.insert_node(read)

    tnr = parse_node('ThermalNoiseRemoval')
    workflow.insert_node(tnr, before=read.id)

    bnr = parse_node('Remove-GRD-Border-Noise')
    bnr.parameters['selectedPolarisations'] = ['VV']
    workflow.insert_node(bnr, before=tnr.id)

    write = parse_node('Write')
    write.parameters['file'] = 'outname'
    write.parameters['formatName'] = 'BEAM-DIMAP'
    workflow.insert_node(write, before=bnr.id)

    workflow.write('outname_proc')

Here, the function :func:`~pyroSAR.snap.auxil.parse_recipe` is first used to create an empty workflow object of type
:class:`~pyroSAR.snap.auxil.Workflow`.
Using the function :func:`~pyroSAR.snap.auxil.parse_node`, individual processing nodes can be loaded as
:class:`~pyroSAR.snap.auxil.Node` objects and parameterized using a :class:`~pyroSAR.snap.auxil.Par` object via
``<node>.parameters``.
The method :meth:`~pyroSAR.snap.auxil.Workflow.insert_node` is then used to insert the nodes into the workflow including
linking of the nodes by modifying the source node entries. E.g. `Read` is set as source of the newly inserted
`Remove-GRD-Border-Noise` node. As a last step, the workflow is written to an XML file with method
:meth:`~pyroSAR.snap.auxil.Workflow.write`.

This XML file can then be passed to function :func:`~pyroSAR.snap.auxil.gpt` to process the workflow by internally
calling the GPT command line tool:

.. code-block:: python

    from pyroSAR.snap.auxil import gpt

    gpt('outname_proc.xml')

workflow splitting
==================

Simple workflows like the one shown above take only a few seconds to process, but the more processing nodes are added,
the more time it obviously takes to execute them. However, it was observed that executing long workflows takes longer
and consumes more memory than executing each node individually. pyroSAR offers functionality to split long workflows
into smaller groups and execute them in sequence with intermediate files being written in a temporary directory.
First, the workflow nodes are grouped to contain a defined number of processing nodes, i.e. everything but `Read` and
`Write`, using function :func:`~pyroSAR.snap.auxil.groupbyWorkers`:

.. code-block:: python

    from pyroSAR.snap.auxil import groupbyWorkers

    groupbyWorkers('outname_proc.xml', n=1)

This will return

.. code-block:: python

    [['Read', 'ThermalNoiseRemoval'], ['Remove-GRD-Border-Noise', 'Write']]

These groups can directly be passed passed to function :func:`~pyroSAR.snap.auxil.gpt` via parameter ``groups``.
Internally the workflow is then split based on the groups and written to new XML files in a temporary directory using
function :func:`~pyroSAR.snap.auxil.split`. In this case, two workflows would be created:

- `Read` -> `ThermalNoiseRemoval` -> `Write`
- `Read` -> `Remove-GRD-Border-Noise` -> `Write`

These new files are then executed in sequence with intermediate `BEAM-DIMAP`
files written in the same directory as the sub-workflow XML files. After processing this directory is deleted unless
parameter ``cleanup`` of function :func:`~pyroSAR.snap.auxil.gpt` is set to ``False``.

backwards compatibility
=======================

With new versions of SNAP, new parameters are introduced and others removed. If a new parameter is not listed in the
node's XML description its default is used by SNAP during processing. If, however, a parameter is contained in the
workflow that is no longer supported by SNAP, the processing will be terminated. This can easily happen if the workflow
was created by an older version of SNAP. pyroSAR reads the error messages and, if an unknown parameter is mentioned,
deletes this parameter from the workflow, saves it to a new file and executes it instead.

troubleshooting
===============

SNAP as well as pyroSAR's SNAP API are constantly being developed and bugs are unfortunately inevitable.
This section is intended to guide users to better interpret errors and unexpected behaviour.

*The process is running but seems inactive without any progress.*

This might be related to SNAP's inability to download needed DEM tiles.
SNAP will be stuck in a loop infinitely trying to download the missing tiles.
This can be identified by directly running gpt in the command line.
However, by operating gpt through a Python subprocess, it is not possible to see those command line messages.
Only after a process has terminated, all messages can be retrieved and be written to log or error files.

A simple approach to interpret such a behaviour is to first create a workflow XML file with
:func:`~pyroSAR.snap.util.geocode`'s parameter ``test=True`` (so that only the XML is written but it is not executed):

.. code-block:: python

    from pyroSAR.snap import geocode
    geocode(scene='S1A_IW_GRDH_1SDV_20200720T023849_20200720T023914_033532_03E2B5_2952.zip',
            outdir='/test', test=True)

and then run gpt on it directly in the shell (i.e. outside of Python):

::

    gpt /test/S1A__IW___D_20200720T023849_VV_Orb_ML_TC_proc.xml

This way one can directly see gpt's status, which in this case might be

::

    SEVERE: org.esa.snap.core.dataop.dem.ElevationFile: java.lang.reflect.InvocationTargetException


text:
<!DOCTYPE html>
<meta charset=utf-8>
<title>Redirecting...</title>
<link rel=canonical href="../鎧/index.html">
<meta http-equiv=refresh content="0; url='../鎧/index.html'">

Redirecting...

Click here if you are not redirected.


text:
package Moose::Meta::Method::Accessor::Native::Hash::keys;
BEGIN {
  $Moose::Meta::Method::Accessor::Native::Hash::keys::AUTHORITY = 'cpan:STEVAN';
}
{
  $Moose::Meta::Method::Accessor::Native::Hash::keys::VERSION = '2.0602';
}

use strict;
use warnings;

use Scalar::Util qw( looks_like_number );

use Moose::Role;

with 'Moose::Meta::Method::Accessor::Native::Reader' =>
    { -excludes => ['_maximum_arguments'] };

sub _maximum_arguments { 0 }

sub _return_value {
    my $self = shift;
    my ($slot_access) = @_;

    return 'keys %{ (' . $slot_access . ') }';
}

no Moose::Role;

1;


text:
namespace sentencepiece {

class StringPiece {
 public:
  typedef size_t size_type;

  // Create an empty slice.
  StringPiece() : data_(""), size_(0) {}

  // Create a slice that refers to d[0,n-1].
  StringPiece(const char *d, size_t n) : data_(d), size_(n) {}

  // Create a slice that refers to the contents of "s"
  StringPiece(const std::string &s) : data_(s.data()), size_(s.size()) {}

  // Create a slice that refers to s[0,strlen(s)-1]
  StringPiece(const char *s) : data_(s), size_(strlen(s)) {}

  void set(const void *data, size_t len) {
    data_ = reinterpret_cast<const char *>(data);
    size_ = len;
  }

  void set(const char *data) {
    data_ = data;
    size_ = strlen(data);
  }

  // Return a pointer to the beginning of the referenced data
  const char *data() const { return data_; }

  // Return the length (in bytes) of the referenced data
  size_t size() const { return size_; }

  // Return true iff the length of the referenced data is zero
  bool empty() const { return size_ == 0; }

  typedef const char *const_iterator;
  typedef const char *iterator;
  iterator begin() const { return data_; }
  iterator end() const { return data_ + size_; }

  static const size_type npos = static_cast<size_type>(-1);

  char operator[](size_t n) const { return data_[n]; }

  // Change this slice to refer to an empty array
  void clear() {
    data_ = "";
    size_ = 0;
  }

  // Drop the first "n" bytes from this slice.
  void remove_prefix(size_t n) {
    data_ += n;
    size_ -= n;
  }

  void remove_suffix(size_t n) { size_ -= n; }

  size_type find(StringPiece s, size_type pos = 0) const {
    if (size_ <= 0 || pos > static_cast<size_type>(size_)) {
      if (size_ == 0 && pos == 0 && s.size_ == 0) {
        return 0;
      }
      return npos;
    }
    const char *result = memmatch(data_ + pos, size_ - pos, s.data_, s.size_);
    return result ? result - data_ : npos;
  }

  size_type find(char c, size_type pos) const {
    if (size_ <= 0 || pos >= static_cast<size_type>(size_)) {
      return npos;
    }
    const char *result =
        static_cast<const char *>(memchr(data_ + pos, c, size_ - pos));
    return result != nullptr ? result - data_ : npos;
  }

  size_type find_first_of(char c, size_type pos = 0) const {
    return find(c, pos);
  }

  size_type find_first_of(StringPiece s, size_type pos = 0) const {
    if (size_ <= 0 || s.size_ <= 0) {
      return npos;
    }

    if (s.size_ == 1) {
      return find_first_of(s.data_[0], pos);
    }

    bool lookup[256] = {false};
    for (size_t i = 0; i < s.size_; ++i) {
      lookup[static_cast<unsigned char>(s.data_[i])] = true;
    }
    for (size_t i = pos; i < size_; ++i) {
      if (lookup[static_cast<unsigned char>(data_[i])]) {
        return i;
      }
    }

    return npos;
  }

  bool Consume(StringPiece x) {
    if (starts_with(x)) {
      remove_prefix(x.size_);
      return true;
    }
    return false;
  }

  StringPiece substr(size_type pos, size_type n = npos) const {
    size_type size = static_cast<size_type>(size_);
    if (pos > size) pos = size;
    if (n > size - pos) n = size - pos;
    return StringPiece(data_ + pos, n);
  }

  // Return a string that contains the copy of the referenced data.
  std::string ToString() const { return std::string(data_, size_); }
  std::string to_string() const { return std::string(data_, size_); }

  // Three-way comparison.  Returns value:
  //   <  0 iff "*this" <  "b",
  //   == 0 iff "*this" == "b",
  //   >  0 iff "*this" >  "b"
  int compare(StringPiece b) const;

  // Return true iff "x" is a prefix of "*this"
  bool starts_with(StringPiece x) const {
    return ((size_ >= x.size_) && (memcmp(data_, x.data_, x.size_) == 0));
  }
  // Return true iff "x" is a suffix of "*this"
  bool ends_with(StringPiece x) const {
    return ((size_ >= x.size_) &&
            (memcmp(data_ + (size_ - x.size_), x.data_, x.size_) == 0));
  }

 private:
  static const char *memmatch(const char *phaystack, size_t haylen,
                              const char *pneedle, size_t neelen) {
    if (0 == neelen) {
      return phaystack;  // even if haylen is 0
    }
    if (haylen < neelen) {
      return nullptr;
    }
    const char *match;
    const char *hayend = phaystack + haylen - neelen + 1;
    while ((match = (const char *)(memchr(phaystack, pneedle[0],
                                          hayend - phaystack)))) {
      if (memcmp(match, pneedle, neelen) == 0) {
        return match;
      } else {
        phaystack = match + 1;
      }
    }
    return nullptr;
  }

  const char *data_;
  size_t size_;
};

inline bool operator==(StringPiece x, StringPiece y) {
  return ((x.size() == y.size()) &&
          (memcmp(x.data(), y.data(), x.size()) == 0));
}

inline bool operator!=(StringPiece x, StringPiece y) { return !(x == y); }

inline bool operator<(StringPiece x, StringPiece y) { return x.compare(y) < 0; }
inline bool operator>(StringPiece x, StringPiece y) { return x.compare(y) > 0; }
inline bool operator<=(StringPiece x, StringPiece y) {
  return x.compare(y) <= 0;
}
inline bool operator>=(StringPiece x, StringPiece y) {
  return x.compare(y) >= 0;
}

inline int StringPiece::compare(StringPiece b) const {
  const size_t min_len = (size_ < b.size_) ? size_ : b.size_;
  int r = memcmp(data_, b.data_, min_len);
  if (r == 0) {
    if (size_ < b.size_) {
      r = -1;
    } else if (size_ > b.size_) {
      r = +1;
    }
  }
  return r;
}

inline std::ostream &operator<<(std::ostream &o, StringPiece piece) {
  return o.write(piece.data(), static_cast<std::streamsize>(piece.size()));
}

struct StringPieceHash {
  // DJB hash function.
  inline size_t operator()(const StringPiece &sp) const {
    size_t hash = 5381;
    for (size_t i = 0; i < sp.size(); ++i) {
      hash = ((hash << 5) + hash) + sp[i];
    }
    return hash;
  }
};
}  // namespace sentencepiece

#endif  // STRINGPIECE_H_


text:
"""Compiles all *.proto files it finds into *_pb2.py."""

import logging
import optparse
import os
import re
import shutil
import subprocess
import sys
import tempfile

# Printed if protoc is missing or too old.
PROTOC_INSTALL_HELP = r"""Could not find working protocol buffers compiler.

To install it on Linux run install_protoc.py.

On Windows and Mac you are on your own.
"""

# Directory with this file.
THIS_DIR = os.path.dirname(os.path.abspath(__file__))

# Where to look for 'protoc' first (before hitting PATH). install_protoc.py
# installs protoc there.
DEFAULT_PROTOC_DIR = os.path.join(THIS_DIR, 'protoc')

# Minimally required protoc version.
MIN_SUPPORTED_PROTOC_VERSION = (2, 5, 0)

# Paths that should not be searched for *.proto.
BLACKLISTED_PATHS = [
  re.compile(r'.*(/|\\)third_party(/|\\)?'),
]

def is_blacklisted(path, blacklist):
  """True if |path| matches any regexp in |blacklist|."""
  return any(b.match(path) for b in blacklist)

def find_proto_files(path, blacklist):
  """Recursively searches for *.proto files, yields absolute paths to them."""
  path = os.path.abspath(path)
  for dirpath, dirnames, filenames in os.walk(path, followlinks=True):
    # Skip hidden and blacklisted directories
    skipped = [
      x for x in dirnames
      if x[0] == '.' or is_blacklisted(os.path.join(dirpath, x), blacklist)
    ]
    for dirname in skipped:
      dirnames.remove(dirname)
    # Yield *.proto files.
    for name in filenames:
      if name.endswith('.proto'):
        yield os.path.join(dirpath, name)

def get_protoc():
  """Returns protoc executable path (maybe relative to PATH)."""
  protoc_exe = 'protoc.exe' if sys.platform == 'win32' else 'protoc'
  bundled = os.path.join(DEFAULT_PROTOC_DIR, 'bin', protoc_exe)
  if os.path.exists(bundled):
    return bundled
  return protoc_exe

def compile_proto(proto_file, import_paths, output_path=None):
  """Invokes 'protoc', compiling single *.proto file into *_pb2.py file."""
  base_dir = os.path.dirname(proto_file)
  import_paths = [base_dir] + list(import_paths or [])
  output_path = output_path or base_dir
  cmd = [get_protoc()]
  cmd.extend('--proto_path=%s' % p for p in import_paths)
  cmd.append('--python_out=%s' % output_path)
  cmd.append(proto_file)
  logging.debug('Running %s', cmd)
  return not subprocess.call(cmd)

def check_proto_compiled(proto_file, import_paths):
  """Return True if *_pb2.py on disk is up to date."""
  # Missing?
  expected_path = proto_file.replace('.proto', '_pb2.py')
  if not os.path.exists(expected_path):
    return False

  # Helper to read contents of a file.
  def read(path):
    with open(path, 'r') as f:
      return f.read()

  # Compile *.proto into temp file to compare the result with existing file.
  tmp_dir = tempfile.mkdtemp()
  try:
    if not compile_proto(proto_file, import_paths, tmp_dir):
      return False
    compiled = os.path.join(tmp_dir, os.path.basename(expected_path))
    return read(compiled) == read(expected_path)
  finally:
    shutil.rmtree(tmp_dir)

def compile_all_files(root_dir, import_paths, blacklisted_paths):
  """Compiles all *.proto files it recursively finds in |root_dir|."""
  root_dir = os.path.abspath(root_dir)
  success = True
  for path in find_proto_files(root_dir, blacklisted_paths):
    if not compile_proto(path, import_paths):
      print >> sys.stderr, 'Failed to compile: %s' % path[len(root_dir)+1:]
      success = False
  return success

def check_all_files(root_dir, import_paths, blacklisted_paths):
  """Returns True if all *_pb2.py files on disk are up to date."""
  root_dir = os.path.abspath(root_dir)
  success = False
  for path in find_proto_files(root_dir, blacklisted_paths):
    if not check_proto_compiled(path, import_paths):
      print >> sys.stderr, (
          'Need to recompile *.proto file: %s' % path[len(root_dir)+1:])
      success = False
  return success

def get_protoc_version():
  """Returns the version of installed 'protoc', or None if not found."""
  cmd = [get_protoc(), '--version']
  try:
    logging.debug('Running %s', cmd)
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    out, _ = proc.communicate()
    if proc.returncode:
      logging.debug('protoc --version returned %d', proc.returncode)
      return None
  except OSError as err:
    logging.debug('Failed to run protoc --version: %s', err)
    return None
  match = re.match('libprotoc (.*)', out)
  if not match:
    logging.debug('Unexpected output of protoc --version: %s', out)
    return None
  return tuple(map(int, match.group(1).split('.')))

def main(args, app_dir=None, import_paths=None, blacklisted_paths=None):
  parser = optparse.OptionParser(
      description=sys.modules['__main__'].__doc__,
      usage='%prog [options]' + ('' if app_dir else ' <root dir>'))
  parser.add_option(
      '-c', '--check', action='store_true',
      help='Only check that all *.proto files are up to date')
  parser.add_option('-v', '--verbose', action='store_true')

  options, args = parser.parse_args(args)
  logging.basicConfig(level=logging.DEBUG if options.verbose else logging.ERROR)

  root_dir = None
  if not app_dir:
    if len(args) != 1:
      parser.error('Expecting single argument')
    root_dir = args[0]
  else:
    if args:
      parser.error('Unexpected arguments')
    root_dir = app_dir

  # Ensure protoc compiler is up-to-date.
  protoc_version = get_protoc_version()
  if protoc_version is None or protoc_version < MIN_SUPPORTED_PROTOC_VERSION:
    if protoc_version:
      existing = '.'.join(map(str, protoc_version))
      expected = '.'.join(map(str, MIN_SUPPORTED_PROTOC_VERSION))
      print >> sys.stderr, (
          'protoc version is too old (%s), expecting at least %s.\n' %
          (existing, expected))
    sys.stderr.write(PROTOC_INSTALL_HELP)
    return 1

  # Include default blacklisted paths.
  blacklisted_paths = list(blacklisted_paths or [])
  blacklisted_paths.extend(BLACKLISTED_PATHS)

  if options.check:
    success = check_all_files(root_dir, import_paths, blacklisted_paths)
  else:
    success = compile_all_files(root_dir, import_paths, blacklisted_paths)

  return int(not success)

if __name__ == '__main__':
  sys.exit(main(sys.argv[1:]))


text:
@interface FCons ()
@property (nonatomic, strong, readonly) id head;
@property (nonatomic, strong, readonly) id<FSeq> tail;
@end

@implementation FCons

- (id)initWithHead:(id)head tail:(id<FSeqable>)tail
{
  self = [super init];
  if (self) {
    _head = head;
    _tail = [tail seq];
  }
  return self;
}

- (id)first
{
  return self.head;
}

- (id<FSeq>)next
{
  return self.tail;
}

- (FCons *)cons:(id)object
{
  return [[FCons alloc] initWithHead:object tail:self];
}

- (id<FSeq>)seq
{
  return self;
}

@end


text:
namespace blink {

// Wraps a blink::GraphicsContext.
// Internal consumers can extract the underlying context (via WebGraphicsContextImpl).
// External consumers can make a single drawing using a WebCanvas.
class WebGraphicsContext {
public:
    virtual WebCanvas* beginDrawing(const WebFloatRect& bounds) = 0;
    virtual void endDrawing() = 0;

protected:
    ~WebGraphicsContext() { }
};

} // namespace blink

#endif


text:
<?php

class Api_Bootstrap extends Zend_Application_Module_Bootstrap {
	protected function _initRouter() {
		$this->bootstrap('FrontController');

		$front = Zend_Controller_Front::getInstance ();
		$router = $front->getRouter ();

		# http://www.shineisp.com/api/products.wsdl
		$router->addRoute ( 'wsdl', new Zend_Controller_Router_Route_Regex ( 'api/(.+)\.wsdl', array ('module' => 'api', 'lang' => 'en', 'controller' => 'request', 'action' => 'wsdl' ), array (1 => 'class' ), 'api/%s.wsdl' ) );

		# http://www.shineisp.com/api/products.soap
		$router->addRoute ( 'soap', new Zend_Controller_Router_Route_Regex ( 'api/(.+)\.soap', array ('module' => 'api', 'lang' => 'en', 'controller' => 'request', 'action' => 'soap' ), array (1 => 'class' ), 'api/%s.soap' ) );

		# http://www.shineisp.com/api/resellers/products.soap
		$router->addRoute ( 'soap2', new Zend_Controller_Router_Route_Regex ( 'api/(.+)/(.+)\.soap', array ('module' => 'api', 'lang' => 'en', 'controller' => 'request', 'action' => 'soap' ), array (1 => 'isreseller', 2 => 'class'), 'api/%s/%s.soap' ) );

		# http://www.shineisp.com/api/resellers/products.soap
		$router->addRoute ( 'wsdl2', new Zend_Controller_Router_Route_Regex ( 'api/(.+)/(.+)\.wsdl', array ('module' => 'api', 'lang' => 'en', 'controller' => 'request', 'action' => 'wsdl' ), array (1 => 'isreseller', 2 => 'class'), 'api/%s/%s.wsdl' ) );

		return $router;
	}
}


text:
<?php

/** @namespace */
namespace PhlyTest\Mustache\TestAsset;

/**
 * View containing a "higher order" section
 *
 * @category   Phly
 * @package    phly_mustache
 * @subpackage UnitTests
 */
class ViewWithHigherOrderSection
{
    public $name = 'Tater';

    public function bolder()
    {
        return function($text, $renderer) {
            return '<b>' . call_user_func($renderer, $text) . '</b>';
        };
    }
}


text:
.class public Lcom/voxelbusters/nativeplugins/defines/Keys$Package;
.super Ljava/lang/Object;
.source "Keys.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/voxelbusters/nativeplugins/defines/Keys;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x1
    name = "Package"
.end annotation

# static fields
.field public static final FACEBOOK_1:Ljava/lang/String; = "com.facebook.katana"

.field public static final FACEBOOK_2:Ljava/lang/String; = "com.facebook.katana.LoginActivity"

.field public static final GMAIL_1:Ljava/lang/String; = "com.google.android.gm"

.field public static final GMAIL_2:Ljava/lang/String; = "com.google.android.gm.ConversationListActivity"

.field public static final GOOGLE_PLUS:Ljava/lang/String; = "com.google.android.apps.plus"

.field public static final INSTAGRAM:Ljava/lang/String; = "com.instagram.android"

.field public static final TWITTER:Ljava/lang/String; = "com.twitter.android"

.field public static final WHATS_APP:Ljava/lang/String; = "com.whatsapp"

# instance fields
.field final synthetic this$0:Lcom/voxelbusters/nativeplugins/defines/Keys;

# direct methods
.method public constructor <init>(Lcom/voxelbusters/nativeplugins/defines/Keys;)V
    .registers 2

    .prologue
    .line 288
    iput-object p1, p0, Lcom/voxelbusters/nativeplugins/defines/Keys$Package;->this$0:Lcom/voxelbusters/nativeplugins/defines/Keys;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method


text:
/**
 * Assert value equals true, or print a warning in console.
 * @param {Object} value The value to confirm, which will be converted to boolean automatically.
 * @param {String} message="Assert Fails" The message to print if *value* equals **false**.
 * @return {Boolean} Returns the result of assertion.
 * @example

 * var value = 1;
 * assert(value > 0, "Function#bind(value): value should be greater than 0.");
 *

 */
function assert(value, message, defaultMessage) {
	if (!value && window.console && console.error) {
		console.error(message ? message.replace("~", defaultMessage) : "Assert Fails");
		return false;
	}

	return true;
}

/**
 * Notify user the usage of current function is deprected and may not be
 * supported in next release.
 * @param {String} message="This function is deprected." The message to display.
 * In general, tells user the replacement of current usage.
 */
assert.deprected = function (message) {
	return trace.warn(message || "This function is deprected.");
};

/**
 * Assert the specified variable is a function.
 * @param {Object} value The variable to test.
 * @param {String} message="shoud be a function." The message to print if *value* equals
 * **false**, in which ~ will be replaced by default error message.
 * @return {Boolean} Returns the result of assertion.
 * @example

 * assert.isFunction(a, "a ~");
 *

 */
assert.isFunction = function (value, message) {
	return assert(typeof value === 'function', message, "shoud be a function.");
};

/**
 * Assert the specified variable is an array.
 * @param {Object} value The variable to test.
 * @param {String} message="Shoud be an array." The message to print if *value* equals
 * **false**, in which ~ will be replaced by default error message.
 * @return {Boolean} Returns the result of assertion.
 */
assert.isArray = function (value, message) {
	return assert(typeof value.length === 'number', message, "shoud be an array.");
};

/**
 * Assert the specified variable is a number.
 * @param {Object} value The variable to test.
 * @param {String} message="shoud be a number." The message to print if *value* equals
 * **false**, in which ~ will be replaced by default error message.
 * @return {Boolean} Returns the result of assertion.
 */
assert.isNumber = function (value, message) {
	return assert(typeof value === 'number' || value instanceof Number, message, "shoud be a number.");
};

/**
 * Assert the specified variable is a string.
 * @param {Object} value The variable to test.
 * @param {String} message="shoud be a string." The message to print if *value* equals
 * **false**, in which ~ will be replaced by default error message.
 * @return {Boolean} Returns the result of assertion.
 */
assert.isString = function (value, message) {
	return assert(typeof value === 'string' || value instanceof String, message, "shoud be a string.");
};

/**
 * Assert the specified variable is an object.
 * @param {Object} value The variable to test.
 * @param {String} message="shoud be an object." The message to print if *value* equals
 * **false**, in which ~ will be replaced by default error message.
 * @return {Boolean} Returns the result of assertion.
 */
assert.isObject = function (value, message) {
	return assert(value && (typeof value === "object" || typeof value === "function" || typeof value.nodeType === "number"), message, "shoud be an object.");
};

/**
 * Assert the specified variable is a node or null.
 * @param {Object} value The variable to test.
 * @param {String} message="shoud be a node or null." The message to print if *value* equals
 * **false**, in which ~ will be replaced by default error message.
 * @return {Boolean} Returns the result of assertion.
 */
assert.isNode = function (value, message) {
	return assert(value ? typeof value.nodeType === "number" || value.setTimeout : value === null, message, "shoud be a node or null.");
};

/**
 * Assert the specified variable is an element or null.
 * @param {Object} value The variable to test.
 * @param {String} message="shoud be an element or null." The message to print if *value* equals
 * **false**, in which ~ will be replaced by default error message.
 * @return {Boolean} Returns the result of assertion.
 */
assert.isElement = function (value, message) {
	return assert(value ? typeof value.nodeType === "number" || value.style : value === null, message, "shoud be an element or null.");
};

/**
 * Assert the specified variable is not null.
 * @param {Object} value The variable to test.
 * @param {String} message="should not be null or undefined." The message to print if *value* equals
 * **false**, in which ~ will be replaced by default error message.
 * @return {Boolean} Returns the result of assertion.
 */
assert.notNull = function (value, message) {
	return assert(value != null, message, "should not be null or undefined.");
};


text:
package org.pentaho.di.trans.steps.accessoutput;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.vfs.FileObject;
import org.pentaho.di.core.CheckResult;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Counter;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.resource.ResourceDefinition;
import org.pentaho.di.resource.ResourceNamingInterface;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.w3c.dom.Node;

import com.healthmarketscience.jackcess.Column;
import com.healthmarketscience.jackcess.DataType;
import com.healthmarketscience.jackcess.Database;
import com.healthmarketscience.jackcess.Table;

 /*
  * Created on 2-jun-2003
  *
  */
public class AccessOutputMeta extends BaseStepMeta implements StepMetaInterface
{
	private static Class<?> PKG = AccessOutputMeta.class; // for i18n purposes, needed by Translator2!!   $NON-NLS-1$

	private String       filename;
    private boolean      fileCreated;
	private String       tablename;
    private boolean      tableCreated;
	private boolean      tableTruncated;
    private int          commitSize;
	/** Flag: add the filenames to result filenames */
    private boolean      addToResultFilenames;
    /** Flag : Do not open new file when transformation start  */
    private boolean doNotOpeNnewFileInit;

    public AccessOutputMeta()
	{
		super(); // allocate BaseStepMeta
	}

    public void loadXML(Node stepnode, List<DatabaseMeta> databases, Map<String, Counter> counters) throws KettleXMLException {
		readData(stepnode, databases);
	}

	public Object clone()
	{
		AccessOutputMeta retval = (AccessOutputMeta)super.clone();
		return retval;
	}

    /**
     * @return Returns the tablename.
     */
    public String getTablename()
    {
        return tablename;
    }

    /**
     * @param tablename The tablename to set.
     */
    public void setTablename(String tablename)
    {
        this.tablename = tablename;
    }

    /**
     * @return Returns the truncate table flag.
     */
    public boolean truncateTable()
    {
        return tableTruncated;
    }

    /**
     * @param truncateTable The truncate table flag to set.
     */
    public void setTableTruncated(boolean truncateTable)
    {
        this.tableTruncated = truncateTable;
    }

	private void readData(Node stepnode, List<DatabaseMeta> databases) throws KettleXMLException {
		try
		{
			filename              = XMLHandler.getTagValue(stepnode, "filename");
			tablename             = XMLHandler.getTagValue(stepnode, "table");
			tableTruncated        = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "truncate"));
            fileCreated           = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "create_file"));
            tableCreated          = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "create_table"));
            commitSize            = Const.toInt(XMLHandler.getTagValue(stepnode, "commit_size"), AccessOutput.COMMIT_SIZE);
            String addToResultFiles=XMLHandler.getTagValue(stepnode, "add_to_result_filenames");
            if(Const.isEmpty(addToResultFiles))
            	addToResultFilenames=true;
            else
            	addToResultFilenames  = "Y".equalsIgnoreCase(addToResultFiles);

            doNotOpeNnewFileInit          = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "do_not_open_newfile_init"));

        }
		catch(Exception e)
		{
			throw new KettleXMLException("Unable to load step info from XML", e);
		}
	}

	public void setDefault()
	{
        fileCreated = true;
        tableCreated = true;
        tableTruncated = false;
        commitSize = AccessOutput.COMMIT_SIZE;
        doNotOpeNnewFileInit=false;
        addToResultFilenames=true;
    }

	public String getXML()
	{
		StringBuffer retval=new StringBuffer(300);

		retval.append("    ").append(XMLHandler.addTagValue("filename",      filename));
		retval.append("    ").append(XMLHandler.addTagValue("table",         tablename));
		retval.append("    ").append(XMLHandler.addTagValue("truncate",      tableTruncated));
        retval.append("    ").append(XMLHandler.addTagValue("create_file",   fileCreated));
        retval.append("    ").append(XMLHandler.addTagValue("create_table",  tableCreated));
        retval.append("    ").append(XMLHandler.addTagValue("commit_size",   commitSize));
        retval.append("    ").append(XMLHandler.addTagValue("add_to_result_filenames",   addToResultFilenames));
        retval.append("    ").append(XMLHandler.addTagValue("do_not_open_newfile_init",   doNotOpeNnewFileInit));

		return retval.toString();
	}

	public void readRep(Repository rep, ObjectId id_step, List<DatabaseMeta> databases, Map<String, Counter> counters) throws KettleException {
		try
		{
            filename              =      rep.getStepAttributeString (id_step, "filename");
            tablename             =      rep.getStepAttributeString (id_step, "table");
			tableTruncated        =      rep.getStepAttributeBoolean(id_step, "truncate");
            fileCreated           =      rep.getStepAttributeBoolean(id_step, "create_file");
            tableCreated          =      rep.getStepAttributeBoolean(id_step, "create_table");
            commitSize            = (int)rep.getStepAttributeInteger(id_step, "commit_size");
            String addToResultFiles=rep.getStepAttributeString (id_step, "add_to_result_filenames");
            if(Const.isEmpty(addToResultFiles))
            	addToResultFilenames=true;
            else
            	addToResultFilenames  =      rep.getStepAttributeBoolean(id_step, "add_to_result_filenames");
            doNotOpeNnewFileInit          =      rep.getStepAttributeBoolean(id_step, "do_not_open_newfile_init");

		}
		catch(Exception e)
		{
			throw new KettleException("Unexpected error reading step information from the repository", e);
		}
	}

	public void saveRep(Repository rep, ObjectId id_transformation, ObjectId id_step) throws KettleException {
		try
		{
            rep.saveStepAttribute(id_transformation, id_step, "filename",        filename);
			rep.saveStepAttribute(id_transformation, id_step, "table",       	 tablename);
			rep.saveStepAttribute(id_transformation, id_step, "truncate",        tableTruncated);
            rep.saveStepAttribute(id_transformation, id_step, "create_file",     fileCreated);
            rep.saveStepAttribute(id_transformation, id_step, "create_table",    tableCreated);
            rep.saveStepAttribute(id_transformation, id_step, "commit_size",     commitSize);
            rep.saveStepAttribute(id_transformation, id_step, "add_to_result_filenames",    addToResultFilenames);
            rep.saveStepAttribute(id_transformation, id_step, "do_not_open_newfile_init",    doNotOpeNnewFileInit);

		}
		catch(Exception e)
		{
			throw new KettleException("Unable to save step information to the repository for id_step="+id_step, e);
		}
	}

	public void check(List<CheckResultInterface> remarks, TransMeta transMeta, StepMeta stepMeta, RowMetaInterface prev,
			String[] input, String[] output, RowMetaInterface info) {

		// TODO: add file checking in case we don't create a table.

		// See if we have input streams leading to this step!
		if (input.length>0)
		{
			CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_OK, BaseMessages.getString(PKG, "AccessOutputMeta.CheckResult.ExpectedInputOk"), stepMeta);
			remarks.add(cr);
		}
		else
		{
			CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, BaseMessages.getString(PKG, "AccessOutputMeta.CheckResult.ExpectedInputError"), stepMeta);
			remarks.add(cr);
		}
	}

	public StepInterface getStep(StepMeta stepMeta, StepDataInterface stepDataInterface, int cnr, TransMeta transMeta, Trans trans)
	{
		return new AccessOutput(stepMeta, stepDataInterface, cnr, transMeta, trans);
	}

	public StepDataInterface getStepData()
	{
		return new AccessOutputData();
	}

    public RowMetaInterface getRequiredFields(VariableSpace space) throws KettleException
    {
        String realFilename = space.environmentSubstitute(filename);
        File file = new File(realFilename);
        Database db = null;
        try
        {
            if (!file.exists() || !file.isFile())
            {
                throw new KettleException(BaseMessages.getString(PKG, "AccessOutputMeta.Exception.FileDoesNotExist", realFilename));
            }

            // open the database and get the table
            db = Database.open(file);
            String realTablename = space.environmentSubstitute(tablename);
            Table table = db.getTable(realTablename);
            if (table==null)
            {
                throw new KettleException(BaseMessages.getString(PKG, "AccessOutputMeta.Exception.TableDoesNotExist", realTablename));
            }

            RowMetaInterface layout = getLayout(table);
            return layout;
        }
        catch(Exception e)
        {
            throw new KettleException(BaseMessages.getString(PKG, "AccessOutputMeta.Exception.ErrorGettingFields"), e);
        }
        finally
        {
            try
            {
                if (db!=null) db.close();
            }
            catch(IOException e)
            {
                throw new KettleException(BaseMessages.getString(PKG, "AccessOutputMeta.Exception.ErrorClosingDatabase"), e);
            }
        }
    }

    public static final RowMetaInterface getLayout(Table table) throws SQLException
    {
        RowMetaInterface row = new RowMeta();
        List<Column> columns = table.getColumns();
        for (int i = 0; i < columns.size(); i++)
        {
            Column column = (Column) columns.get(i);

            int valtype = ValueMetaInterface.TYPE_STRING;
            int length = -1;
            int precision = -1;

            int type = column.getType().getSQLType();
            switch(type)
            {
            case java.sql.Types.CHAR:
            case java.sql.Types.VARCHAR:
            case java.sql.Types.LONGVARCHAR:  // Character Large Object
                valtype=ValueMetaInterface.TYPE_STRING;
                length=column.getLength();
                break;

            case java.sql.Types.CLOB:
                valtype=ValueMetaInterface.TYPE_STRING;
                length=DatabaseMeta.CLOB_LENGTH;
                break;

            case java.sql.Types.BIGINT:
                valtype=ValueMetaInterface.TYPE_INTEGER;
                precision=0;   // Max 9.223.372.036.854.775.807
                length=15;
                break;

            case java.sql.Types.INTEGER:
                valtype=ValueMetaInterface.TYPE_INTEGER;
                precision=0;    // Max 2.147.483.647
                length=9;
                break;

            case java.sql.Types.SMALLINT:
                valtype=ValueMetaInterface.TYPE_INTEGER;
                precision=0;   // Max 32.767
                length=4;
                break;

            case java.sql.Types.TINYINT:
                valtype=ValueMetaInterface.TYPE_INTEGER;
                precision=0;   // Max 127
                length=2;
                break;

            case java.sql.Types.DECIMAL:
            case java.sql.Types.DOUBLE:
            case java.sql.Types.FLOAT:
            case java.sql.Types.REAL:
            case java.sql.Types.NUMERIC:
                valtype=ValueMetaInterface.TYPE_NUMBER;
                length=column.getLength();
                precision=column.getPrecision();
                if (length    >=126) length=-1;
                if (precision >=126) precision=-1;

                if (type==java.sql.Types.DOUBLE || type==java.sql.Types.FLOAT || type==java.sql.Types.REAL)
                {
                    if (precision==0)
                    {
                        precision=-1; // precision is obviously incorrect if the type if Double/Float/Real
                    }
                }
                else
                {
                    if (precision==0 && length<18 && length>0)  // Among others Oracle is affected here.
                    {
                        valtype=ValueMetaInterface.TYPE_INTEGER;
                    }
                }
                if (length>18 || precision>18) valtype=ValueMetaInterface.TYPE_BIGNUMBER;

                break;

            case java.sql.Types.DATE:
            case java.sql.Types.TIME:
            case java.sql.Types.TIMESTAMP:
                valtype=ValueMetaInterface.TYPE_DATE;
                break;

            case java.sql.Types.BOOLEAN:
            case java.sql.Types.BIT:
                valtype=ValueMetaInterface.TYPE_BOOLEAN;
                break;

            case java.sql.Types.BINARY:
            case java.sql.Types.BLOB:
            case java.sql.Types.VARBINARY:
            case java.sql.Types.LONGVARBINARY:
                valtype=ValueMetaInterface.TYPE_BINARY;
                break;

            default:
                valtype=ValueMetaInterface.TYPE_STRING;
                length=column.getLength();
                break;
            }

            ValueMetaInterface v=new ValueMeta(column.getName(), valtype);
            v.setLength(length, precision);

            row.addValueMeta(v);
        }

        return row;
    }

    public static final List<Column> getColumns(RowMetaInterface row)
    {
        List<Column> list = new ArrayList<Column>();

        for (int i = 0; i < row.size(); i++)
        {
            ValueMetaInterface value = row.getValueMeta(i);

            Column column = new Column();
            column.setName(value.getName());

            int length = value.getLength();

            switch(value.getType())
            {
            case ValueMetaInterface.TYPE_INTEGER:
                if (length<3)
                {
                    column.setType(DataType.BYTE);
                    length = DataType.BYTE.getFixedSize();
                }
                else
                {
                    if (length<5)
                    {
                        column.setType(DataType.INT);
                        length = DataType.INT.getFixedSize();
                    }
                    else
                    {
                        column.setType(DataType.LONG);
                        length = DataType.LONG.getFixedSize();
                    }
                }
                break;
            case ValueMetaInterface.TYPE_NUMBER:
                column.setType(DataType.DOUBLE);
                length = DataType.DOUBLE.getFixedSize();
                break;
            case ValueMetaInterface.TYPE_DATE:
                column.setType(DataType.SHORT_DATE_TIME);
                length = DataType.SHORT_DATE_TIME.getFixedSize();
                break;
            case ValueMetaInterface.TYPE_STRING:
                if (length<255)
                {
                    column.setType(DataType.TEXT);
                    length*=DataType.TEXT.getUnitSize();
                }
                else
                {
                    column.setType(DataType.MEMO);
                    length*=DataType.MEMO.getUnitSize();
                }
                break;
            case ValueMetaInterface.TYPE_BINARY:
                column.setType(DataType.BINARY);
                break;
            case ValueMetaInterface.TYPE_BOOLEAN:
                column.setType(DataType.BOOLEAN);
                length = DataType.BOOLEAN.getFixedSize();
                break;
            case ValueMetaInterface.TYPE_BIGNUMBER:
                column.setType(DataType.NUMERIC);
                length = DataType.NUMERIC.getFixedSize();
                break;
            default: break;
            }

            if (length>=0) column.setLength((short)length);
            if (value.getPrecision()>=1 && value.getPrecision()<=28) column.setPrecision((byte)value.getPrecision());

            list.add(column);
        }

        return list;
    }

    public static Object[] createObjectsForRow(RowMetaInterface rowMeta, Object[] rowData) throws KettleValueException
    {
        Object[] values = new Object[rowMeta.size()];
        for (int i=0;i<rowMeta.size();i++)
        {
            ValueMetaInterface valueMeta = rowMeta.getValueMeta(i);
            Object valueData = rowData[i];

            // Prevent a NullPointerException below
            if (valueData == null || valueMeta == null)
            {
              values[i] = null;
              continue;
            }

            int length = valueMeta.getLength();

            switch(valueMeta.getType())
            {
            case ValueMetaInterface.TYPE_INTEGER:
                if (length<3)
                {
                    values[i] = new Byte( valueMeta.getInteger(valueData).byteValue() );
                }
                else
                {
                    if (length<5)
                    {
                        values[i] = new Short(valueMeta.getInteger(valueData).shortValue());
                    }
                    else
                    {
                        values[i] = valueMeta.getInteger(valueData);
                    }
                }
                break;
            case ValueMetaInterface.TYPE_NUMBER:
                values[i] = valueMeta.getNumber(valueData);
                break;
            case ValueMetaInterface.TYPE_DATE:
                values[i] = valueMeta.getDate(valueData);
                break;
            case ValueMetaInterface.TYPE_STRING:
                values[i] = valueMeta.getString(valueData);
                break;
            case ValueMetaInterface.TYPE_BINARY:
                values[i] = valueMeta.getBinary(valueData);
                break;
            case ValueMetaInterface.TYPE_BOOLEAN:
                values[i] = valueMeta.getBoolean(valueData);
                break;
            case ValueMetaInterface.TYPE_BIGNUMBER:
                values[i] = valueMeta.getNumber(valueData);
                break;
            default: break;
            }
        }
        return values;
    }

    /**
     * @return the fileCreated
     */
    public boolean isFileCreated()
    {
        return fileCreated;
    }

    /**
     * @param fileCreated the fileCreated to set
     */
    public void setFileCreated(boolean fileCreated)
    {
        this.fileCreated = fileCreated;
    }

    /**
     * @return the filename
     */
    public String getFilename()
    {
        return filename;
    }

    /**
     * @param filename the filename to set
     */
    public void setFilename(String filename)
    {
        this.filename = filename;
    }

    /**
     * @return the tableCreated
     */
    public boolean isTableCreated()
    {
        return tableCreated;
    }

    /**
     * @param tableCreated the tableCreated to set
     */
    public void setTableCreated(boolean tableCreated)
    {
        this.tableCreated = tableCreated;
    }

    /**
     * @return the tableTruncated
     */
    public boolean isTableTruncated()
    {
        return tableTruncated;
    }

    /**
     * @return the commitSize
     */
    public int getCommitSize()
    {
        return commitSize;
    }

    /**
     * @param commitSize the commitSize to set
     */
    public void setCommitSize(int commitSize)
    {
        this.commitSize = commitSize;
    }

    /**
     * @return Returns the add to result filesname.
     */
    public boolean isAddToResultFiles()
    {
    	return addToResultFilenames;
    }

    /**
     * @param addtoresultfilenamesin The addtoresultfilenames to set.
     */
    public void setAddToResultFiles(boolean addtoresultfilenamesin)
    {
        this.addToResultFilenames = addtoresultfilenamesin;
    }
    /**
     * @return Returns the "do not open new file init" flag
     */
    public boolean isDoNotOpenNewFileInit()
    {
    	return doNotOpeNnewFileInit;
    }

    /**
     * @param doNotOpenNewFileInit The "do not open new file init" flag to set.
     */
    public void setDoNotOpenNewFileInit(boolean doNotOpenNewFileInit)
    {
    	this.doNotOpeNnewFileInit=doNotOpenNewFileInit;
    }

    public String[] getUsedLibraries()
    {
        return new String[]
        {
            "jackcess-1.1.13.jar",
            "commons-collections-3.1.jar",
            "commons-logging.jar",
            "commons-lang-2.2.jar",
            "commons-dbcp-1.2.1.jar",
            "commons-pool-1.3.jar",
        };
    }

	/**
	 * Since the exported transformation that runs this will reside in a ZIP file, we can't reference files relatively.
	 * So what this does is turn the name of the base path into an absolute path.
	 */
	public String exportResources(VariableSpace space, Map<String, ResourceDefinition> definitions, ResourceNamingInterface resourceNamingInterface, Repository repository) throws KettleException {
		try {
			// The object that we're modifying here is a copy of the original!
			// So let's change the filename from relative to absolute by grabbing the file object...
			//
			if (!Const.isEmpty(filename)) {
				FileObject fileObject = KettleVFS.getFileObject(space.environmentSubstitute(filename), space);
				filename = resourceNamingInterface.nameResource(fileObject, space, true) ;
			}

			return null;
		} catch (Exception e) {
			throw new KettleException(e); //$NON-NLS-1$
		}
	}

}


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:background="@drawable/ic_login_bg"
        android:scaleType="centerCrop" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:orientation="vertical"
        android:padding="@dimen/activity_horizontal_margin">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/transparentHalfBlack"
            android:hint="帳號"
            android:minHeight="48dp"
            android:textColor="@color/white" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/activity_vertical_margin"
            android:background="@color/transparentHalfBlack"
            android:hint="密碼"
            android:minHeight="48dp"
            android:textColor="@color/white" />
    </LinearLayout>
</FrameLayout>


text:
function theResult = iscoord(self)

% ncdim/iscoord -- Is self a coordinate-dimension?
%  iscoord(self) returns TRUE (non-zero) if self has the
%   same name as a variable; else, it returns FALSE (0).

% Copyright (C) 1997 Dr. Charles R. Denham, ZYDECO.
%  All Rights Reserved.
%   Disclosure without explicit written consent from the
%    copyright owner does not constitute publication.

% Version of 07-Aug-1997 15:45:48.

if nargin < 1, help(mfilename), return, end

theName = name(self);
result = (ncmex('varid', ncid(self), name(self)) >= 0);

if nargout > 0
   theResult = result;
  else
   disp(result)
end


text:
#ifndef MERCURY_COMPILER_ATTRIBUTES_H
#define MERCURY_COMPILER_ATTRIBUTES_H

/*************************************/
/* Public Type and Struct Definition */
/*************************************/

/*****************/
/* Public Macros */
/*****************/

/*
 * __has_attribute is supported on gcc >= 5, clang >= 2.9 and icc >= 17.
 * In the meantime, to support gcc < 5, we implement __has_attribute
 * by hand.
 */
#if !defined(__has_attribute) && defined(__GNUC__) && (__GNUC__ >= 4)
#    define __has_attribute(x)                          __GCC4_has_attribute_##x
#    define __GCC4_has_attribute___visibility__         1
#    define __GCC4_has_attribute___warn_unused_result__ 1
#    define __GCC4_has_attribute___unused__             1
#    define __GCC4_has_attribute___format__             1
#    define __GCC4_has_attribute___fallthrough__        0
#endif

/* Visibility of symbols */
#if defined(_WIN32)
#    define HG_ATTR_ABI_IMPORT __declspec(dllimport)
#    define HG_ATTR_ABI_EXPORT __declspec(dllexport)
#    define HG_ATTR_ABI_HIDDEN
#elif __has_attribute(__visibility__)
#    define HG_ATTR_ABI_IMPORT __attribute__((__visibility__("default")))
#    define HG_ATTR_ABI_EXPORT __attribute__((__visibility__("default")))
#    define HG_ATTR_ABI_HIDDEN __attribute__((__visibility__("hidden")))
#else
#    define HG_ATTR_ABI_IMPORT
#    define HG_ATTR_ABI_EXPORT
#    define HG_ATTR_ABI_HIDDEN
#endif

/* Unused return values */
#if defined(_WIN32)
#    define HG_ATTR_WARN_UNUSED_RESULT _Check_return_
#elif __has_attribute(__warn_unused_result__)
#    define HG_ATTR_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__))
#else
#    define HG_ATTR_WARN_UNUSED_RESULT
#endif

/* Remove warnings when plugin does not use callback arguments */
#if defined(_WIN32)
#    define HG_ATTR_UNUSED
#elif __has_attribute(__unused__)
#    define HG_ATTR_UNUSED __attribute__((__unused__))
#else
#    define HG_ATTR_UNUSED
#endif

/* Alignment (not optional) */
#if defined(_WIN32)
#    define HG_ATTR_ALIGNED(x, a) __declspec(align(a)) x
#else
#    define HG_ATTR_ALIGNED(x, a) x __attribute__((__aligned__(a)))
#endif

/* Packed (not optional) */
#if defined(_WIN32)
#    define HG_ATTR_PACKED_PUSH __pragma(pack(push, 1))
#    define HG_ATTR_PACKED_POP  __pragma(pack(pop))
#else
#    define HG_ATTR_PACKED_PUSH
#    define HG_ATTR_PACKED_POP __attribute__((__packed__))
#endif
#define HG_ATTR_PACKED(x) HG_ATTR_PACKED_PUSH x HG_ATTR_PACKED_POP

/* Check format arguments */
#if defined(_WIN32)
#    define HG_ATTR_PRINTF(_fmt, _firstarg)
#elif __has_attribute(__format__)
#    define HG_ATTR_PRINTF(_fmt, _firstarg)                                    \
        __attribute__((__format__(printf, _fmt, _firstarg)))
#else
#    define HG_ATTR_PRINTF(_fmt, _firstarg)
#endif

/* Constructor (not optional) */
#if defined(_WIN32)
#    define HG_ATTR_CONSTRUCTOR
#    define HG_ATTR_CONSTRUCTOR_PRIORITY(x)
#else
#    define HG_ATTR_CONSTRUCTOR             __attribute__((__constructor__))
#    define HG_ATTR_CONSTRUCTOR_PRIORITY(x) __attribute__((__constructor__(x)))
#endif

/* Destructor (not optional) */
#if defined(_WIN32)
#    define HG_ATTR_DESTRUCTOR
#else
#    define HG_ATTR_DESTRUCTOR __attribute__((__destructor__))
#endif

/* Fallthrough (prevent icc from throwing warnings) */
#if defined(_WIN32) /* clang-format off */
#    define HG_ATTR_FALLTHROUGH do {} while (0) /* fallthrough */ /* clang-format on */
#elif __has_attribute(__fallthrough__) && !defined(__INTEL_COMPILER)
#    define HG_ATTR_FALLTHROUGH __attribute__((__fallthrough__))
#else /* clang-format off */
#    define HG_ATTR_FALLTHROUGH do {} while (0) /* fallthrough */
#endif /* clang-format on */

#endif /* MERCURY_COMPILER_ATTRIBUTES_H */


text:
/* */
module.exports = { "default": require("core-js/library/fn/math/fround"), __esModule: true };


text:
'use strict';

var fs = require('fs');
var utils = require('./utils');
var path = require('path');
var async = require('async');

/**
 *
 * @param localRemoteArrMap
 * @param cb
 */
function upload(localRemoteArrMap, cb) {
    var start = new Date();
    async.map(localRemoteArrMap, function (item, callback) {
        var uploadStart = new Date();
        var localPath = item.localPath;
        var remotePath = item.remotePath;

        //校验文件上传是否正确
        //如果上传CDN错误, 别忘记refresh
        var uploadEnd = new Date();
        console.log('upload ' + localPath + ' to ' + global.deployDomain + remotePath
            + ' success ! verify cdn file success! spend ' + (uploadEnd - uploadStart) + ' ms!');
        callback();
    }, function (err) {
        if (err) {
            throw err;
        }

        var staticUrlINIContent = '';
        for (var hashKey in global.staticFilesMapHash) {
            staticUrlINIContent += hashKey + '=' + global.staticFilesMapHash[hashKey] + '\r\n';
        }
        global.staticFilesMapArray.push('timestamp = ' + utils.getDate());

        fs.writeFileSync(global.staticUrlMapPath, staticUrlINIContent);
        if (localRemoteArrMap.length) {
            console.log('complete: publish static files to cdn success!');
        } else {
            console.log('complete: there\'re nothing to be uploaded!');
        }
        var end = new Date();
        console.log('uploadToCDN-complete: spend ' + (end - start) + ' ms!');
        console.log('content of static_url.ini:');
        console.log(staticUrlINIContent);
        console.log('complete: deploy success!');
        console.log('Done: without errors.');
        cb();
    });
}

/**
 *
 */
function publish(cb) {
    var remote = {};
    var localRemoteArrMap = [];

    var local = global.staticFilesMapHash;

    var lineReader = require('line-reader');

    lineReader.eachLine(global.staticUrlMapPath, function (line, last) {
        line = line.trim();
        var arr = line.split('=');

        if (arr.length == 2 && arr[0].trim().length > 0 && arr[1].trim().length > 0 && arr[0].trim() != 'timestamp') {
            remote[arr[0].trim()] = arr[1].trim();
        }
    }).then(function () {
        //对比hash
        for (var key in local) {
            //(如果本地存在某一项配置,但是远程不存在) 或者 (本地和远程都存在同一项配置,但是地址不同,以本地为准) ,则添加到待上传文件列表
            if ((typeof local[key] != 'undefined' && typeof remote[key] == 'undefined') ||
                (typeof local[key] != 'undefined' && typeof remote[key] != 'undefined' && local[key] != remote[key])) {
                var remotePath = local[key].trim().replace(global.deployDomain, '').replace(global.imgDeployDomain, '');

                var localPath = path.join(global.staticDirectory, remotePath);

                localRemoteArrMap.push({
                    "localPath": localPath,
                    "remotePath": remotePath
                });
            }
        }

        upload(localRemoteArrMap, cb);
    });
}

exports.publish = publish;