text:
#!/usr/bin/env bash
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

#
# Creates a HBase release candidate. The script will update versions, tag the branch,
# build HBase binary packages and documentation, and upload maven artifacts to a staging
# repository. There is also a dry run mode where only local builds are performed, and
# nothing is uploaded to the ASF repos.
#
# Run with "-h" for options. For example, running below will do all
# steps above using the 'rm' dir under Downloads as workspace:
#
# $ ./do-release-docker.sh  -d ~/Downloads/rm
#
# The scripts in this directory came originally from spark [1]. They were then
# modified to suite the hbase context. These scripts supercedes the old
# ../make_rc.sh script for making release candidates because what is here is more
# comprehensive doing more steps of the RM process as well as running in a
# container so the RM build environment can be a constant.
#
# It:
#  * Tags release
#  * Sets version to the release version
#  * Sets version to next SNAPSHOT version.
#  * Builds, signs, and hashes all artifacts.
#  * Pushes release tgzs to the dev dir in a apache dist.
#  * Pushes to repository.apache.org staging.
#
# The entry point is here, in the do-release-docker.sh script.
#
# 1. https://github.com/apache/spark/tree/master/dev/create-release
#
set -e

# Set this to build other hbase repos: e.g. PROJECT=hbase-operator-tools
export PROJECT="${PROJECT:-hbase}"

SELF="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=SCRIPTDIR/release-util.sh
. "$SELF/release-util.sh"
ORIG_PWD="$(pwd)"

function usage {
  local NAME
  NAME="$(basename "${BASH_SOURCE[0]}")"
  cat <<EOF
Usage: $NAME [OPTIONS]
Runs release scripts inside a docker image.
Options:
  -d [path]    Required. Working directory. Output will be written to "output" in here.
  -f           "force" -- actually publish this release. Unless you specify '-f', it will
               default to dry run mode, which checks and does local builds, but does not
               upload anything.
  -t [tag]     Tag for the hbase-rm docker image to use for building (default: "latest").
  -j [path]    Path to local JDK installation to use building. By default the script will
               use openjdk8 installed in the docker image.
  -p [project] Project to build: e.g. 'hbase' or 'hbase-thirdparty'; defaults to PROJECT env var
  -r [repo]    Git repo to use for remote git operations. defaults to ASF gitbox for project.
  -s [step]    Runs a single step of the process; valid steps: tag|publish-dist|publish-release.
               If none specified, runs tag, then publish-dist, and then publish-release.
               'publish-snapshot' is also an allowed, less used, option.
  -x           Debug. Does less clean up (env file, gpg forwarding on mac)
EOF
  exit 1
}

WORKDIR=
IMGTAG=latest
JAVA=
RELEASE_STEP=
GIT_REPO=
while getopts "d:fhj:p:r:s:t:x" opt; do
  case $opt in
    d) WORKDIR="$OPTARG" ;;
    f) DRY_RUN=0 ;;
    t) IMGTAG="$OPTARG" ;;
    j) JAVA="$OPTARG" ;;
    p) PROJECT="$OPTARG" ;;
    r) GIT_REPO="$OPTARG" ;;
    s) RELEASE_STEP="$OPTARG" ;;
    x) DEBUG=1 ;;
    h) usage ;;
    ?) error "Invalid option. Run with -h for help." ;;
  esac
done
shift $((OPTIND-1))
if (( $# > 0 )); then
  error "Arguments can only be provided with option flags, invalid args: $*"
fi
export DEBUG

if [ -z "$WORKDIR" ] || [ ! -d "$WORKDIR" ]; then
  error "Work directory (-d) must be defined and exist. Run with -h for help."
fi

if [ -d "$WORKDIR/output" ]; then
  read -r -p "Output directory already exists. Overwrite and continue? [y/n] " ANSWER
  if [ "$ANSWER" != "y" ]; then
    error "Exiting."
  fi
fi

if [ -f "${WORKDIR}/gpg-proxy.ssh.pid" ] || \
   [ -f "${WORKDIR}/gpg-proxy.cid" ] || \
   [ -f "${WORKDIR}/release.cid" ]; then
  read -r -p "container/pid files from prior run exists. Overwrite and continue? [y/n] " ANSWER
  if [ "$ANSWER" != "y" ]; then
    error "Exiting."
  fi
fi

cd "$WORKDIR"
rm -rf "$WORKDIR/output"
rm -rf "${WORKDIR}/gpg-proxy.ssh.pid" "${WORKDIR}/gpg-proxy.cid" "${WORKDIR}/release.cid"
mkdir "$WORKDIR/output"

banner "Gathering release details."
HOST_OS="$(get_host_os)"
get_release_info

banner "Setup"

# Place all RM scripts and necessary data in a local directory that must be defined in the command
# line. This directory is mounted into the image. Its WORKDIR, the arg passed with -d.
for f in "$SELF"/*; do
  if [ -f "$f" ]; then
    cp "$f" "$WORKDIR"
  fi
done

# We need to import that public key in the container in order to use the private key via the agent.
GPG_KEY_FILE="$WORKDIR/gpg.key.public"
log "Exporting public key for ${GPG_KEY}"
fcreate_secure "$GPG_KEY_FILE"
$GPG "${GPG_ARGS[@]}" --export "${GPG_KEY}" > "${GPG_KEY_FILE}"

function cleanup {
  local id
  banner "Release Cleanup"
  if is_debug; then
    log "skipping due to debug run"
    return 0
  fi
  log "details in cleanup.log"
  if [ -f "${ENVFILE}" ]; then
    rm -f "$ENVFILE"
  fi
  rm -f "$GPG_KEY_FILE"
  if [ -f "${WORKDIR}/gpg-proxy.ssh.pid" ]; then
    id=$(cat "${WORKDIR}/gpg-proxy.ssh.pid")
    echo "Stopping ssh tunnel for gpg-agent at PID ${id}" | tee -a cleanup.log
    kill -9 "${id}" >>cleanup.log 2>&1 || true
    rm -f "${WORKDIR}/gpg-proxy.ssh.pid" >>cleanup.log 2>&1
  fi
  if [ -f "${WORKDIR}/gpg-proxy.cid" ]; then
    id=$(cat "${WORKDIR}/gpg-proxy.cid")
    echo "Stopping gpg-proxy container with ID ${id}" | tee -a cleanup.log
    docker kill "${id}" >>cleanup.log 2>&1 || true
    rm -f "${WORKDIR}/gpg-proxy.cid" >>cleanup.log 2>&1
    # TODO we should remove the gpgagent volume?
  fi
  if [ -f "${WORKDIR}/release.cid" ]; then
    id=$(cat "${WORKDIR}/release.cid")
    echo "Stopping release container with ID ${id}" | tee -a cleanup.log
    docker kill "${id}" >>cleanup.log 2>&1 || true
    rm -f "${WORKDIR}/release.cid" >>cleanup.log 2>&1
  fi
}

trap cleanup EXIT

log "Host OS: ${HOST_OS}"
if [ "${HOST_OS}" == "DARWIN" ]; then
  run_silent "Building gpg-agent-proxy image with tag ${IMGTAG}..." "docker-proxy-build.log" \
    docker build --build-arg "UID=${UID}" --build-arg "RM_USER=${USER}" \
        --tag "org.apache.hbase/gpg-agent-proxy:${IMGTAG}" "${SELF}/mac-sshd-gpg-agent"
fi

run_silent "Building hbase-rm image with tag $IMGTAG..." "docker-build.log" \
  docker build --tag "org.apache.hbase/hbase-rm:$IMGTAG" --build-arg "UID=$UID" \
      --build-arg "RM_USER=${USER}" "$SELF/hbase-rm"

banner "Final prep for container launch."
log "Writing out environment for container."
# Write the release information to a file with environment variables to be used when running the
# image.
ENVFILE="$WORKDIR/env.list"
fcreate_secure "$ENVFILE"

cat > "$ENVFILE" <<EOF
PROJECT=$PROJECT
DRY_RUN=$DRY_RUN
SKIP_TAG=$SKIP_TAG
RUNNING_IN_DOCKER=1
GIT_BRANCH=$GIT_BRANCH
NEXT_VERSION=$NEXT_VERSION
RELEASE_VERSION=$RELEASE_VERSION
RELEASE_TAG=$RELEASE_TAG
GIT_REF=$GIT_REF
ASF_USERNAME=$ASF_USERNAME
GIT_NAME=$GIT_NAME
GIT_EMAIL=$GIT_EMAIL
GPG_KEY=$GPG_KEY
ASF_PASSWORD=$ASF_PASSWORD
RELEASE_STEP=$RELEASE_STEP
API_DIFF_TAG=$API_DIFF_TAG
HOST_OS=$HOST_OS
EOF

JAVA_MOUNT=()
if [ -n "$JAVA" ]; then
  echo "JAVA_HOME=/opt/hbase-java" >> "$ENVFILE"
  JAVA_MOUNT=(--mount "type=bind,src=${JAVA},dst=/opt/hbase-java,readonly")
fi

#TODO some debug output would be good here
GIT_REPO_MOUNT=()
if [ -n "${GIT_REPO}" ]; then
  case "${GIT_REPO}" in
    # skip the easy to identify remote protocols
    ssh://*|git://*|http://*|https://*|ftp://*|ftps://*) ;;
    # for sure local
    /*)
      GIT_REPO_MOUNT=(--mount "type=bind,src=${GIT_REPO},dst=/opt/hbase-repo,consistency=delegated")
      echo "HOST_GIT_REPO=${GIT_REPO}" >> "${ENVFILE}"
      GIT_REPO="/opt/hbase-repo"
      ;;
    # on the host but normally git wouldn't use the local optimization
    file://*)
      log "Converted file:// git repo to a local path, which changes git to assume --local."
      GIT_REPO_MOUNT=(--mount "type=bind,src=${GIT_REPO#file://},dst=/opt/hbase-repo,consistency=delegated")
      echo "HOST_GIT_REPO=${GIT_REPO}" >> "${ENVFILE}"
      GIT_REPO="/opt/hbase-repo"
      ;;
    # have to decide if it's a local path or the "scp-ish" remote
    *)
      declare colon_remove_prefix;
      declare slash_remove_prefix;
      declare local_path;
      colon_remove_prefix="${GIT_REPO#*:}"
      slash_remove_prefix="${GIT_REPO#*/}"
      if [ "${GIT_REPO}" = "${colon_remove_prefix}" ]; then
        # if there was no colon at all, we assume this must be a local path
        local_path="no colon at all"
      elif [ "${GIT_REPO}" != "${slash_remove_prefix}" ]; then
        # if there was a colon and there is no slash, then we assume it must be scp-style host
        # and a relative path

        if [ "${#colon_remove_prefix}" -lt "${#slash_remove_prefix}" ]; then
          # Given the substrings made by removing everything up to the first colon and slash
          # we can determine which comes first based on the longer substring length.
          # if the slash is first, then we assume the colon is part of a path name and if the colon
          # is first then it is the seperator between a scp-style host name and the path.
          local_path="slash happened before a colon"
        fi
      fi
      if [ -n "${local_path}" ]; then
        # convert to an absolute path
        GIT_REPO="$(cd "$(dirname "${ORIG_PWD}/${GIT_REPO}")"; pwd)/$(basename "${ORIG_PWD}/${GIT_REPO}")"
        GIT_REPO_MOUNT=(--mount "type=bind,src=${GIT_REPO},dst=/opt/hbase-repo,consistency=delegated")
        echo "HOST_GIT_REPO=${GIT_REPO}" >> "${ENVFILE}"
        GIT_REPO="/opt/hbase-repo"
      fi
      ;;
  esac
  echo "GIT_REPO=${GIT_REPO}" >> "${ENVFILE}"
fi

GPG_PROXY_MOUNT=()
if [ "${HOST_OS}" == "DARWIN" ]; then
  GPG_PROXY_MOUNT=(--mount "type=volume,src=gpgagent,dst=/home/${USER}/.gnupg/")
  log "Setting up GPG agent proxy container needed on OS X."
  log "    we should clean this up for you. If that fails the container ID is below and in " \
      "gpg-proxy.cid"
  #TODO the key pair used should be configurable
  docker run --rm -p 62222:22 \
     --detach --cidfile "${WORKDIR}/gpg-proxy.cid" \
     --mount \
     "type=bind,src=${HOME}/.ssh/id_rsa.pub,dst=/home/${USER}/.ssh/authorized_keys,readonly" \
     "${GPG_PROXY_MOUNT[@]}" \
     "org.apache.hbase/gpg-agent-proxy:${IMGTAG}"
  # gotta trust the container host
  ssh-keyscan -p 62222 localhost 2>/dev/null | sort > "${WORKDIR}/gpg-agent-proxy.ssh-keyscan"
  sort "${HOME}/.ssh/known_hosts" | comm -1 -3 - "${WORKDIR}/gpg-agent-proxy.ssh-keyscan" \
      > "${WORKDIR}/gpg-agent-proxy.known_hosts"
  if [ -s "${WORKDIR}/gpg-agent-proxy.known_hosts" ]; then
    log "Your ssh known_hosts does not include the entries for the gpg-agent proxy container."
    log "The following entry(ies) are missing:"
    sed -e 's/^/    /' "${WORKDIR}/gpg-agent-proxy.known_hosts"
    read -r -p "Okay to add these entries to ${HOME}/.ssh/known_hosts? [y/n] " ANSWER
    if [ "$ANSWER" != "y" ]; then
      error "Exiting."
    fi
    cat "${WORKDIR}/gpg-agent-proxy.known_hosts" >> "${HOME}/.ssh/known_hosts"
  fi
  log "Launching ssh reverse tunnel from the container to gpg agent."
  log "    we should clean this up for you. If that fails the PID is in gpg-proxy.ssh.pid"
  ssh -p 62222 -R "/home/${USER}/.gnupg/S.gpg-agent:$(gpgconf --list-dir agent-extra-socket)" \
      -i "${HOME}/.ssh/id_rsa" -N -n localhost >gpg-proxy.ssh.log 2>&1 &
  echo $! > "${WORKDIR}/gpg-proxy.ssh.pid"
else
  # Note that on linux we always directly mount the gpg agent's extra socket to limit what the
  # container can ask the gpg-agent to do.
  # When working on a remote linux machine you should be sure to forward both the remote machine's
  # agent socket and agent extra socket to your local gpg-agent's extra socket. See the README.txt
  # for an example.
  GPG_PROXY_MOUNT=(--mount \
      "type=bind,src=$(gpgconf --list-dir agent-extra-socket),dst=/home/${USER}/.gnupg/S.gpg-agent")
fi

banner "Building $RELEASE_TAG; output will be at $WORKDIR/output"
log "We should clean the container up when we are done. If that fails then the container ID " \
    "is in release.cid"
echo
# Where possible we specify "consistency=delegated" when we do not need host access during the
# build run. On Mac OS X specifically this gets us a big perf improvement.
cmd=(docker run --rm -ti \
  --env-file "$ENVFILE" \
  --cidfile "${WORKDIR}/release.cid" \
  --mount "type=bind,src=${WORKDIR},dst=/home/${USER}/hbase-rm,consistency=delegated" \
  "${JAVA_MOUNT[@]}" \
  "${GIT_REPO_MOUNT[@]}" \
  "${GPG_PROXY_MOUNT[@]}" \
  "org.apache.hbase/hbase-rm:$IMGTAG")
echo "${cmd[*]}"
"${cmd[@]}"


text:
/* global $:false Handlebars:false marked:false MathJax:false */
$.fn.serializeJson = function() {
  var obj = {};
  $.each(this.serializeArray(), function() {
    obj[this.name] = this.value;
  });
  return obj;
};
$.fn.isVisible = function() {
  return $.expr.filters.visible(this[0]);
};

$(function(){

  var questionList = [];
  var userInfo = {};

  $('#lang').on('change', function(ev) {
    localStorage.setItem('lang', $(ev.currentTarget).val());
  });
  $('#lang').val(localStorage.getItem('lang'));

  loadQuestionList()
    .then(formSettings)
    .then(loadUserInfo);

  function loadQuestionList() {
    return fetch('./questionList.json')
      .then(function(res) { return res.json(); })
      .then(function(json) {
        questionList = json.map(function(f) { return f.split('-'); })
          .map(function(a) { return a.concat(a.splice(1).join('-')); })
          .map(function(a) { return {
            point: parseInt(a[0], 10),
            name: a[1],
            question: a.join('-')
          }; });
        return questionList;
      })
      .then(function(list) {
        var $qListContainer = $('main#qList');
        var source = $('template', $qListContainer).html();
        var template = Handlebars.compile(source);
        list.forEach(function(qInfo) {
          var $panel = $(template(qInfo));
          $('a.toggle-details', $panel).on('click', toggleDetails);
          $qListContainer.append($panel);
        });
      });
  }

  function formSettings() {
    $('form').on('submit', function(ev) {
      ev.preventDefault();
    });
    $('#qList .panel form').on('submit', submitCode);
    $('#login button').on('click', login);
    $('#logout button').on('click', logout);
  }

  function submitCode(ev) {
    var $target = $(ev.currentTarget);
    var $parent = $target.parent();
    $('.alert', $parent).hide(250);

    var code = $('textarea', $target).val();
    var lang = $('select#lang').val();

    return fetch('./api/submit', {
      credentials: 'same-origin',
      method: 'post',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        question: $target.data('question'),
        code: code,
        lang: lang
      })
    })
    .then(function(res) { return res.json(); })
    .then(function(json) {
      if (json.status !== 'ok') {
        $('.alert-warning', $parent).text(json.message).show(250);
      } else {
        var message = $('<span>').text('Your submitID is ');
        var id = $('<a>')
          .attr({
            href: '/search.html#_id=' + json.info._id,
            target: '_blank'
          })
          .text(json.info._id);
        $('.alert-info', $parent).empty().append(message).append(id).show(250);
      }
    })
    .then(loadUserInfo);
  }

  function login(ev) {
    var action = $(ev.currentTarget).data('action');
    var $loginForm = $('form#login');
    var query = $loginForm.serializeJson();

    var opts = {
      credentials: 'same-origin',
      method: 'post',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(query)
    };

    var promise = (action === 'signup') ?
      fetch('./api/signup', opts)
        .then(function(res) { return res.json(); })
        .then(function(json) { if (json.status !== 'ok') throw json; }) :
      Promise.resolve();

    return promise.then(function() {
      return fetch('./api/auth', opts);
    })
    .then(function(res) { return res.json(); })
    .then(function(json) { if (json.status !== 'ok') throw json; })
    .then(loadUserInfo)
    .catch(function(json) {
      alert(json.message);
    });
  }

  function loadUserInfo() {
    return fetch('./api/user', {
      credentials: 'same-origin'
    })
    .then(function(res) { return res.json(); })
    .then(function(json) {
      if (json.status === 'ok') {
        userInfo = json.user;
        $('#userStatus').text(userInfo.username + '(' + userInfo.score + 'pts)');
        $('#login').hide(0);
        $('#logout').show(0);
      } else {
        throw new Error(json.message);
      }
    })
    .then(loadSubmitted);
  }

  function logout() {
    return fetch('./api/logout', {
      credentials: 'same-origin'
    }).then(function() {
      $('#userStatus').text('');
      $('#login').show(0);
      $('#logout').hide(0);
      $('.panel .label-info').hide(0);
      userInfo = {};
    })
    .then(loadUserInfo);
  }

  function loadSubmitted() {
    return fetch('./api/scores', {
      credentials: 'same-origin',
      method: 'post',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        username: userInfo.username
      })
    })
    .then(function(res) { return res.json(); })
    .then(function(json) {
      if (json.status !== 'ok') return;
      $('.panel .label-info').hide(0);
      json.scores.forEach(function(sInfo) {
        $('.panel[data-question="' + sInfo.question + '"]')
          .find('.label-info').show(0);
      });
    });
  }

  function toggleDetails(ev) {
    ev.preventDefault();

    var $target = $(ev.currentTarget);
    var question = $target.data('question');
    var $details = $('.panel[data-question="' + question + '"] .details');
    if (!$details.isVisible()) {
      fetch('/' + question + '/README.md')
        .then(function(res) { return res.text(); })
        .then(function(md) {
          $details.html(md);
          return new Promise(function(resolve) {
            this.resolve = resolve;
            MathJax.Hub.Queue(
              ['Typeset', MathJax.Hub, $details[0]],
              ['resolve', this]
            );
          });
        })
        .then(function() {
          var renderer = new marked.Renderer();
          (function() {
            var link = renderer.link.bind(renderer);
            renderer.link = function(href, title, text) {
              if (!href.match(/^http/)) href = '/' + question + '/' + href;
              return link(href, title, text);
            };
            var image = renderer.image.bind(renderer);
            renderer.image = function(href, title, text) {
              if (!href.match(/^http/)) href = '/' + question + '/' + href;
              return image(href, title, text);
            };
          })();
          $details.html(marked($details.html() + '\n\n----', {
            sanitize: false, renderer: renderer
          }));
          $('a', $details).attr({ target: '_blank' });
        })
        .then(function() {
          return fetch('./api/scores', {
            method: 'post',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              question: question
            })
          })
          .then(function(res) { return res.json(); });
        })
        .then(function(json) {
          if (json.status === 'ok') {
            $details.append($('<p>').text(json.scores.length + ' users submitted.'));
          }
          $details.show(500);
        });
    } else {
      $details.hide(500);
    }
  }

});

redpajama_set_name: RedPajamaGithub


text:
<?php

class AssetManager {

    private static $asset_columns = '`asset`.`id`, `asset`.`name`, `asset`.`description`, `asset`.`logoUrl`, `asset`.`linkUrl`, `asset`.`videoUrl`, `asset`.`attachments`';
    public static function getTable($name) {
        return db::query("SELECT * FROM `{$name}`;");
    }
    public static function getAssets($language = LANGUAGE, $keyword = '') {

        $asset_columns = self::$asset_columns;
        if(empty($keyword)) {
            return db::query("SELECT {$asset_columns} FROM `asset` WHERE `language` = ?;", $language);
        }
        return db::query("SELECT {$asset_columns} FROM `asset` WHERE `language` = ? AND `name` LIKE ?;", [ $language, "%{$keyword}%" ]);
    }

    public static function getAssetsByCatalogName($key, $name, $language = LANGUAGE) {

        $result = [];
        $asset_columns = self::$asset_columns;
        if($key === KEY_INDUSTRY) {
            $result = db::query("SELECT {$asset_columns} FROM `asset`
                JOIN `catalog` ON `catalog`.`id` = `asset`.`idindustry`
                WHERE ((`catalog`.`key` = ? AND `catalog`.`name` LIKE ?) OR `catalog`.`id` < 0) AND `catalog`.`language` = ?;",
                [$key, $name, $language]
            );
        }
        else {
            $result =  db::query("SELECT {$asset_columns} FROM `asset`
                JOIN `catalog_to_asset` ON `catalog_to_asset`.`idasset` = `asset`.`id`
                JOIN `catalog` ON `catalog`.`id` = `catalog_to_asset`.`idcatalog`
                WHERE `catalog`.`key` = ? AND `catalog`.`name` LIKE ?;",
                [$key, $name]
            );
        }

        // todo: to avoid addtional query, maybe store ids in master table
        $result = self::fetchAttachments($result);

        return $result;
    }

    private static function fetchAttachments($result) {
        if(count($result) > 0) {
            foreach($result as $key => $val) {

                $list = [];
                $query = json_decode($val['attachments'], TRUE);

                if(is_array($query)) {
                    foreach($query as $k => $v) {
                        //array_push($list, "/api/v1/assets/attachment/{$v['id']}");
                        array_push($list, $v['id']);
                    }
                }
                $result[$key]['attachments'] = $list;
            }
        }
        return $result;
    }

    public static function getAssetsByCatalogId($key, $id) {

        $result = [];
        $asset_columns = self::$asset_columns;
        if($key === KEY_INDUSTRY) {
            $result = db::query("SELECT {$asset_columns} FROM `asset` WHERE `asset`.`idindustry` = ?", array($id));
        }
        else {
            $result =  db::query("SELECT {$asset_columns} FROM `asset`
                JOIN `catalog_to_asset` ON `catalog_to_asset`.`idasset` = `asset`.`id`
                JOIN `catalog` ON `catalog`.`id` = `catalog_to_asset`.`idcatalog`
                WHERE `catalog`.`key` = ? AND `catalog`.`id` = ?;",
                [$key, $id]
            );
        }

        // todo: to avoid addtional query, maybe store ids in master table
        $result = self::fetchAttachments($result);

        return $result;
    }

    public static function getAssetsByCompanyId($id) {

        $result = [];
        $asset_columns = self::$asset_columns;

        $result = db::query("SELECT {$asset_columns} FROM `asset` WHERE `videourl` != '' ORDER BY RAND() LIMIT 10 ;"); //, array($id)

        $result = self::fetchAttachments($result);

        return $result;
    }

    public static function addAsset($name, $idindustry, $description, $logourl, $videourl, $linkurl, $language) {

        return db::insert(
            "INSERT INTO `asset` (`name`, `idindustry`, `description`, `logourl`, `videourl`, `linkurl`, `language`) VALUES (?,?,?,?,?,?,?);",
            [$name, $idindustry, $description, $logourl, $videourl, $linkurl, $language]
        );
    }

    public static function updateAsset($id, $name, $idindustry, $description, $logourl, $videourl, $linkurl, $language) {

        return db::update(
            "UPDATE `asset` SET `name` = ?, `idindustry` = ?, `description` = ?, `logourl` = ?, `videourl` = ?, `linkurl` = ?, `language` = ? WHERE `id` = ?;",
            [$name, $idindustry, $description, $logourl, $videourl, $linkurl, $language, $id]
        );
    }

    public static function deleteAsset($id) {

        return db::execute('DELETE FROM `asset` WHERE `id` = ?;', $id);
    }

    public static function deleteCatalogToAsset($id) {

        return db::execute("DELETE FROM `catalog_to_asset` WHERE `idasset` = ?;", $id);
    }

    public static function addCatalogToAsset($key, $idasset, $idcatalog) {

        return db::insert(
            "INSERT INTO `catalog_to_asset` (`key`, `idasset`, `idcatalog`) VALUES (?,?,?);",
            [$key, $idasset, $idcatalog]
        );
    }

    public static function getFileIDList($id) {

        return db::query("SELECT `id` FROM `asset_to_file` WHERE `idasset` = ?", $id);
    }

    public static function readFile($id) {

        return db::queryFirst("SELECT `*` FROM `asset_to_file` WHERE `id` = ?", $id);
    }

    public static function addFiles($id, $files) {

        foreach($files as $file) {
            $size = $file->getSize();
            if($size == 0) continue;

            $binary = file_get_contents($file->file);
            $name = $file->getClientFilename();
            $type = $file->getClientMediaType();

            db::insert(
                "INSERT INTO `asset_to_file` (`idasset`, `binary`, `name`, `size`, `type`) VALUES (?,?,?,?,?);",
                [$id, $binary, $name, $size, $type]
            );

        }

    }

    public static function updateFileIds($id) {
        $result = self::getFileIDList($id);
        $data = json_encode($result);
        return db::execute("UPDATE `asset` SET `attachments` = ? WHERE `id` = ?", array($data, $id));
    }

    public static function deleteFile($id) {

        return db::execute("DELETE FROM `asset_to_file` WHERE `id` = ?", $id);
    }

}


text:
package sun.awt;

/**
 * Used for replacing window owner with another non-Swing window.
 * It is useful in case of JavaFX-Swing interop:
 * it helps to keep Swing dialogs above its owner(JavaFX stage).
 */

public interface OverrideNativeWindowHandle {

    /**
     * Replaces an owner window with a window with provided handle.
     * @param handle native window handle
     */
    void overrideWindowHandle(final long handle);
}


text:
<?php

namespace backend\models;

use Yii;

/**
 * This is the model class for table "inventory_parts_ligament".
 *
 * @property integer $id
 * @property string $invnum_inventory
 * @property integer $id_inventory_parts
 * @property integer $amount
 *
 * @property Inventory $invnumInventory
 * @property InventoryParts $idInventoryParts
 */
class InventoryPartsLigament extends \yii\db\ActiveRecord
{
    public static function getDb()
    {
        return \Yii::$app->db4;
    }
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'inventory_parts_ligament';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['invnum_inventory', 'id_inventory_parts', 'amount_ipl'], 'required'],
            [['invnum_inventory'], 'string'],
            [['id_inventory_parts', 'amount_ipl'], 'integer']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'invnum_inventory' => 'Инв. объекта',
            'id_inventory_parts' => 'Запчасть',
            'amount_ipl' => 'Шт.',
            'typepartsName' => 'Тип запчасти'
        ];
    }

    public function getTypepartsName()
    {
        return $this->idInventoryParts->typepartsName;
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getInvnumInventory()
    {
        return $this->hasOne(Inventory::className(), ['invnum' => 'invnum_inventory']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getIdInventoryParts()
    {
        return $this->hasOne(InventoryParts::className(), ['id' => 'id_inventory_parts']);
    }
}


text:
using DDW.V2D;
using Microsoft.Xna.Framework.Graphics;
using V2DRuntime.Attributes;
using Box2D.XNA;
using SharpNeatLib.Maths;
using System;

namespace Sleepwalker.Components
{
    public class TiltElevator : V2DSprite
    {
        [RevoluteJointAttribute(lowerAngle = -.1f, upperAngle = .1f, enableLimit = true)]
        public RevoluteJoint rj;
        [RevoluteJointAttribute(lowerAngle = -.1f, upperAngle = .1f, enableLimit = true)]
        public RevoluteJoint rt;

        [PrismaticJointAttribute(enableMotor = true, maxMotorForce = 80000, motorSpeed = -5)]
        public PrismaticJoint pj;

        [V2DSpriteAttribute(isSensor = true)]
        public V2DSprite[] buildBeam;

        [V2DSpriteAttribute(isSensor = true)]
        public V2DSprite[] invBeam;

        [V2DSpriteAttribute()]
        public V2DSprite seesawBeam;

        private int speed = 5;
        private int direction = 1;
        private static Random rnd = new Random((int)DateTime.Now.Ticks);

        public TiltElevator(Texture2D texture, V2DInstance instance) : base(texture, instance)
		{
        }

        public int Speed {
            get { return speed; }
            set
            {
                speed = value;
                direction = rnd.Next(2) > .5 ? 1 : -1;
                pj.SetMotorSpeed(speed * direction);
            }
        }

        public override void Initialize()
        {
            base.Initialize();
        }

        public override void Update(Microsoft.Xna.Framework.GameTime gameTime)
        {
            base.Update(gameTime);

            if (pj != null)
            {
                if (pj._limitState == LimitState.AtUpper && direction == 1)
                {
                    direction = -1;
                    pj.SetMotorSpeed(speed * direction);
                }
                else if (pj._limitState == LimitState.AtLower && direction == -1)
                {
                    direction = 1;
                    pj.SetMotorSpeed(speed * direction);
                }
            }
        }
    }
}


text:
\documentclass[a4paper]{article}

%\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{graphicx}
\usepackage{scrextend}
\usepackage[colorinlistoftodos]{todonotes}
\usepackage [bookmarks=true,backref=page, hyperfigures=true, pdfpagelabels=false] {hyperref}
%===========================================================
% BEGIN Hyperlink Setup
%===========================================================
\hypersetup{
									  % TCM Added more precise definition and options for Hyperref package.
									  % TCM Comment out or change hyperref preferences
									  % TCM \hypersetup should be loaded last
    bookmarksopen=true,				  % True: Open bookmark tree
    bookmarksnumbered=true, 		  % True: put section numbers in bookmarks
    breaklinks=true,				  % True: split the url over multiple lines
    linktocpage, 					  % Makes the page number of TOC the link vs the text
%    pagebackref=true,				  % True: Links references back to referring page
    unicode=false,             		  % Non-Latin characters in Acrobat bookmarks
    pdfnewwindow=true,         		  % True: URL links in new window
    plainpages=false, 				  % True: do page number anchors as plain Arabic
    pdffitwindow=false,        		  % Window fit to page when opened
    pdfmenubar=true,           		  % Show Acrobat menu
    pdfstartview={FitH},       		  % Fits the width of the page to the window
    pdftoolbar=true, 				  % Show Acrobat toolbar
    pdfauthor={Ted C. Munger, IV}, 	  % Author in PDF document properties
    pdfcreator={Ted C. Munger, IV},   % Creator of the document in PDF document properties
    pdfkeywords={Dedman} {Lyle Engineering} {SMU} {Latex} {template} {Ted C. Munger}, % List of keywords in PDF document properties
    pdfproducer={Ted C. Munger, IV}, 		  % Producer of the document in PDF document properties
    pdfsubject={SMU Dedman / Lyle Engineering Latex Template},   % Subject of the document in PDF document properties
    pdftitle={Dedman/Lyle LaTeX Dissertation Template, v2016 Package}, 				  % Title in PDF document properties
    colorlinks=true, 				  % False: boxed links; true: colored links
    linkcolor=blue, 				  % Color of internal links
    citecolor=blue, 				  % Color of links to bibliography
    filecolor=magenta, 				  % Color of file links
    urlcolor=cyan 					  % Color of external links
}
%===========================================================
% END Hyperlink Setup
%===========================================================

\title{Dedman/Lyle LaTeX Dissertation Template, v2016 Package}

\author{Ted C. Munger\thanks{Department of Engineering Management, Information, and Systems, Lyle School of Engineering, Southern Methodist University, Dallas, TX 75275 USA, theodore@smu.edu}}

\date{\today}

\begin{document}
\maketitle

\begin{abstract}
This short article describes the files required for the Dedman/Lyle LaTeX Dissertation Template, v.2016 and lists helpful tips in getting started with your first \LaTeX {} project.
\end{abstract}

\section{Introduction}

This package was created to help Dedman and Lyle Engineering students get started with their thesis, dissertation, or praxis document using \LaTeX {}. While helpful tips on \LaTeX {} is included this is not intended to be a tutorial on how to write using \LaTeX {} typesetting language.  To use the package, unzip DedmanLatexTemplate.zip to your computer and open DedmanTemplate.tex in the \LaTeX {} editor of your choice.

\section{Files Included In This Package}\label{sec:files}

\addtokomafont{labelinglabel}{\bf}
\begin{labeling}{Dissertation\_Image.png} % Option is the longest label for indenting
	\item[DedmanTemplate.tex] This is the main file that organizes your paper. Chapter and appendix .tex files are included here as well as your bibliography file.
    \item[DedmanTemplate.pdf] The main template file with example text compiled into a PDF.
    \item[FrontPages.tex] This file constructs the required first pages of your thesis, dissertation, or praxis.  The file is filled with example data and needs to be replaces with your document and personal information.
    \item[packages.tex] This file contains the list of packages that you want to utilize in constructing your \LaTeX {} document.  The file has been pre-populated with many common packages as well as some specialized ones.  Use this file to add or comment out packages for your specific needs.
    \item[DL\_thesis\_v2016] This is the style file that sets up your document to the 2016 SMU Dedman and Lyle Engineering Thesis Standards.
    \item[customcommands.tex] This is where you place all your custom \LaTeX {} commands should you need to create them.
    \item[symbols.tex] This is where you place all your specialized symbols should you need to create a List of Symbols in your document.  Not often used and is commented out in the FrontPages.tex.  You will have to uncomment if you want to use symbols.tex.
    \item[.gitignore] This is a list of file type extensions to have Git or GitHub to ignore when replicating with a repository.  See the below for more information about Git.
    \item[readme.tex] This file.
    \item[readme.pdf] This file compiled into a PDF.
    \item[abstract.tex] An example abstract.
    \item[acknow.tex] An example document acknowledgment.
    \item[chap1.tex] An example chapter one file.
    \item[chap2.tex] An example chapter two file.
    \item[app.tex] An example appendix file.
    \item[dedmanbib.bib] An example bibliography file.
    \item[fig folder] Folder for all example figures.
    \item[Dissertation\_Image.png] An example figure located in the fig folder.
    \item[frog.jpg] An example figure for this document.
 \end{labeling}

\section{Some \LaTeX {}{} Tools} \label{sec:tools}

Here is a list of some following tools to create a document in \LaTeX {}:

\addtokomafont{labelinglabel}{\bf}
\begin{labeling}{Excel-to-\LaTeX {}} % Option is the longest label for indenting
	\item[Overleaf.com] Overleaf is an online \LaTeX {} editor that does not require any \LaTeX {} binaries to be installed on your PC/Mac.  Overleaf is the easiest way to get started. Signup for a free account, create a project, upload the template files, make DedmanTemplate.tex the main file, and start typing.  The free account could be all you need, but if you have many files and images, you may need to upgrade to a student account. The drawback is that you have to be online.
    \item[TexStudio] TexStudio is a \LaTeX {} editing package that can be installed in Windows, Linux, OSX, and OS2.  It organizes the document as a project and makes it easy to see the entire structure of your document.  It compiles the pdf and allows you to view both side by side.  See \url{http://www.texstudio.org/} to learn more.
 	\item[GitHub] GitHub is a web-based Git repository hosting service. It offers distributed revision control and source code management (SCM).  GitHub can be used alone as a backup/versioning repository or with Overleaf.  Using with Overleaf allows you to edit your Overleaf files off-line.  Any changes in Overleaf or on your PC can be synced.  Always sync with GitHub before you edit on your PC and after you make changes on your PC. This avoids change conflicts.  GitHub handles conflicts, but it is much easier to avoid them.  You do not have to be a member of GitHub to use the GitHub Desktop with Overleaf.  GitHub Desktop is available for Windows and Mac. See \url{https://desktop.github.com/},  \url{https://www.github.com/} and  \url{http://www.overleaf.com/} for more information.
    \item[JabRef] JabRef is an easy to use open source database application to keep track of all your references.  It creates the bibtex.bib file for you. It is available for Windows, Linux, and Mac OSX. A nice feature is that you can attach your article PDFs to the reference so that you can easily jump to the article without searching for it.  See \url{http://www.jabref.org/} for more information.
    \item[Excel-to-\LaTeX {}] An Excel add-in that converts Excel spreadsheets to \LaTeX {} tables. Supports the Booktabs style formatting and is a great way to create a table.  See \url{https://www.ctan.org/pkg/excel2latex?lang=en} for more information.  While the documentation says that it works up to Excel 2010, I use it in Excel 2013 with no issues.
\end{labeling}

\section{Some \LaTeX {}{} Examples from Overleaf.com} \label{sec:examples}

The following section and subsection is from Overleaf.com's sample file.  It provides a good overview of simple \LaTeX {} commands.

\subsection{How to Leave Comments}

Comments can be added to the margins of the document using the \todo{Here's a comment in the margin!} todo command, as shown in the example on the right. You can also add inline comments:

\todo[inline, color=green!40]{This is an inline comment.}

\subsection{How to Include Figures}

First you have to upload the image file (JPEG, PNG or PDF) from your computer to writeLaTeX using the upload link the project menu. Then use the includegraphics command to include it in your document. Use the figure environment and the caption command to add a number and a caption to your figure. See the code for Figure \ref{fig:frog} in this section for an example.

\begin{figure}[ht] % [ht] option places image Here, Top of page
\centering
\includegraphics[width=0.3\textwidth]{frog.jpg}
\caption{\label{fig:frog}This frog was uploaded to writeLaTeX via the project menu.}
\end{figure}

\subsection{How to Make Tables}

Use the table and tabular commands for basic tables --- see Table~\ref{tab:widgets}, for example.

\begin{table}
\centering
\begin{tabular}{l|r}
Item & Quantity \\\hline
Widgets & 42 \\
Gadgets & 13
\end{tabular}
\caption{\label{tab:widgets}An example table.}
\end{table}

\subsection{How to Write Mathematics}

\LaTeX {}{} is great at typesetting mathematics. Let $X_1, X_2, \ldots, X_n$ be a sequence of independent and identically distributed random variables with $\text{E}[X_i] = \mu$ and $\text{Var}[X_i] = \sigma^2 < \infty$, and let
$$S_n = \frac{X_1 + X_2 + \cdots + X_n}{n}
      = \frac{1}{n}\sum_{i}^{n} X_i$$
denote their mean. Then as $n$ approaches infinity, the random variables $\sqrt{n}(S_n - \mu)$ converge in distribution to a normal $\mathcal{N}(0, \sigma^2)$.

\subsection{How to Make Sections and Subsections}

Use section and subsection commands to organize your document. \LaTeX {}{} handles all the formatting and numbering automatically. Use ref and label commands for cross-references.

\subsection{How to Make Lists}

You can make lists with automatic numbering \dots

\begin{enumerate}
\item Like this,
\item and like this.
\end{enumerate}
\dots or bullet points \dots
\begin{itemize}
\item Like this,
\item and like this.
\end{itemize}
\dots or with words and descriptions \dots
\begin{description}
\item[Word] Definition
\item[Concept] Explanation
\item[Idea] Text
\end{description}

\bigskip

I hope this document and the associated template package is helpful for you.  Good luck.
- Ted C. Munger

\end{document}


text:
   package mars.venus;
   import mars.simulator.*;
	import mars.*;
   import java.util.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import java.io.*;

   /**
    * Action class for the Settings menu item to control whether or not
	 * program arguments can be entered and used.  If so, a text field
	 * will be displayed where they can be interactively entered.
    */
    public class SettingsProgramArgumentsAction extends GuiAction  {

       public SettingsProgramArgumentsAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }

       public void actionPerformed(ActionEvent e) {
		   boolean selected = ((JCheckBoxMenuItem)e.getSource()).isSelected();
		   Globals.getSettings().setProgramArguments(selected);
			if (selected) {
			   Globals.getGui().getMainPane().getExecutePane().getTextSegmentWindow().addProgramArgumentsPanel();
			} else {
			   Globals.getGui().getMainPane().getExecutePane().getTextSegmentWindow().removeProgramArgumentsPanel();
			}
      }

   }


text:
This Hydropower Projects includes:
  - Finding optimal design flow rate of a run-of-river hydropower plant
  - Optimizing operations of a pumped-storage hydropower facility


text:
#include "EP_ExodusFile.h"
#include "EP_Internals.h"
#include "EP_ParallelDisks.h"
#include "EP_SystemInterface.h"
#include "smart_assert.h"
#include <climits>
#include <cstdlib>

#include <cstddef>
#include <iostream>
#include <string>
#include <vector>

#if !defined(_WIN32)
#include <unistd.h>
#endif

#include <exodusII.h>

std::vector<int>         Excn::ExodusFile::fileids_;
std::vector<std::string> Excn::ExodusFile::filenames_;
int                      Excn::ExodusFile::processorCount_ = 0;
int                      Excn::ExodusFile::partCount_      = 0;
int                      Excn::ExodusFile::startPart_      = 0;
int                      Excn::ExodusFile::outputId_       = -1;
int                      Excn::ExodusFile::ioWordSize_     = 0;
int                      Excn::ExodusFile::cpuWordSize_    = 0;
int                      Excn::ExodusFile::mode64bit_      = 0;
std::string              Excn::ExodusFile::outputFilename_;
bool                     Excn::ExodusFile::keepOpen_          = false;
int                      Excn::ExodusFile::maximumNameLength_ = 32;

Excn::ExodusFile::ExodusFile(int processor) : myProcessor_(processor)
{
  SMART_ASSERT(processor < processorCount_)(processor)(processorCount_);
  SMART_ASSERT(fileids_.size() == (size_t)processorCount_);
  if (!keepOpen_ && processor != 0) {
    float version          = 0.0;
    int   cpu_word_size    = cpuWordSize_;
    int   io_word_size_var = ioWordSize_;
    int   mode             = EX_READ;
    mode |= mode64bit_;

    fileids_[processor] =
        ex_open(filenames_[processor].c_str(), mode, &cpu_word_size, &io_word_size_var, &version);
    if (fileids_[processor] < 0) {
      std::cerr << "Cannot open file '" << filenames_[processor] << "' - exiting" << '\n';
      exit(1);
    }
    ex_set_max_name_length(fileids_[processor], maximumNameLength_);

    SMART_ASSERT(io_word_size_var == ioWordSize_);
    SMART_ASSERT(cpu_word_size == cpuWordSize_);
  }
}

int Excn::ExodusFile::output()
{
  SMART_ASSERT(outputId_ >= 0);
  return outputId_;
}

Excn::ExodusFile::operator int() const
{
  SMART_ASSERT(fileids_[myProcessor_] >= 0);
  return fileids_[myProcessor_];
}

Excn::ExodusFile::~ExodusFile()
{
  try {
    if (!keepOpen_ && myProcessor_ != 0) {
      ex_close(fileids_[myProcessor_]);
      fileids_[myProcessor_] = -1;
    }
  }
  catch (...) {
  }
}

void Excn::ExodusFile::close_all()
{
  for (int p = 0; p < partCount_; p++) {
    if (fileids_[p] >= 0) {
      ex_close(fileids_[p]);
      fileids_[p] = -1;
    }
  }
  if (outputId_ >= 0) {
    ex_close(outputId_);
    outputId_ = -1;
  }
}

void Excn::ExodusFile::unlink_temporary_files()
{
  for (int p = 0; p < partCount_; p++) {
    if (fileids_[p] >= 0) {
      ex_close(fileids_[p]);
      unlink(filenames_[p].c_str());
      fileids_[p] = -1;
    }
  }
  if (outputId_ >= 0) {
    ex_close(outputId_);
    outputId_ = -1;
  }
}

bool Excn::ExodusFile::initialize(const SystemInterface &si, int start_part, int part_count,
                                  int cycle, bool joining_subcycle)
{
  processorCount_ = si.processor_count(); // Total number processors
  partCount_      = part_count;           // Total parts we are processing
  startPart_      = start_part;           // Which one to start with
  SMART_ASSERT(partCount_ + startPart_ <= processorCount_)(partCount_)(startPart_)(processorCount_);

  // EPU always wants entity (block, set, map) ids as 64-bit quantities...
  mode64bit_ = EX_IDS_INT64_API;
  if (si.int64()) {
    mode64bit_ |= EX_ALL_INT64_API;

    // For output...
    mode64bit_ |= EX_ALL_INT64_DB;
  }

  // See if we can keep files open
  int max_files = get_free_descriptor_count();
  if (partCount_ <= max_files) {
    keepOpen_ = true;
    if (cycle == 0) {
      if ((si.debug() & 1) != 0) {
        std::cout << "Files kept open... (Max open = " << max_files << ")\n\n";
      }
    }
  }
  else {
    keepOpen_ = false;
    if (cycle == 0) {
      std::cout << "Single file mode... (Max open = " << max_files << ")\n"
                << "Consider using the -subcycle option for faster execution...\n\n";
    }
  }

  fileids_.resize(processorCount_);
  filenames_.resize(processorCount_);

  std::string curdir        = si.cwd();
  std::string file_prefix   = si.basename();
  std::string exodus_suffix = si.exodus_suffix();

  std::string root_dir = si.root_dir();
  std::string sub_dir  = si.sub_dir();

  ParallelDisks disks;
  disks.Raid_Offset(si.raid_offset());
  disks.Number_of_Raids(si.raid_count());

  float version = 0.0;

  // create exo names
  for (int p = 0; p < partCount_; p++) {
    std::string name = file_prefix;
    if (!exodus_suffix.empty()) {
      name += "." + exodus_suffix;
    }

    int proc = p + startPart_;
    if (joining_subcycle) {
      name = si.output_filename();
      disks.rename_file_for_mp("", "", name, proc, processorCount_);
    }
    else {
      disks.rename_file_for_mp(root_dir, sub_dir, name, proc, processorCount_);
    }
    filenames_[p] = name;

    if (p == 0) {
      int cpu_word_size    = sizeof(float);
      int io_word_size_var = 0;
      int mode             = EX_READ;
      mode |= mode64bit_;
      int exoid = ex_open(filenames_[p].c_str(), mode, &cpu_word_size, &io_word_size_var, &version);
      if (exoid < 0) {
        std::cerr << "Cannot open file '" << filenames_[p] << "'" << '\n';
        return false;
      }

      int int64db = ex_int64_status(exoid) & EX_ALL_INT64_DB;
      if (int64db != 0) {
        // If anything stored on input db as 64-bit int, then output db will have
        // everything stored as 64-bit ints and all API functions will use 64-bit
        mode64bit_ |= EX_ALL_INT64_API;
        mode64bit_ |= EX_ALL_INT64_DB;
      }

      int max_name_length = ex_inquire_int(exoid, EX_INQ_DB_MAX_USED_NAME_LENGTH);
      if (max_name_length > maximumNameLength_) {
        maximumNameLength_ = max_name_length;
      }

      ex_close(exoid);

      if (io_word_size_var < static_cast<int>(sizeof(float))) {
        io_word_size_var = sizeof(float);
      }

      ioWordSize_  = io_word_size_var;
      cpuWordSize_ = io_word_size_var;
    }

    if (keepOpen_ || p == 0) {
      int io_word_size_var = 0;
      int mode             = EX_READ;
      // All entity ids (block, sets) are read/written as 64-bit...
      mode |= mode64bit_;
      fileids_[p] =
          ex_open(filenames_[p].c_str(), mode, &cpuWordSize_, &io_word_size_var, &version);
      if (fileids_[p] < 0) {
        std::cerr << "Cannot open file '" << filenames_[p] << "'" << '\n';
        return false;
      }
      ex_set_max_name_length(fileids_[p], maximumNameLength_);
      SMART_ASSERT(ioWordSize_ == io_word_size_var)(ioWordSize_)(io_word_size_var);
    }

    if (((si.debug() & 64) != 0) || p == 0 || p == partCount_ - 1) {
      std::cout << "[" << cycle << "] Input(" << p << "): '" << name.c_str() << "'" << '\n';
      if (((si.debug() & 64) == 0) && p == 0) {
        std::cout << "..." << '\n';
      }
    }
  }

  if ((mode64bit_ & EX_ALL_INT64_DB) != 0) {
    if (cycle == 0) {
      std::cout << "Input files contain 8-byte integers.\n";
    }
    si.set_int64();
  }

  return true;
}

bool Excn::ExodusFile::create_output(const SystemInterface &si, int cycle)
// Create output file...
{
  std::string curdir        = si.cwd();
  std::string file_prefix   = si.basename();
  std::string output_suffix = si.output_suffix();

  outputFilename_ = file_prefix;
  if (!output_suffix.empty()) {
    outputFilename_ += "." + output_suffix;
  }

  if ((curdir.length() != 0u) && !Excn::is_path_absolute(outputFilename_)) {
    outputFilename_ = curdir + "/" + outputFilename_;
  }

  si.set_output_filename(outputFilename_);

  if (si.subcycle() > 1) {
    Excn::ParallelDisks::Create_IO_Filename(outputFilename_, cycle, si.subcycle());
  }

  // See if output file should be opened in netcdf4 format...
  // Did user specify it via -netcdf4 or -large_model argument...
  int mode = 0;

  if (si.compress_data() > 0) {
    // Force netcdf-4 if compression is specified...
    mode |= EX_NETCDF4;
  }
  else if (si.use_netcdf4()) {
    mode |= EX_NETCDF4;
  }
  else if (ex_large_model(fileids_[0]) == 1) {
    mode |= EX_LARGE_MODEL;
  }

  mode |= mode64bit_;

  if (si.int64()) {
    mode |= EX_ALL_INT64_DB;
    mode |= EX_ALL_INT64_API;
  }

  if (si.append()) {
    std::cout << "[" << cycle << "] Output:   '" << outputFilename_ << "' (appending)" << '\n';
    float version = 0.0;
    mode |= EX_WRITE;
    outputId_ = ex_open(outputFilename_.c_str(), mode, &cpuWordSize_, &ioWordSize_, &version);
  }
  else {
    mode |= EX_CLOBBER;
    std::cout << "[" << cycle << "] Output:   '" << outputFilename_ << "'" << '\n';
    outputId_ = ex_create(outputFilename_.c_str(), mode, &cpuWordSize_, &ioWordSize_);
  }
  if (outputId_ < 0) {
    std::cerr << "Cannot open file '" << outputFilename_ << "'" << '\n';
    return false;
  }

  if (si.compress_data() > 0) {
    ex_set_option(outputId_, EX_OPT_COMPRESSION_LEVEL, si.compress_data());
    ex_set_option(outputId_, EX_OPT_COMPRESSION_SHUFFLE, 1);
  }

  // EPU Can add a name of "processor_id_epu" which is 16 characters long.
  // Make sure maximumNameLength_ is at least that long...

  if (maximumNameLength_ < 16) {
    maximumNameLength_ = 16;
  }
  ex_set_option(outputId_, EX_OPT_MAX_NAME_LENGTH, maximumNameLength_);

  int int_size = si.int64() ? 8 : 4;
  if (cycle == 0) {
    std::cout << "IO Word sizes: " << ioWordSize_ << " bytes floating point and " << int_size
              << " bytes integer.\n";
  }
  return true;
}

int Excn::ExodusFile::get_free_descriptor_count()
{
// Returns maximum number of files that one process can have open
// at one time. (POSIX)
#if defined(__PUMAGON__)
  int fdmax = FOPEN_MAX;
#elif defined(_WIN32)
  int fdmax = _getmaxstdio();
#else
  int fdmax = sysconf(_SC_OPEN_MAX);
  if (fdmax == -1) {
    // POSIX indication that there is no limit on open files...
    fdmax = INT_MAX;
  }
#endif
  // File descriptors are assigned in order (0,1,2,3,...) on a per-process
  // basis.

  // Assume that we have stdin, stdout, stderr, and output exodus
  // file (4 total).

  return fdmax - 4;

  // Could iterate from 0..fdmax and check for the first
  // EBADF (bad file descriptor) error return from fcntl, but that takes
  // too long and may cause other problems.  There is a isastream(filedes)
  // call on Solaris that can be used for system-dependent code.
  //
  // Another possibility is to do an open and see which descriptor is
  // returned -- take that as 1 more than the current count of open files.
  //
}


text:
LOG IN

A highly curated platform that brings together innovative founders with investors who offer value beyond just money.

				<uib-alert ng-repeat="alert in alerts" type="{{alert.type}}" close="closeAlert($index)">{{alert.msg}}</uib-alert>

			<form class="form-inline " ng-submit="login()">
			  	<input type="email" class="form-control" ng-model="email" style="margin-bottom:20px; width:100%;" placeholder="Your email">

			  	<input type="password" class="form-control" ng-model="password" placeholder="Password"style="width:100%;">

			  	<button class="btn btn-grey pull-right" ng-click="submit_pressed = true" type="submit" style="margin-top:40px;">
			        LOG IN
			    </button>
			</form>

			<uib-progressbar class="progress-striped active" value="dynamic" type="success">Logging you in...</uib-progressbar>


text:
package org.apache.edgent.javax.websocket;

import java.util.Properties;
import java.util.ServiceLoader;

import javax.websocket.WebSocketContainer;

/**
 * A {@link WebSocketContainer} provider for dealing with javax.websocket
 * SSL issues.
 *

 *
JSR356 lacks API for Client-side SSL configuration

 *
Jetty's {@code javax.websocket.ContainerProvider} ignores the
 *     {@code javax.net.ssl.keyStore} system property.
 *     It correctly handles {@code javax.net.ssl.trustStore}

 *

 * see https://github.com/eclipse/jetty.project/issues/155
 *

 * The net is that Jetty's {@code javax.websocket.ContainerProvider}
 * works fine for the "ws" protocol and for "wss" as long as
 * one doesn't need to programatically specify a trustStore path
 * and one doesn't to specify a keyStore for SSL client authentication support.
 *

 * A {@code EdgentSslContainerProvider} implementation is responsible for
 * working around those limitations.
 */
public abstract class EdgentSslContainerProvider {

    /**
     * Create a WebSocketContainer setup for SSL.
     *

     * The Java {@link ServiceLoader} is used to locate an implementation
     * of {@code org.apache.edgent.javax.websocket.Edgent.SslContainerProvider}.
     * @param config  SSL configuration info as described by
     * {@code org.apache.edgent.connectors.wsclient.javax.websocket.Jsr356WebSocketClient}.
     * @return the WebSocketContainer
     * @throws RuntimeException upon failure
     */
    public static WebSocketContainer getSslWebSocketContainer(Properties config) throws RuntimeException {
        for (EdgentSslContainerProvider provider : ServiceLoader.load(EdgentSslContainerProvider.class)) {
            WebSocketContainer container = provider.getSslContainer(config);
            if (container != null)
                return container;
        }

        throw new RuntimeException("Unable to find an implementation of EdgentSslContainerProvider");
    }

    /**
     * Create a WebSocketContainer setup for SSL.
     * To be implemented by a javax.websocket client provider.
     * @param config  SSL configuration info.
     * @return the WebSocketContainer
     * @throws RuntimeException if it fails
     */
    protected abstract WebSocketContainer getSslContainer(Properties config);
}


text:
<?php

abstract class Multiton
{
    /**
     * @var self[]
     */
    private static $instances = [];

    /**
     * @params mixed
     * @return static
     */
    final public static function getInstance()
    {
        $calledClassName = get_called_class();
        if (!array_key_exists($calledClassName, self::$instances)) {
            self::$instances[$calledClassName] = new $calledClassName(func_get_args());
        }

        return self::$instances[$calledClassName];
    }

    private function __clone()
    {
    }

    private function __sleep()
    {
    }

    private function __wakeup()
    {
    }

    protected function __construct()
    {
    }
}


text:
import Link from 'next/link'

export default function Page() {
  return (

      <Link href="/">
        top
      </Link>
      <Link href="#section">
        section link
      </Link>

section content

  )
}


text:
/*================================================================================
  code generated by: java2cpp
  author: Zoran Angelov, mailto://baldzar@gmail.com
  class: org.apache.http.ProtocolException
================================================================================*/

#ifndef J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_ORG_APACHE_HTTP_PROTOCOLEXCEPTION_HPP_DECL
#define J2CPP_ORG_APACHE_HTTP_PROTOCOLEXCEPTION_HPP_DECL

namespace j2cpp { namespace java { namespace lang { class Exception; } } }
namespace j2cpp { namespace java { namespace lang { class String; } } }
namespace j2cpp { namespace java { namespace lang { class Throwable; } } }
namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace java { namespace io { class Serializable; } } }
namespace j2cpp { namespace org { namespace apache { namespace http { class HttpException; } } } }

#include <java/io/Serializable.hpp>
#include <java/lang/Exception.hpp>
#include <java/lang/Object.hpp>
#include <java/lang/String.hpp>
#include <java/lang/Throwable.hpp>
#include <org/apache/http/HttpException.hpp>

namespace j2cpp {

namespace org { namespace apache { namespace http {

	class ProtocolException;
	class ProtocolException
		: public object<ProtocolException>
	{
	public:

		J2CPP_DECLARE_CLASS

		J2CPP_DECLARE_METHOD(0)
		J2CPP_DECLARE_METHOD(1)
		J2CPP_DECLARE_METHOD(2)

		explicit ProtocolException(jobject jobj)
		: object<ProtocolException>(jobj)
		{
		}

		operator local_ref<java::lang::Exception>() const;
		operator local_ref<java::lang::Throwable>() const;
		operator local_ref<java::lang::Object>() const;
		operator local_ref<java::io::Serializable>() const;
		operator local_ref<org::apache::http::HttpException>() const;

		ProtocolException();
		ProtocolException(local_ref< java::lang::String > const&);
		ProtocolException(local_ref< java::lang::String > const&, local_ref< java::lang::Throwable > const&);
	}; //class ProtocolException

} //namespace http
} //namespace apache
} //namespace org

} //namespace j2cpp

#endif //J2CPP_ORG_APACHE_HTTP_PROTOCOLEXCEPTION_HPP_DECL

#else //J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_ORG_APACHE_HTTP_PROTOCOLEXCEPTION_HPP_IMPL
#define J2CPP_ORG_APACHE_HTTP_PROTOCOLEXCEPTION_HPP_IMPL

namespace j2cpp {

org::apache::http::ProtocolException::operator local_ref<java::lang::Exception>() const
{
	return local_ref<java::lang::Exception>(get_jobject());
}

org::apache::http::ProtocolException::operator local_ref<java::lang::Throwable>() const
{
	return local_ref<java::lang::Throwable>(get_jobject());
}

org::apache::http::ProtocolException::operator local_ref<java::lang::Object>() const
{
	return local_ref<java::lang::Object>(get_jobject());
}

org::apache::http::ProtocolException::operator local_ref<java::io::Serializable>() const
{
	return local_ref<java::io::Serializable>(get_jobject());
}

org::apache::http::ProtocolException::operator local_ref<org::apache::http::HttpException>() const
{
	return local_ref<org::apache::http::HttpException>(get_jobject());
}

org::apache::http::ProtocolException::ProtocolException()
: object<org::apache::http::ProtocolException>(
	call_new_object<
		org::apache::http::ProtocolException::J2CPP_CLASS_NAME,
		org::apache::http::ProtocolException::J2CPP_METHOD_NAME(0),
		org::apache::http::ProtocolException::J2CPP_METHOD_SIGNATURE(0)
	>()
)
{
}

org::apache::http::ProtocolException::ProtocolException(local_ref< java::lang::String > const &a0)
: object<org::apache::http::ProtocolException>(
	call_new_object<
		org::apache::http::ProtocolException::J2CPP_CLASS_NAME,
		org::apache::http::ProtocolException::J2CPP_METHOD_NAME(1),
		org::apache::http::ProtocolException::J2CPP_METHOD_SIGNATURE(1)
	>(a0)
)
{
}

org::apache::http::ProtocolException::ProtocolException(local_ref< java::lang::String > const &a0, local_ref< java::lang::Throwable > const &a1)
: object<org::apache::http::ProtocolException>(
	call_new_object<
		org::apache::http::ProtocolException::J2CPP_CLASS_NAME,
		org::apache::http::ProtocolException::J2CPP_METHOD_NAME(2),
		org::apache::http::ProtocolException::J2CPP_METHOD_SIGNATURE(2)
	>(a0, a1)
)
{
}

J2CPP_DEFINE_CLASS(org::apache::http::ProtocolException,"org/apache/http/ProtocolException")
J2CPP_DEFINE_METHOD(org::apache::http::ProtocolException,0,"<init>","()V")
J2CPP_DEFINE_METHOD(org::apache::http::ProtocolException,1,"<init>","(Ljava/lang/String;)V")
J2CPP_DEFINE_METHOD(org::apache::http::ProtocolException,2,"<init>","(Ljava/lang/String;Ljava/lang/Throwable;)V")

} //namespace j2cpp

#endif //J2CPP_ORG_APACHE_HTTP_PROTOCOLEXCEPTION_HPP_IMPL

#endif //J2CPP_INCLUDE_IMPLEMENTATION


text:
module Network.HaskellNet.IMAP
    ( connectIMAP, connectIMAPPort, connectStream
      -- * IMAP commands
      -- ** any state commands
    , noop, capability, logout
      -- ** not authenticated state commands
    , login, authenticate
      -- ** autenticated state commands
    , select, examine, create, delete, rename
    , subscribe, unsubscribe
    , list, lsub, status, append
      -- ** selected state commands
    , check, close, expunge
    , search, store, copy
      -- * fetch commands
    , fetch, fetchHeader, fetchSize, fetchHeaderFields, fetchHeaderFieldsNot
    , fetchFlags, fetchR, fetchByString, fetchByStringR
      -- * other types
    , Flag(..), Attribute(..), MailboxStatus(..)
    , SearchQuery(..), FlagsQuery(..)
    )
where

import Network
import Network.HaskellNet.BSStream
import Network.HaskellNet.IMAP.Connection
import Network.HaskellNet.IMAP.Types
import Network.HaskellNet.IMAP.Parsers
import qualified Network.HaskellNet.Auth as A

import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BS

import Control.Applicative ((<$>))
import Control.Monad

import System.IO
import System.Time

import Data.Maybe
import Data.List hiding (delete)
import Data.Char

import Text.Packrat.Parse (Result)

-- suffixed by `s'
data SearchQuery = ALLs
                 | FLAG Flag
                 | UNFLAG Flag
                 | BCCs String
                 | BEFOREs CalendarTime
                 | BODYs String
                 | CCs String
                 | FROMs String
                 | HEADERs String String
                 | LARGERs Integer
                 | NEWs
                 | NOTs SearchQuery
                 | OLDs
                 | ONs CalendarTime
                 | ORs SearchQuery SearchQuery
                 | SENTBEFOREs CalendarTime
                 | SENTONs CalendarTime
                 | SENTSINCEs CalendarTime
                 | SINCEs CalendarTime
                 | SMALLERs Integer
                 | SUBJECTs String
                 | TEXTs String
                 | TOs String
                 | UIDs [UID]

instance Show SearchQuery where
    showsPrec d q = showParen (d>app_prec) $ showString $ showQuery q
        where app_prec = 10
              showQuery ALLs            = "ALL"
              showQuery (FLAG f)        = showFlag f
              showQuery (UNFLAG f)      = "UN" ++ showFlag f
              showQuery (BCCs addr)     = "BCC " ++ addr
              showQuery (BEFOREs t)     = "BEFORE " ++ dateToStringIMAP t
              showQuery (BODYs s)       = "BODY " ++ s
              showQuery (CCs addr)      = "CC " ++ addr
              showQuery (FROMs addr)    = "FROM " ++ addr
              showQuery (HEADERs f v)   = "HEADER " ++ f ++ " " ++ v
              showQuery (LARGERs siz)   = "LARGER {" ++ show siz ++ "}"
              showQuery NEWs            = "NEW"
              showQuery (NOTs qry)      = "NOT " ++ show qry
              showQuery OLDs            = "OLD"
              showQuery (ONs t)         = "ON " ++ dateToStringIMAP t
              showQuery (ORs q1 q2)     = "OR " ++ show q1 ++ " " ++ show q2
              showQuery (SENTBEFOREs t) = "SENTBEFORE " ++ dateToStringIMAP t
              showQuery (SENTONs t)     = "SENTON " ++ dateToStringIMAP t
              showQuery (SENTSINCEs t)  = "SENTSINCE " ++ dateToStringIMAP t
              showQuery (SINCEs t)      = "SINCE " ++ dateToStringIMAP t
              showQuery (SMALLERs siz)  = "SMALLER {" ++ show siz ++ "}"
              showQuery (SUBJECTs s)    = "SUBJECT " ++ s
              showQuery (TEXTs s)       = "TEXT " ++ s
              showQuery (TOs addr)      = "TO " ++ addr
              showQuery (UIDs uids)     = concat $ intersperse "," $
                                          map show uids
              showFlag Seen        = "SEEN"
              showFlag Answered    = "ANSWERED"
              showFlag Flagged     = "FLAGGED"
              showFlag Deleted     = "DELETED"
              showFlag Draft       = "DRAFT"
              showFlag Recent      = "RECENT"
              showFlag (Keyword s) = "KEYWORD " ++ s

data FlagsQuery = ReplaceFlags [Flag]
                | PlusFlags [Flag]
                | MinusFlags [Flag]

----------------------------------------------------------------------
-- establish connection

connectIMAPPort :: String -> PortNumber -> IO (IMAPConnection Handle)
connectIMAPPort hostname port =
    connectTo hostname (PortNumber port) >>= connectStream

connectIMAP :: String -> IO (IMAPConnection Handle)
connectIMAP hostname = connectIMAPPort hostname 143

connectStream :: BSStream s => s -> IO (IMAPConnection s)
connectStream s =
    do msg <- bsGetLine s
       unless (and $ BS.zipWith (==) msg (BS.pack "* OK")) $
              fail "cannot connect to the server"
       newConnection s

----------------------------------------------------------------------
-- normal send commands
sendCommand' :: (BSStream s) => IMAPConnection s -> String -> IO (ByteString, Int)
sendCommand' c cmdstr = do
  (_, num) <- withNextCommandNum c $ \num -> bsPutCrLf c $ BS.pack $ show6 num ++ " " ++ cmdstr
  resp <- getResponse c
  return (resp, num)

show6 :: (Ord a, Num a, Show a) => a -> String
show6 n | n > 100000 = show n
        | n > 10000  = '0' : show n
        | n > 1000   = "00" ++ show n
        | n > 100    = "000" ++ show n
        | n > 10     = "0000" ++ show n
        | otherwise  = "00000" ++ show n

sendCommand :: BSStream s => IMAPConnection s -> String
            -> (RespDerivs -> Result RespDerivs (ServerResponse, MboxUpdate, v))
            -> IO v
sendCommand imapc cmdstr pFunc =
    do (buf, num) <- sendCommand' imapc cmdstr
       let (resp, mboxUp, value) = eval pFunc (show6 num) buf
       case resp of
         OK _ _        -> do mboxUpdate imapc mboxUp
                             return value
         NO _ msg      -> fail ("NO: " ++ msg)
         BAD _ msg     -> fail ("BAD: " ++ msg)
         PREAUTH _ msg -> fail ("preauth: " ++ msg)

getResponse :: BSStream s => s -> IO ByteString
getResponse s = unlinesCRLF <$> getLs
    where unlinesCRLF = BS.concat . concatMap (:[crlfStr])
          getLs =
              do l <- strip <$> bsGetLine s
                 case () of
                   _ | isLiteral l ->  do l' <- getLiteral l (getLitLen l)
                                          ls <- getLs
                                          return (l' : ls)
                     | isTagged l -> (l:) <$> getLs
                     | otherwise -> return [l]
          getLiteral l len =
              do lit <- bsGet s len
                 l2 <- strip <$> bsGetLine s
                 let l' = BS.concat [l, crlfStr, lit, l2]
                 if isLiteral l2
                   then getLiteral l' (getLitLen l2)
                   else return l'
          crlfStr = BS.pack "\r\n"
          isLiteral l = BS.last l == '}' &&
                        BS.last (fst (BS.spanEnd isDigit (BS.init l))) == '{'
          getLitLen = read . BS.unpack . snd . BS.spanEnd isDigit . BS.init
          isTagged l = BS.head l == '*' && BS.head (BS.tail l) == ' '

mboxUpdate :: (BSStream s) => IMAPConnection s -> MboxUpdate -> IO ()
mboxUpdate conn (MboxUpdate exists' recent') = do
  when (isJust exists') $
       modifyMailboxInfo conn $ \mbox -> mbox { _exists = fromJust exists' }

  when (isJust recent') $
       modifyMailboxInfo conn $ \mbox -> mbox { _recent = fromJust recent' }

----------------------------------------------------------------------
-- IMAP commands
--

noop :: BSStream s => IMAPConnection s -> IO ()
noop conn = sendCommand conn "NOOP" pNone

capability :: BSStream s => IMAPConnection s -> IO [String]
capability conn = sendCommand conn "CAPABILITY" pCapability

logout :: (BSStream s) => IMAPConnection s -> IO ()
logout c = do bsPutCrLf c $ BS.pack "a0001 LOGOUT"
              bsClose c

login :: BSStream s => IMAPConnection s -> A.UserName -> A.Password -> IO ()
login conn username password = sendCommand conn ("LOGIN " ++ username ++ " " ++ password)
                               pNone

authenticate :: (BSStream s) => IMAPConnection s -> A.AuthType
             -> A.UserName -> A.Password -> IO ()
authenticate conn A.LOGIN username password =
    do (_, num) <- sendCommand' conn "AUTHENTICATE LOGIN"
       bsPutCrLf conn $ BS.pack userB64
       bsGetLine conn
       bsPutCrLf conn $ BS.pack passB64
       buf <- getResponse conn
       let (resp, mboxUp, value) = eval pNone (show6 num) buf
       case resp of
         OK _ _        -> do mboxUpdate conn $ mboxUp
                             return value
         NO _ msg      -> fail ("NO: " ++ msg)
         BAD _ msg     -> fail ("BAD: " ++ msg)
         PREAUTH _ msg -> fail ("preauth: " ++ msg)
    where (userB64, passB64) = A.login username password
authenticate conn at username password =
    do (c, num) <- sendCommand' conn $ "AUTHENTICATE " ++ show at
       let challenge =
               if BS.take 2 c == BS.pack "+ "
               then A.b64Decode $ BS.unpack $ head $
                    dropWhile (isSpace . BS.last) $ BS.inits $ BS.drop 2 c
               else ""
       bsPutCrLf conn $ BS.pack $ A.auth at challenge username password
       buf <- getResponse conn
       let (resp, mboxUp, value) = eval pNone (show6 num) buf
       case resp of
         OK _ _        -> do mboxUpdate conn $ mboxUp
                             return value
         NO _ msg      -> fail ("NO: " ++ msg)
         BAD _ msg     -> fail ("BAD: " ++ msg)
         PREAUTH _ msg -> fail ("preauth: " ++ msg)

_select :: (BSStream s) => String -> IMAPConnection s -> String -> IO ()
_select cmd conn mboxName =
    do mbox' <- sendCommand conn (cmd ++ mboxName) pSelect
       setMailboxInfo conn $ mbox' { _mailbox = mboxName }

select :: BSStream s => IMAPConnection s -> MailboxName -> IO ()
select = _select "SELECT "

examine :: BSStream s => IMAPConnection s -> MailboxName -> IO ()
examine = _select "EXAMINE "

create :: BSStream s => IMAPConnection s -> MailboxName -> IO ()
create conn mboxname = sendCommand conn ("CREATE " ++ mboxname) pNone

delete :: BSStream s => IMAPConnection s -> MailboxName -> IO ()
delete conn mboxname = sendCommand conn ("DELETE " ++ mboxname) pNone

rename :: BSStream s => IMAPConnection s -> MailboxName -> MailboxName -> IO ()
rename conn mboxorg mboxnew =
    sendCommand conn ("RENAME " ++ mboxorg ++ " " ++ mboxnew) pNone

subscribe :: BSStream s => IMAPConnection s -> MailboxName -> IO ()
subscribe conn mboxname = sendCommand conn ("SUBSCRIBE " ++ mboxname) pNone

unsubscribe :: BSStream s => IMAPConnection s -> MailboxName -> IO ()
unsubscribe conn mboxname = sendCommand conn ("UNSUBSCRIBE " ++ mboxname) pNone

list :: BSStream s => IMAPConnection s -> IO [([Attribute], MailboxName)]
list conn = (map (\(a, _, m) -> (a, m))) <$> listFull conn "\"\"" "*"

lsub :: BSStream s => IMAPConnection s -> IO [([Attribute], MailboxName)]
lsub conn = (map (\(a, _, m) -> (a, m))) <$> lsubFull conn "\"\"" "*"

listFull :: BSStream s => IMAPConnection s -> String -> String
         -> IO [([Attribute], String, MailboxName)]
listFull conn ref pat = sendCommand conn (unwords ["LIST", ref, pat]) pList

lsubFull :: BSStream s => IMAPConnection s -> String -> String
         -> IO [([Attribute], String, MailboxName)]
lsubFull conn ref pat = sendCommand conn (unwords ["LSUB", ref, pat]) pLsub

status :: BSStream s => IMAPConnection s -> MailboxName -> [MailboxStatus]
       -> IO [(MailboxStatus, Integer)]
status conn mbox stats =
    let cmd = "STATUS " ++ mbox ++ " (" ++ (unwords $ map show stats) ++ ")"
    in sendCommand conn cmd pStatus

append :: BSStream s => IMAPConnection s -> MailboxName -> ByteString -> IO ()
append conn mbox mailData = appendFull conn mbox mailData [] Nothing

appendFull :: BSStream s => IMAPConnection s -> MailboxName -> ByteString
           -> [Flag] -> Maybe CalendarTime -> IO ()
appendFull conn mbox mailData flags' time =
    do (buf, num) <- sendCommand' conn
                (unwords ["APPEND", mbox
                         , fstr, tstr,  "{" ++ show len ++ "}"])
       unless (BS.null buf || (BS.head buf /= '+')) $
              fail "illegal server response"
       mapM_ (bsPutCrLf conn) mailLines
       buf2 <- getResponse conn
       let (resp, mboxUp, ()) = eval pNone (show6 num) buf2
       case resp of
         OK _ _ -> mboxUpdate conn mboxUp
         NO _ msg -> fail ("NO: "++msg)
         BAD _ msg -> fail ("BAD: "++msg)
         PREAUTH _ msg -> fail ("PREAUTH: "++msg)
    where mailLines = BS.lines mailData
          len       = sum $ map ((2+) . BS.length) mailLines
          tstr      = maybe "" show time
          fstr      = unwords $ map show flags'

check :: BSStream s => IMAPConnection s -> IO ()
check conn = sendCommand conn "CHECK" pNone

close :: BSStream s => IMAPConnection s -> IO ()
close conn =
    do sendCommand conn "CLOSE" pNone
       setMailboxInfo conn emptyMboxInfo

expunge :: BSStream s => IMAPConnection s -> IO [Integer]
expunge conn = sendCommand conn "EXPUNGE" pExpunge

search :: BSStream s => IMAPConnection s -> [SearchQuery] -> IO [UID]
search conn queries = searchCharset conn "" queries

searchCharset :: BSStream s => IMAPConnection s -> Charset -> [SearchQuery]
              -> IO [UID]
searchCharset conn charset queries =
    sendCommand conn ("UID SEARCH "
                    ++ (if not . null $ charset
                           then charset ++ " "
                           else "")
                    ++ unwords (map show queries)) pSearch

fetch :: BSStream s => IMAPConnection s -> UID -> IO ByteString
fetch conn uid =
    do lst <- fetchByString conn uid "BODY[]"
       return $ maybe BS.empty BS.pack $ lookup "BODY[]" lst

fetchHeader :: BSStream s => IMAPConnection s -> UID -> IO ByteString
fetchHeader conn uid =
    do lst <- fetchByString conn uid "BODY[HEADER]"
       return $ maybe BS.empty BS.pack $ lookup "BODY[HEADER]" lst

fetchSize :: BSStream s => IMAPConnection s -> UID -> IO Int
fetchSize conn uid =
    do lst <- fetchByString conn uid "RFC822.SIZE"
       return $ maybe 0 read $ lookup "RFC822.SIZE" lst

fetchHeaderFields :: BSStream s => IMAPConnection s
                  -> UID -> [String] -> IO ByteString
fetchHeaderFields conn uid hs =
    do lst <- fetchByString conn uid ("BODY[HEADER.FIELDS "++unwords hs++"]")
       return $ maybe BS.empty BS.pack $
              lookup ("BODY[HEADER.FIELDS "++unwords hs++"]") lst

fetchHeaderFieldsNot :: BSStream s => IMAPConnection s
                     -> UID -> [String] -> IO ByteString
fetchHeaderFieldsNot conn uid hs =
    do let fetchCmd = "BODY[HEADER.FIELDS.NOT "++unwords hs++"]"
       lst <- fetchByString conn uid fetchCmd
       return $ maybe BS.empty BS.pack $ lookup fetchCmd lst

fetchFlags :: BSStream s => IMAPConnection s -> UID -> IO [Flag]
fetchFlags conn uid =
    do lst <- fetchByString conn uid "FLAGS"
       return $ getFlags $ lookup "FLAGS" lst
    where getFlags Nothing  = []
          getFlags (Just s) = eval' dvFlags "" s

fetchR :: BSStream s => IMAPConnection s -> (UID, UID)
       -> IO [(UID, ByteString)]
fetchR conn r =
    do lst <- fetchByStringR conn r "BODY[]"
       return $ map (\(uid, vs) -> (uid, maybe BS.empty BS.pack $
                                       lookup "BODY[]" vs)) lst
fetchByString :: BSStream s => IMAPConnection s -> UID -> String
              -> IO [(String, String)]
fetchByString conn uid command =
    do lst <- fetchCommand conn ("UID FETCH "++show uid++" "++command) id
       return $ snd $ head lst

fetchByStringR :: BSStream s => IMAPConnection s -> (UID, UID) -> String
               -> IO [(UID, [(String, String)])]
fetchByStringR conn (s, e) command =
    fetchCommand conn ("UID FETCH "++show s++":"++show e++" "++command) proc
    where proc (n, ps) =
              (maybe (toEnum (fromIntegral n)) read (lookup "UID" ps), ps)

fetchCommand :: (BSStream s) => IMAPConnection s -> String
             -> ((Integer, [(String, String)]) -> b) -> IO [b]
fetchCommand conn command proc =
    (map proc) <$> sendCommand conn command pFetch

storeFull :: BSStream s => IMAPConnection s -> String -> FlagsQuery -> Bool
          -> IO [(UID, [Flag])]
storeFull conn uidstr query isSilent =
    fetchCommand conn ("UID STORE " ++ uidstr ++ flgs query) procStore
    where fstrs fs = "(" ++ (concat $ intersperse " " $ map show fs) ++ ")"
          toFStr s fstrs' =
              s ++ (if isSilent then ".SILENT" else "") ++ " " ++ fstrs'
          flgs (ReplaceFlags fs) = toFStr "FLAGS" $ fstrs fs
          flgs (PlusFlags fs)    = toFStr "+FLAGS" $ fstrs fs
          flgs (MinusFlags fs)   = toFStr "-FLAGS" $ fstrs fs
          procStore (n, ps) = (maybe (toEnum (fromIntegral n)) read
                                         (lookup "UID" ps)
                              ,maybe [] (eval' dvFlags "") (lookup "FLAG" ps))

store :: BSStream s => IMAPConnection s -> UID -> FlagsQuery -> IO ()
store conn i q       = storeFull conn (show i) q True >> return ()

copyFull :: (BSStream s) => IMAPConnection s -> String -> String -> IO ()
copyFull conn uidStr mbox =
    sendCommand conn ("UID COPY " ++ uidStr ++ " " ++ mbox) pNone

copy :: BSStream s => IMAPConnection s -> UID -> MailboxName -> IO ()
copy conn uid mbox     = copyFull conn (show uid) mbox

----------------------------------------------------------------------
-- auxialiary functions

dateToStringIMAP :: CalendarTime -> String
dateToStringIMAP date = concat $ intersperse "-" [show2 $ ctDay date
                                                 , showMonth $ ctMonth date
                                                 , show $ ctYear date]
    where show2 n | n < 10    = '0' : show n
                  | otherwise = show n
          showMonth January   = "Jan"
          showMonth February  = "Feb"
          showMonth March     = "Mar"
          showMonth April     = "Apr"
          showMonth May       = "May"
          showMonth June      = "Jun"
          showMonth July      = "Jul"
          showMonth August    = "Aug"
          showMonth September = "Sep"
          showMonth October   = "Oct"
          showMonth November  = "Nov"
          showMonth December  = "Dec"

strip :: ByteString -> ByteString
strip = fst . BS.spanEnd isSpace . BS.dropWhile isSpace


text:
import { Component, EventEmitter, Input, Output } from '@angular/core';

@Component({
  selector: 'bc-sidenav',
  template: `
    <mat-sidenav
      #sidenav
      [opened]="open"
      (keydown.escape)="sidenav.close()"
      (closedStart)="closeMenu.emit()"
      disableClose
    >
      <mat-nav-list>
        <ng-content></ng-content>
      </mat-nav-list>
    </mat-sidenav>
  `,
  styles: [
    `
      mat-sidenav {
        width: 300px;
      }
    `,
  ],
})
export class SidenavComponent {
  @Input() open = false;
  @Output() closeMenu = new EventEmitter();
}


text:
Utilizando el [tema SinglePaged](https://github.com/t413/SinglePaged) de [Tim O'Brien](http://t413.com/)
—
Funcionando gracias a [Jekyll](http://jekyllrb.com/) y [GitHub](https://github.com/minfingt/minfingt.github.io)
—
por un gobierno transparente


text:
"""Global import for model hyper-parameters.

Using this module any ModelParams can be accessed via GetParams.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import importlib
import REDACTED.transformer_lingvo.lingvo.compat as tf

def _Import(name):
  """Imports the python module of the given name."""
  tf.logging.info('Importing %s', name)
  try:
    importlib.import_module(name)
    tf.logging.info('Imported %s', name)
  except ImportError as e:
    # It is expected that some imports may be missing.
    tf.logging.info('Could not import %s: %s', name, e)

_TASK_ROOT = 'REDACTED.transformer_lingvo.lingvo.tasks'

# LINT.IfChange(task_dirs)
_TASK_DIRS = (
    'asr',
    'car',
    'image',
    'lm',
    'mt',
    'punctuator',
)
# LINT.ThenChange(tasks/BUILD:task_dirs)

def ImportAllParams(task_root=_TASK_ROOT, task_dirs=_TASK_DIRS):
  # Import all ModelParams to ensure that they are added to the global registry.
  for task in task_dirs:
    # By our code repository convention, there is a params.py under the task's
    # params directory. params.py imports _all_ modules that may registers a
    # model param.
    _Import('{}.{}.params.params'.format(task_root, task))

def ImportParams(model_name, task_root=_TASK_ROOT, task_dirs=_TASK_DIRS):
  """Attempts to only import the files that may contain the model."""
  # 'model_name' follows <task>.<path>.<class name>
  if '.' not in model_name:
    raise ValueError('Invalid model name %s' % model_name)
  model_module = model_name.rpartition('.')[0]
  # Try importing the module directly, in case it's a local import.
  _Import(model_module)

  # Try built-in tasks imports.
  for task in sorted(task_dirs):
    if model_module.startswith(task + '.'):
      path = model_module[len(task) + 1:]
      _Import('{}.{}.params.{}'.format(task_root, task, path))


text:
// query

var selector = function() {
  var city = Session.get('currentCity');
  return Users.hasAmbassadorPermission() ? {} : {hiddenIn: {$ne: city}};
}

DealsSorted = function() {
  var city = Session.get('currentCity');
  var deals = Deals.find(selector()).fetch();
  var sort = (DealsSort.findOne({city: city}) || {}).sort || [];
  return Query.sortedDocs(deals, sort);
}

// editor

var editor = new Editor('Deals');

// Template helpers

Template.deals.helpers({
  'isEmpty': function() {
    return Deals.find(selector()).count() === 0;
  },
  'deals': function() {
    return DealsSorted();
  },
  'editor': function() {
    return editor;
  }
});

Template.deal.helpers({
  'codeType': function() {
    return /^http/.test(this.code) ? 'url' : 'code';
  },
  'isSelected': function() {
    return this._id === editor.selectedId() ? 'selected' : '';
  },
  'mode': editor.mode,
});

/* events */

Template.deal.events({
  "click .deal": function(evt) {
    var dealId = $(evt.currentTarget).data('id');
    editor.select(dealId, true);
  },
});

Template.deals.events({
  "click #DealsEditor [action='edit']": function() {
    // select first deal
    if (!editor.selectedId()) {
      var firstDealId = $("#dealsContainer .deal").onScreen().data('id');
      if (firstDealId)
        editor.select(firstDealId);
    }
  },
});

// DB

var updateSort = function(sort) {
  Meteor.call('updateDealsSort', sort, function(err) {
    if (err) console.log(err);
  });
}

// Template instance

Template.deals.rendered = function() {

  // make deals sortable for ambassadors
  if (Users.hasAmbassadorPermission()) {
    var $deals = this.$('#dealsContainer');
    $deals.addClass('draggable');
    $deals.sortable({
      axis: "y",
      cursor: 'move',
      handle: '.drag-handle',
      stop: function(event, ui) {
        var sort = $deals.sortable('toArray', {attribute: 'data-id'});
        updateSort(sort);
      }
    });
  }
}


text:
import numpy as np
import xarray as xr

from . import TestCase
from .test_dataset import create_test_data

from xarray.core import merge

class TestMergeInternals(TestCase):
    def test_broadcast_dimension_size(self):
        actual = merge.broadcast_dimension_size(
            [xr.Variable('x', [1]), xr.Variable('y', [2, 1])])
        assert actual == {'x': 1, 'y': 2}

        actual = merge.broadcast_dimension_size(
            [xr.Variable(('x', 'y'), [[1, 2]]), xr.Variable('y', [2, 1])])
        assert actual == {'x': 1, 'y': 2}

        with self.assertRaises(ValueError):
            actual = merge.broadcast_dimension_size(
                [xr.Variable(('x', 'y'), [[1, 2]]), xr.Variable('y', [2])])

class TestMergeFunction(TestCase):
    def test_merge_arrays(self):
        data = create_test_data()
        actual = xr.merge([data.var1, data.var2])
        expected = data[['var1', 'var2']]
        assert actual.identical(expected)

    def test_merge_datasets(self):
        data = create_test_data()

        actual = xr.merge([data[['var1']], data[['var2']]])
        expected = data[['var1', 'var2']]
        assert actual.identical(expected)

        actual = xr.merge([data, data])
        assert actual.identical(data)

    def test_merge_dataarray_unnamed(self):
        data = xr.DataArray([1, 2], dims='x')
        with self.assertRaisesRegexp(
                ValueError, 'without providing an explicit name'):
            xr.merge([data])

    def test_merge_dicts_simple(self):
        actual = xr.merge([{'foo': 0}, {'bar': 'one'}, {'baz': 3.5}])
        expected = xr.Dataset({'foo': 0, 'bar': 'one', 'baz': 3.5})
        assert actual.identical(expected)

    def test_merge_dicts_dims(self):
        actual = xr.merge([{'y': ('x', [13])}, {'x': [12]}])
        expected = xr.Dataset({'x': [12], 'y': ('x', [13])})
        assert actual.identical(expected)

    def test_merge_error(self):
        ds = xr.Dataset({'x': 0})
        with self.assertRaises(xr.MergeError):
            xr.merge([ds, ds + 1])

class TestMergeMethod(TestCase):

    def test_merge(self):
        data = create_test_data()
        ds1 = data[['var1']]
        ds2 = data[['var3']]
        expected = data[['var1', 'var3']]
        actual = ds1.merge(ds2)
        assert expected.identical(actual)

        actual = ds2.merge(ds1)
        assert expected.identical(actual)

        actual = data.merge(data)
        assert data.identical(actual)
        actual = data.reset_coords(drop=True).merge(data)
        assert data.identical(actual)
        actual = data.merge(data.reset_coords(drop=True))
        assert data.identical(actual)

        with self.assertRaises(ValueError):
            ds1.merge(ds2.rename({'var3': 'var1'}))
        with self.assertRaisesRegexp(
                ValueError, 'should be coordinates or not'):
            data.reset_coords().merge(data)
        with self.assertRaisesRegexp(
                ValueError, 'should be coordinates or not'):
            data.merge(data.reset_coords())

    def test_merge_broadcast_equals(self):
        ds1 = xr.Dataset({'x': 0})
        ds2 = xr.Dataset({'x': ('y', [0, 0])})
        actual = ds1.merge(ds2)
        assert ds2.identical(actual)

        actual = ds2.merge(ds1)
        assert ds2.identical(actual)

        actual = ds1.copy()
        actual.update(ds2)
        assert ds2.identical(actual)

        ds1 = xr.Dataset({'x': np.nan})
        ds2 = xr.Dataset({'x': ('y', [np.nan, np.nan])})
        actual = ds1.merge(ds2)
        assert ds2.identical(actual)

    def test_merge_compat(self):
        ds1 = xr.Dataset({'x': 0})
        ds2 = xr.Dataset({'x': 1})
        for compat in ['broadcast_equals', 'equals', 'identical']:
            with self.assertRaises(xr.MergeError):
                ds1.merge(ds2, compat=compat)

        ds2 = xr.Dataset({'x': [0, 0]})
        for compat in ['equals', 'identical']:
            with self.assertRaisesRegexp(
                    ValueError, 'should be coordinates or not'):
                ds1.merge(ds2, compat=compat)

        ds2 = xr.Dataset({'x': ((), 0, {'foo': 'bar'})})
        with self.assertRaises(xr.MergeError):
            ds1.merge(ds2, compat='identical')

        with self.assertRaisesRegexp(ValueError, 'compat=\S+ invalid'):
            ds1.merge(ds2, compat='foobar')

    def test_merge_auto_align(self):
        ds1 = xr.Dataset({'a': ('x', [1, 2])})
        ds2 = xr.Dataset({'b': ('x', [3, 4]), 'x': [1, 2]})
        expected = xr.Dataset({'a': ('x', [1, 2, np.nan]),
                            'b': ('x', [np.nan, 3, 4])})
        assert expected.identical(ds1.merge(ds2))
        assert expected.identical(ds2.merge(ds1))

        expected = expected.isel(x=slice(2))
        assert expected.identical(ds1.merge(ds2, join='left'))
        assert expected.identical(ds2.merge(ds1, join='right'))

        expected = expected.isel(x=slice(1, 2))
        assert expected.identical(ds1.merge(ds2, join='inner'))
        assert expected.identical(ds2.merge(ds1, join='inner'))


text:
define([ 'jquery', 'plugins/bootstrap' ],
    function( $ ){
        'use strict';

        return function($els){
            $els.each(function(){
                var $this = $(this);
                $this.popover({
                    content: $this.data('content'),
                    title: $this.attr('title')
                })
            });

        };
    });


text:
<?php

namespace TripShaper\AdminBundle\Form\Type\Path;

use Admingenerated\TripShaperAdminBundle\Form\BasePathType\FiltersType as BaseFiltersType;

class FiltersType extends BaseFiltersType
{
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
	<File path="Classes/AutoScalingScalingPolicyUnmarshaller.html">

		<Token>
			<TokenIdentifier>//apple_ref/occ/cl/AutoScalingScalingPolicyUnmarshaller</TokenIdentifier>
			<Abstract type="html">Scaling Policy Unmarshaller</Abstract>
			<DeclaredIn>AutoScalingScalingPolicyUnmarshaller.h</DeclaredIn>

			<NodeRef refid="165"/>
		</Token>

	</File>
</Tokens>


text:
<?php
use yii\helpers\Html;

/* @var $this yii\web\View */

$this->title = Yii::t('app', 'About');
$this->params['breadcrumbs'][] = $this->title;
?>

        <meta charset="utf-8">
        <title>About Page - Travel by templatemo</title>
        <meta name="description" content="">

        <meta name="viewport" content="width=device-width">
		<meta name="author" content="templatemo">
        <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,800,700,600,300' rel='stylesheet' type='text/css'>

        <link rel="stylesheet" href="css/bootstrap.min.css">
        <link rel="stylesheet" href="css/font-awesome.css">
        <link rel="stylesheet" href="css/animate.css">
        <link rel="stylesheet" href="css/templatemo_misc.css">
        <link rel="stylesheet" href="css/templatemo_style.css">

O podjetju

Potovanje brez meja

PISI TUKAJ:..Interdum et malesuada fames ac ante ipsum primis in faucibus. Sed lacinia nulla sit amet ligula porta, vitae mattis nunc posuere. Curabitur eu aliquam erat. Etiam sollicitudin est eu turpis dapibus aliquet. Ut vitae lacus vel nulla iaculis interdum.

							Suspendisse convallis congue tellus, nec ultricies sem molestie ac. Nunc lobortis elit orci, vitae suscipit urna dictum id. Nullam at elementum magna. Vivamus sit amet ipsum tortor. Nullam molestie eros quis risus pellentesque, eget pellentesque mauris placerat.

Naša ekipa

Najboljša ekipa za vaše potovanje

PISI TUKAJ:....Curabitur eu aliquam erat. Etiam sollicitudin est eu turpis dapibus aliquet. Ut vitae lacus vel nulla iaculis interdum. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Lorem ipsum dolor sit amet, consectetur adipiscing elit.

							In hac habitasse platea dictumst. Nulla mollis nisl id ipsum faucibus lacinia. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam sit amet ultricies mauris. Nulla fermentum nisl felis, id blandit nunc vehicula vel.

                            Copyright © 2084 Company Name


text:
<?php

namespace GameAffinity\JuegoBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class JuegoBundle extends Bundle
{
}


text:
require File.dirname(__FILE__) + '/test_helper'

describe "Braid" do
  it "puts the lotion in the basket" do
    # dedicated to dblack
  end
end


text:
@interface Navigation_ToolbarControllerViewController : UINavigationController<UINavigationControllerDelegate>

@property(nonatomic, readonly) UIToolbar *primaryToolbar;
@property(nonatomic, readonly) UIToolbar *secondaryToolbar;

@end


text:
<?php
namespace AcMailer\View;

use Zend\View\Model\ViewModel;

/**
 * Interface DefaultLayoutInterface
 * @author Alejandro Celaya Alastrué
 * @link http://www.alejandrocelaya.com
 */
interface DefaultLayoutInterface
{
    /**
     * @return ViewModel
     */
    public function getModel();

    /**
     * @return boolean
     */
    public function hasModel();

    /**
     * @return string
     */
    public function getTemplateCaptureTo();
}


text:
'use strict';

var parse = require('..').json.parse;
var request = function(options) {
  return require('..').http.request(options).then(require('..').http.response);
};

var options = {
  hostname: 'graph.facebook.com',
  secure: true,
  path: '/ping',
  headers: {
    'content-type': 'application/json; charset=utf-8',
    'accept-encoding': 'gzip, deflate, identity'
  },
  timeout: 3000
};

request(options).then(parse).done(function(json) {
  console.log(json);
});

// note: this version will not send compression headers
// note: this version will respect the default socket timeout
request('https://graph.facebook.com/ping').then(parse).done(function(json) {
  console.log(json);
});


text:
package com.ltsllc.miranda.mina;

import com.ltsllc.miranda.Message;
import com.ltsllc.miranda.network.Handle;
import com.ltsllc.miranda.network.NetworkException;
import com.ltsllc.miranda.node.networkMessages.WireMessage;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;

import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.util.concurrent.BlockingQueue;

public class MinaHandle extends Handle {
    private IoSession ioSession;

    public IoSession getIoSession() {
        return ioSession;
    }

    public MinaHandle(IoSession ioSession, BlockingQueue<Message> queue) {
        super(queue);
        this.ioSession = ioSession;
    }

    public void send(WireMessage wireMessage) throws NetworkException {
        try {
            String json = wireMessage.toJson();
            IoBuffer ioBuffer = IoBuffer.allocate(json.length());
            Charset charset = Charset.defaultCharset();
            ioBuffer.putString(json, charset.newEncoder());
            ioBuffer.flip();
            ioSession.write(ioBuffer);
        } catch (CharacterCodingException e) {
            throw new NetworkException("Exception trying to send", e, NetworkException.Errors.ExceptionSending);
        }
    }

    public void close() {
        ioSession.closeNow();
    }

    public void panic() {
        close();
    }

}