text:
using namespace arangodb;
using namespace arangodb::rest;

RestSimpleHandler::RestSimpleHandler(
    GeneralRequest* request, GeneralResponse* response,
    arangodb::aql::QueryRegistry* queryRegistry)
    : RestVocbaseBaseHandler(request, response),
      _queryRegistry(queryRegistry),
      _queryLock(),
      _query(nullptr),
      _queryKilled(false) {}

RestHandler::status RestSimpleHandler::execute() {
  // extract the request type
  auto const type = _request->requestType();

  if (type == GeneralRequest::RequestType::PUT) {
    bool parsingSuccess = true;
    std::shared_ptr<VPackBuilder> parsedBody =
        parseVelocyPackBody(&VPackOptions::Defaults, parsingSuccess);

    if (!parsingSuccess) {
      return status::DONE;
    }

    VPackSlice body = parsedBody.get()->slice();

    if (!body.isObject()) {
      generateError(GeneralResponse::ResponseCode::BAD, TRI_ERROR_TYPE_ERROR,
                    "expecting JSON object body");
      return status::DONE;
    }

    std::string const& prefix = _request->requestPath();

    if (prefix == RestVocbaseBaseHandler::SIMPLE_REMOVE_PATH) {
      removeByKeys(body);
    } else if (prefix == RestVocbaseBaseHandler::SIMPLE_LOOKUP_PATH) {
      lookupByKeys(body);
    } else {
      generateError(GeneralResponse::ResponseCode::BAD, TRI_ERROR_TYPE_ERROR,
                    "unsupported value for <operation>");
    }

    return status::DONE;
  }

  generateError(GeneralResponse::ResponseCode::METHOD_NOT_ALLOWED,
                TRI_ERROR_HTTP_METHOD_NOT_ALLOWED);
  return status::DONE;
}

bool RestSimpleHandler::cancel() { return cancelQuery(); }

////////////////////////////////////////////////////////////////////////////////
/// @brief register the currently running query
////////////////////////////////////////////////////////////////////////////////

void RestSimpleHandler::registerQuery(arangodb::aql::Query* query) {
  MUTEX_LOCKER(mutexLocker, _queryLock);

  TRI_ASSERT(_query == nullptr);
  _query = query;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief unregister the currently running query
////////////////////////////////////////////////////////////////////////////////

void RestSimpleHandler::unregisterQuery() {
  MUTEX_LOCKER(mutexLocker, _queryLock);

  _query = nullptr;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief cancel the currently running query
////////////////////////////////////////////////////////////////////////////////

bool RestSimpleHandler::cancelQuery() {
  MUTEX_LOCKER(mutexLocker, _queryLock);

  if (_query != nullptr) {
    _query->killed(true);
    _queryKilled = true;
    return true;
  }

  return false;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief whether or not the query was canceled
////////////////////////////////////////////////////////////////////////////////

bool RestSimpleHandler::wasCanceled() {
  MUTEX_LOCKER(mutexLocker, _queryLock);
  return _queryKilled;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief was docuBlock RestRemoveByKeys
////////////////////////////////////////////////////////////////////////////////

void RestSimpleHandler::removeByKeys(VPackSlice const& slice) {
  TRI_ASSERT(slice.isObject());
  try {
    std::string collectionName;
    {
      VPackSlice const value = slice.get("collection");

      if (!value.isString()) {
        generateError(GeneralResponse::ResponseCode::BAD, TRI_ERROR_TYPE_ERROR,
                      "expecting string for <collection>");
        return;
      }

      collectionName = value.copyString();

      if (!collectionName.empty() && collectionName[0] >= '0' &&
          collectionName[0] <= '9') {
        // If we have a numeric name we probably have to translate it.
        CollectionNameResolver resolver(_vocbase);
        collectionName = resolver.getCollectionName(collectionName);
      }
    }

    VPackSlice const keys = slice.get("keys");

    if (!keys.isArray()) {
      generateError(GeneralResponse::ResponseCode::BAD, TRI_ERROR_TYPE_ERROR,
                    "expecting array for <keys>");
      return;
    }

    bool waitForSync = false;
    bool silent = true;
    bool returnOld = false;
    {
      VPackSlice const value = slice.get("options");
      if (value.isObject()) {
        VPackSlice wfs = value.get("waitForSync");
        if (wfs.isBool()) {
          waitForSync = wfs.getBool();
        }
        wfs = value.get("silent");
        if (wfs.isBool()) {
          silent = wfs.getBool();
        }
        wfs = value.get("returnOld");
        if (wfs.isBool()) {
          returnOld = wfs.getBool();
        }
      }
    }

    auto bindVars = std::make_shared<VPackBuilder>();
    bindVars->openObject();
    bindVars->add("@collection", VPackValue(collectionName));
    bindVars->add("keys", keys);
    bindVars->close();

    std::string aql(
        "FOR key IN @keys REMOVE key IN @@collection OPTIONS { ignoreErrors: "
        "true, waitForSync: ");
    aql.append(waitForSync ? "true" : "false");
    aql.append(" }");
    if (!silent) {
      if (returnOld) {
        aql.append(" RETURN OLD");
      } else {
        aql.append(" RETURN {_id: OLD._id, _key: OLD._key, _rev: OLD._rev}");
      }
    }

    arangodb::aql::Query query(false, _vocbase, aql.c_str(), aql.size(),
                               bindVars, nullptr, arangodb::aql::PART_MAIN);

    registerQuery(&query);
    auto queryResult = query.execute(_queryRegistry);
    unregisterQuery();

    if (queryResult.code != TRI_ERROR_NO_ERROR) {
      if (queryResult.code == TRI_ERROR_REQUEST_CANCELED ||
          (queryResult.code == TRI_ERROR_QUERY_KILLED && wasCanceled())) {
        THROW_ARANGO_EXCEPTION(TRI_ERROR_REQUEST_CANCELED);
      }

      THROW_ARANGO_EXCEPTION_MESSAGE(queryResult.code, queryResult.details);
    }

    {
      size_t ignored = 0;
      size_t removed = 0;
      if (queryResult.stats != nullptr) {
        VPackSlice stats = queryResult.stats->slice();

        if (!stats.isNone()) {
          TRI_ASSERT(stats.isObject());
          VPackSlice found = stats.get("writesIgnored");
          if (found.isNumber()) {
            ignored = found.getNumericValue<size_t>();
          }

          found = stats.get("writesExecuted");
          if (found.isNumber()) {
            removed = found.getNumericValue<size_t>();
          }
        }
      }

      VPackBuilder result;
      result.add(VPackValue(VPackValueType::Object));
      result.add("removed", VPackValue(removed));
      result.add("ignored", VPackValue(ignored));
      result.add("error", VPackValue(false));
      result.add(
          "code",
          VPackValue(static_cast<int>(GeneralResponse::ResponseCode::OK)));
      if (!silent) {
        result.add("old", queryResult.result->slice());
      }
      result.close();

      generateResult(GeneralResponse::ResponseCode::OK, result.slice(),
                     queryResult.context);
    }
  } catch (arangodb::basics::Exception const& ex) {
    unregisterQuery();
    generateError(GeneralResponse::responseCode(ex.code()), ex.code(),
                  ex.what());
  } catch (...) {
    unregisterQuery();
    generateError(GeneralResponse::ResponseCode::SERVER_ERROR,
                  TRI_ERROR_INTERNAL);
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief was docuBlock RestLookupByKeys
////////////////////////////////////////////////////////////////////////////////

void RestSimpleHandler::lookupByKeys(VPackSlice const& slice) {
  // TODO needs to generalized
  auto response = dynamic_cast<HttpResponse*>(_response);

  if (response == nullptr) {
    THROW_ARANGO_EXCEPTION(TRI_ERROR_INTERNAL);
  }

  try {
    std::string collectionName;
    {
      VPackSlice const value = slice.get("collection");
      if (!value.isString()) {
        generateError(GeneralResponse::ResponseCode::BAD, TRI_ERROR_TYPE_ERROR,
                      "expecting string for <collection>");
        return;
      }
      collectionName = value.copyString();

      if (!collectionName.empty()) {
        auto const* col =
            TRI_LookupCollectionByNameVocBase(_vocbase, collectionName);

        if (col != nullptr && collectionName.compare(col->_name) != 0) {
          // user has probably passed in a numeric collection id.
          // translate it into a "real" collection name
          collectionName = std::string(col->_name);
        }
      }
    }

    VPackSlice const keys = slice.get("keys");

    if (!keys.isArray()) {
      generateError(GeneralResponse::ResponseCode::BAD, TRI_ERROR_TYPE_ERROR,
                    "expecting array for <keys>");
      return;
    }

    auto bindVars = std::make_shared<VPackBuilder>();
    bindVars->openObject();
    bindVars->add("@collection", VPackValue(collectionName));
    VPackBuilder strippedBuilder =
        arangodb::aql::BindParameters::StripCollectionNames(
            keys, collectionName.c_str());

    bindVars->add("keys", strippedBuilder.slice());
    bindVars->close();

    std::string const aql(
        "FOR doc IN @@collection FILTER doc._key IN @keys RETURN doc");

    arangodb::aql::Query query(false, _vocbase, aql.c_str(), aql.size(),
                               bindVars, nullptr, arangodb::aql::PART_MAIN);

    registerQuery(&query);
    auto queryResult = query.execute(_queryRegistry);
    unregisterQuery();

    if (queryResult.code != TRI_ERROR_NO_ERROR) {
      if (queryResult.code == TRI_ERROR_REQUEST_CANCELED ||
          (queryResult.code == TRI_ERROR_QUERY_KILLED && wasCanceled())) {
        THROW_ARANGO_EXCEPTION(TRI_ERROR_REQUEST_CANCELED);
      }

      THROW_ARANGO_EXCEPTION_MESSAGE(queryResult.code, queryResult.details);
    }

    size_t resultSize = 10;
    VPackSlice qResult = queryResult.result->slice();
    if (qResult.isArray()) {
      resultSize = static_cast<size_t>(qResult.length());
    }

    VPackBuilder result;
    {
      VPackObjectBuilder guard(&result);
      setResponseCode(GeneralResponse::ResponseCode::OK);

      // TODO this should be generalized
      response->setContentType(HttpResponse::ContentType::JSON);

      if (qResult.isArray()) {
        // This is for internal use of AQL Traverser only.
        // Should not be documented
        VPackSlice const postFilter = slice.get("filter");
        if (postFilter.isArray()) {
          std::vector<arangodb::traverser::TraverserExpression*> expressions;
          arangodb::basics::ScopeGuard guard{[]() -> void {},
                                             [&expressions]() -> void {
                                               for (auto& e : expressions) {
                                                 delete e;
                                               }
                                             }};

          VPackValueLength length = postFilter.length();
          expressions.reserve(static_cast<size_t>(length));

          for (auto const& it : VPackArrayIterator(postFilter)) {
            if (it.isObject()) {
              auto expression =
                  std::make_unique<traverser::TraverserExpression>(it);
              expressions.emplace_back(expression.get());
              expression.release();
            }
          }

          result.add(VPackValue("documents"));
          std::vector<std::string> filteredIds;

          // just needed to build the result
          SingleCollectionTransaction trx(
              StandaloneTransactionContext::Create(_vocbase), collectionName,
              TRI_TRANSACTION_READ);

          result.openArray();
          for (auto const& tmp : VPackArrayIterator(qResult)) {
            if (!tmp.isNone()) {
              bool add = true;
              for (auto& e : expressions) {
                if (!e->isEdgeAccess && !e->matchesCheck(&trx, tmp)) {
                  add = false;
                  std::string _id = trx.extractIdString(tmp);
                  filteredIds.emplace_back(std::move(_id));
                  break;
                }
              }
              if (add) {
                result.add(tmp);
              }
            }
          }
          result.close();

          result.add(VPackValue("filtered"));
          result.openArray();
          for (auto const& it : filteredIds) {
            result.add(VPackValue(it));
          }
          result.close();
        } else {
          result.add(VPackValue("documents"));
          result.add(qResult);
          queryResult.result = nullptr;
        }
      } else {
        result.add(VPackValue("documents"));
        result.add(qResult);
        queryResult.result = nullptr;
      }
      result.add("error", VPackValue(false));
      result.add("code",
                 VPackValue(static_cast<int>(_response->responseCode())));

      // reserve a few bytes per result document by default
      int res = response->body().reserve(32 * resultSize);

      if (res != TRI_ERROR_NO_ERROR) {
        THROW_ARANGO_EXCEPTION(res);
      }
    }

    auto customTypeHandler = queryResult.context->orderCustomTypeHandler();
    VPackOptions options = VPackOptions::Defaults; // copy defaults
    options.customTypeHandler = customTypeHandler.get();

    arangodb::basics::VPackStringBufferAdapter buffer(
        response->body().stringBuffer());
    VPackDumper dumper(&buffer, &options);
    dumper.dump(result.slice());
  } catch (arangodb::basics::Exception const& ex) {
    unregisterQuery();
    generateError(GeneralResponse::responseCode(ex.code()), ex.code(),
                  ex.what());
  } catch (std::exception const& ex) {
    unregisterQuery();
    generateError(GeneralResponse::ResponseCode::SERVER_ERROR,
                  TRI_ERROR_INTERNAL, ex.what());
  } catch (...) {
    unregisterQuery();
    generateError(GeneralResponse::ResponseCode::SERVER_ERROR,
                  TRI_ERROR_INTERNAL);
  }
}


text:
<?php

namespace DisposableEmailChecker;

use DisposableEmailChecker\Exception\InvalidEmailException;
use DisposableEmailChecker\Provider\InMemoryProvider;
use DisposableEmailChecker\Provider\ProviderInterface;

class Checker
{
    private $provider;

    public function __construct(ProviderInterface $provider = null)
    {
        $this->provider = $provider ?: new InMemoryProvider();
    }

    public function check($email)
    {
        // Sanitize the email to prevent false negative.
        $email = strtolower($email);
        $email = trim($email);

        if (!preg_match('/.+\@.+\..+/', $email)) {
            throw new InvalidEmailException('The provided value is not a valid email address.');
        }

        return $this->provider->check($email);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.github.ddth.commons.crypto.utils;

/**
 * Thrown by {@link DdthCipherInputStream} and {@link DdthCipherOutputStream} to wrap the actual
 * error while encrypting/decrypting.
 *
 * @author Thanh Nguyen <btnguyen2k@gmail.com>
 * @since 0.9.2
 */
public class CipherException extends RuntimeException {
    private static final long serialVersionUID = 1L;

    public CipherException() {
        // TODO Auto-generated constructor stub
    }

    public CipherException(String message) {
        super(message);
        // TODO Auto-generated constructor stub
    }

    public CipherException(Throwable cause) {
        super(cause);
        // TODO Auto-generated constructor stub
    }

    public CipherException(String message, Throwable cause) {
        super(message, cause);
        // TODO Auto-generated constructor stub
    }

    public CipherException(String message, Throwable cause, boolean enableSuppression,
            boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
        // TODO Auto-generated constructor stub
    }
}


text:
<?php

	$about = array(
		'name' => 'Russian',
		'author' => array(
			'name' => 'Danila Susak',
			'email' => 'danilasusak@gmail.com',
			'website' => ''
		),
		'release-date' => '2011-06-01'
	);

	/**
	 * Members
	 */
	$dictionary = array(

		'%s Automatically log the member in after activation' =>
		'%s Осуществлять автоматический вход после активации',

		'%s Prevent unactivated members from logging in' =>
		'%s Запретить не активированным пользователям осуществлять вход',

		'%s cannot be blank.' =>
		'%s не может быть пустым.',

		'%s confirmation does not match.' =>
		'%s подтверждения пароля не совпадает.',

		'%s contains invalid characters.' =>
		'%s содержит недопустимые символы',

		'%s is a required field.' =>
		'%s это поле обязательно для заполнения.',

		'%s is already taken.' =>
		'%s уже существует',

		'%s is not strong enough.' =>
		'%s недостаточно сильный',

		'%s is too short. It must be at least %d characters.' =>
		'%s слишком короткий. Как минимум должно содержать в себе %d символов.',

		'A Members section will at minimum contain either a Member: Email or a Member: Username field' =>
		'Пользовательская сущность должна содержать как минимум одно из этих полей: `Пользователь: Электронная почта` или `Пользователь: имя пользователя`',

		'A role with the name %s already exists.' =>
		'Роль с данным именем %s уже существует.',

		'A salt gives your passwords extra security. It cannot be changed once set' =>
		'Секретное слово дает Вашему паролю дополнительную защиту. Вы не можете поменять это в будущем.',

		'Account will be activated when entry is saved' =>
		'Учетная запись будет активирована после сохранения.',

		'Activate Account Email Template' =>
		'Email Шаблон для активация учетной записи',

		'Activated' =>
		'Активированный',

		'Activated %s' =>
		'Активированы: %s',

		'Activation Code Expiry' =>
		'Срок кода активации',

		'Activation code %s' =>
		'Код активации учетной записи: %s',

		'Activation code expired %s' =>
		'Код активации учетной записи истекает в: %s',

		'Activation error. Code was invalid or has expired.' =>
		'Ошибка активации. Код активации неверный или устарел.',

		'Active Members Section' =>
		'Сущность с Пользователями',

		'An error occurred while processing this form.' =>
		'Во время обработки формы были обнаружены ошибки.',

		'Available Zones' =>
		'Доступные зоны',

		'Confirm' =>
		'Подтверждение',

		'Create a Role' =>
		'Создать Роль',

		'Default Member Role' =>
		'Роль по умолчанию',

		'Delete Members' =>
		'Удалить пользователя',

		'Delete this Role' =>
		'Удалить эту Роль',

		'Deny Access' =>
		'Доступ закрыт',

		'Edit All' =>
		'Редактировать все',

		'Edit Own' =>
		'Редактировать свои',

		'Event' =>
		'Событие',

		'Event Level Permissions' =>
		'Разрешения для событий',

		'Event updated at {$time}. Create another? View all Events' =>
		'Событие обновлено в {$time}. Добавить еще? Все события',

		'Generate Recovery Code Email Template' =>
		'Email Шаблон для кода восстановления пароля',

		'Good' =>
		'Хороший',

		'Invalid %s.' =>
		'Неверный %s',

		'Leave new password field blank to keep the current password' =>
		'Оставить поле пароля пустым, чтобы сохранить существующий пароль нетронутым.',

		'Member Roles' =>
		'Пользовательские роли',

		'Member is already activated.' =>
		'Пользователь уже активирован',

		'Member is not activated.' =>
		'Пользователь не активирован.',

		'Member not found.' =>
		'Пользователь не найден',

		'Member will assume the role %s when activated.' =>
		'Пользователь возьмет эту роль %s сразу после активации.',

		'Member: Activation' =>
		'Пользователь: Код активации',

		'Member: Email' =>
		'Пользователь: Электронная почта',

		'Member: Password' =>
		'Пользователь: Пароль',

		'Member: Role' =>
		'Пользователь: Роль',

		'Member: Timezone' =>
		'Пользователь: Часовой пояс',

		'Member: Username' =>
		'Пользователь: Имя пользователя',

		'Members' =>
		'Пользователи',

		'Members Timezone' =>
		'Часовой пояс',

		'Members: Lock Activation' =>
		'Пользователь: Оставить активацию учетной записи',

		'Members: Lock Role' =>
		'Пользователь: Оставить роль',

		'Members: Update Password' =>
		'Пользователь: Обновить пароль',

		'Minimum Length' =>
		'Минимальная длина',

		'Minimum Strength' =>
		'Минимальная сила',

		'Move Members To' =>
		'Переместить пользователя в',

		'No Activation field found.' =>
		'Не найдено поле для активации учетной записи',

		'No Authentication field found.' =>
		'Не найден поле с кодом активации',

		'No Edit' =>
		'Не редактировать',

		'No Identity field found.' =>
		'Не найдено поля с определением пользователя',

		'No Member section has been specified in %s. Please do this first.' =>
		'Не определено ни одной сущности с Пользователями.Пожалуйста, сделайте это в первую очередь',

		'No recovery code found.' =>
		'Не найден код для восстановления',

		'Not Activated' =>
		'Не активированный',

		'Page Level Permissions' =>
		'Разрешения для страниц',

		'Password Salt' =>
		'Секретное слово для пароля',

		'Recovery Code Expiry' =>
		'Код восстановления устарел',

		'Recovery code has expired.' =>
		'Код активации устарел',

		'Recovery code is a required field.' =>
		'Поле Код для восстановления обязательно для заполнения.',

		'Regenerate Activation Code Email Template' =>
		'Email Шаблон для повторной активации учетной записи',

		'Role created at %1$s. Create another? View all Roles' =>
		'Роль создана в %1$. Добавить еще? Посмотреть все Роли',

		'Role for Members who are awaiting activation' =>
		'Роли, ожидающие активацию',

		'Role not found' =>
		'Роль не найдена',

		'Role updated at %1$s. Create another? View all Roles' =>
		'Роль обновлена в %1$. Добавить еще? Посмотреть все Роли',

		'Strong' =>
		'Сильный',

		'Symphony – Member Roles' =>
		'Symphony – Пользовательские роли',

		'Symphony – Member Roles – ' =>
		'Symphony –Пользовательские роли – ',

		'The Public role cannot be removed' =>
		'Гостевая роль не может быть удалена',

		'The page you have requested has restricted access permissions.' =>
		'Для просмотра страницы, которую вы запрашиваете, у вас недостаточно прав',

		'The role you requested to delete does not exist.' =>
		'Роль, которую вы собираетесь удалить не существует.',

		'The role you requested to edit does not exist.' =>
		'Роль, которую вы хотите отредактировать не существует',

		'There is no Member: Role field in the active Members section. Add Member: Role field?' =>
		'Для сущности Пользователи не выбрана ни одна Роль. Добавит роль?',

		'This is the role assumed by the general public.' =>
		'Эта роль определена по умолчанию для всех пользователей',

		'Toggle all' =>
		'Выбрать все',

		'User can create new entries' =>
		'Пользователь может создавать новые записи',

		'User can edit all entries' =>
		'Пользователь может редактировать все записи',

		'User can edit their own entries only' =>
		'Пользователь может редактировать только свои существующие записи',

		'User cannot edit existing entries' =>
		'Пользователь не может редактировать существующие записи',

		'Weak' =>
		'Слабый',

		'You are not authorised to perform this action.' =>
		'Вы не авторизованы для выполнения этого действия',

		'You cannot generate a recovery code while being logged in.' =>
		'Вы не можете запросить новый код для восстановления, пока вы не осуществите вход',

		'Email Template Filter' =>
		false,

		'Email Template Manager' =>
		false,

		'Reset Password Email Template' =>
		'Email шаблон для сброса пароля',

		'%s Automatically log the member in after changing their password' =>
		'%s Автоматически осуществлять вход после смены пароля',

		'How long a member\'s activation code will be valid for before it expires' =>
		'Как долго код активации пользователя будет актуальным',

		'Code expiry must be a unit of time, such as 1 day or 2 hours' =>
		'Время действия кода может указана в слудеющих единицах времени: 1 day или 2 hours',

		'How long a member\'s recovery code will be valid for before it expires' =>
		'Как долго код восстановления пароля пользователя будет актуальным',

	);


text:
package com.mysql.jdbc.interceptors;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.ResultSetInternalMethods;
import com.mysql.jdbc.Statement;
import com.mysql.jdbc.StatementInterceptor;

public class SessionAssociationInterceptor implements StatementInterceptor {

	protected String currentSessionKey;
	protected final static ThreadLocal sessionLocal = new ThreadLocal();

	public static final void setSessionKey(String key) {
		sessionLocal.set(key);
	}

	public static final void resetSessionKey() {
		sessionLocal.set(null);
	}

	public static final String getSessionKey() {
		return (String)sessionLocal.get();
	}

	public boolean executeTopLevelOnly() {
		return true;
	}

	public void init(Connection conn, Properties props) throws SQLException {

	}

	public ResultSetInternalMethods postProcess(String sql,
			Statement interceptedStatement,
			ResultSetInternalMethods originalResultSet, Connection connection)
			throws SQLException {
		return null;
	}

	public ResultSetInternalMethods preProcess(String sql,
			Statement interceptedStatement, Connection connection)
			throws SQLException {
		String key = getSessionKey();

		if (key != null && !key.equals(this.currentSessionKey)) {
			PreparedStatement pstmt = connection.clientPrepareStatement("SET @mysql_proxy_session=?");

			try {
				pstmt.setString(1, key);
				pstmt.execute();
			} finally {
				pstmt.close();
			}

			this.currentSessionKey = key;
		}

		return null;
	}

	public void destroy() {

	}
}


text:
package org.zkoss.zsoup.nodes;

import java.io.File;
import java.io.IOException;

import org.junit.Test;
import org.junit.Ignore;
import org.zkoss.zsoup.Zsoup;
import org.zkoss.zsoup.TextUtil;
import org.zkoss.zsoup.integration.ParseTest;
import org.zkoss.zsoup.nodes.Document;
import org.zkoss.zsoup.nodes.Entities;

import static org.junit.Assert.*;
import static org.zkoss.zsoup.nodes.Document.OutputSettings.Syntax;

/**
 Tests for Document.

 @author Jonathan Hedley, jonathan@hedley.net */
public class DocumentTest {
    @Test public void setTextPreservesDocumentStructure() {
        Document doc = Zsoup.parse("
Hello
");
        doc.text("Replaced");
        assertEquals("Replaced", doc.text());
        assertEquals("Replaced", doc.body().text());
        assertEquals(1, doc.select("head").size());
    }

    @Test public void testTitles() {
        Document noTitle = Zsoup.parse("
Hello
");
        Document withTitle = Zsoup.parse("<title>First</title><title>Ignore</title>
Hello
");

        assertEquals("", noTitle.title());
        noTitle.title("Hello");
        assertEquals("Hello", noTitle.title());
        assertEquals("Hello", noTitle.select("title").first().text());

        assertEquals("First", withTitle.title());
        withTitle.title("Hello");
        assertEquals("Hello", withTitle.title());
        assertEquals("Hello", withTitle.select("title").first().text());

        Document normaliseTitle = Zsoup.parse("<title>   Hello\nthere   \n   now   \n");
        assertEquals("Hello there now", normaliseTitle.title());
    }

    @Test public void testOutputEncoding() {
        Document doc = Zsoup.parse("
π & < >
");
        // default is utf-8
        assertEquals("
π & < >
", doc.body().html());
        assertEquals("UTF-8", doc.outputSettings().charset().displayName());

        doc.outputSettings().charset("ascii");
        assertEquals(Entities.EscapeMode.base, doc.outputSettings().escapeMode());
        assertEquals("
π & < >
", doc.body().html());

        doc.outputSettings().escapeMode(Entities.EscapeMode.extended);
        assertEquals("
π & < >
", doc.body().html());
    }

    @Test public void testXhtmlReferences() {
        Document doc = Zsoup.parse("< > & " ' ×");
        doc.outputSettings().escapeMode(Entities.EscapeMode.xhtml);
        assertEquals("< > & \" ' ×", doc.body().html());
    }

    @Test public void testNormalisesStructure() {
        Document doc = Zsoup.parse("
two

three

four
");
        assertEquals("
two

three

four
", TextUtil.stripNewlines(doc.html()));
    }

    @Test public void testClone() {
        Document doc = Zsoup.parse("<title>Hello</title>
One
Two");
        Document clone = doc.clone();

        assertEquals("<title>Hello</title>
One

Two
", TextUtil.stripNewlines(clone.html()));
        clone.title("Hello there");
        clone.select("p").first().text("One more").attr("id", "1");
        assertEquals("<title>Hello there</title>
One more

Two
", TextUtil.stripNewlines(clone.html()));
        assertEquals("<title>Hello</title>
One

Two
", TextUtil.stripNewlines(doc.html()));
    }

    @Test public void testClonesDeclarations() {
        Document doc = Zsoup.parse("<!DOCTYPE html><title>Doctype test");
        Document clone = doc.clone();

        assertEquals(doc.html(), clone.html());
        assertEquals("<!DOCTYPE html><title>Doctype test</title>",
                TextUtil.stripNewlines(clone.html()));
    }

    @Test public void testLocation() throws IOException {
    	File in = new ParseTest().getFile("/htmltests/yahoo-jp.html");
        Document doc = Zsoup.parse(in, "UTF-8", "http://www.yahoo.co.jp/index.html");
        String location = doc.location();
        String baseUri = doc.baseUri();
        assertEquals("http://www.yahoo.co.jp/index.html",location);
        assertEquals("http://www.yahoo.co.jp/_ylh=X3oDMTB0NWxnaGxsBF9TAzIwNzcyOTYyNjUEdGlkAzEyBHRtcGwDZ2Ex/",baseUri);
        in = new ParseTest().getFile("/htmltests/nyt-article-1.html");
        doc = Zsoup.parse(in, null, "http://www.nytimes.com/2010/07/26/business/global/26bp.html?hp");
        location = doc.location();
        baseUri = doc.baseUri();
        assertEquals("http://www.nytimes.com/2010/07/26/business/global/26bp.html?hp",location);
        assertEquals("http://www.nytimes.com/2010/07/26/business/global/26bp.html?hp",baseUri);
    }

    @Test public void testHtmlAndXmlSyntax() {
        String h = "<!DOCTYPE html><img async checked='checked' src='&<>\"'><>&"<foo />bar";
        Document doc = Zsoup.parse(h);

        doc.outputSettings().syntax(Syntax.html);
        assertEquals("<!DOCTYPE html>\n" +
                "\n" +
                " \n" +
                " \n" +
                "  <img async checked src=\"&<>"\"><>&\"\n" +
                "  <foo />bar\n" +
                " \n" +
                "", doc.html());

        doc.outputSettings().syntax(Document.OutputSettings.Syntax.xml);
        assertEquals("<!DOCTYPE html>\n" +
                "\n" +
                " \n" +
                " \n" +
                "  <img async=\"\" checked=\"checked\" src=\"&<>"\" /><>&\"\n" +
                "  <foo />bar\n" +
                " \n" +
                "", doc.html());
    }

    @Test public void htmlParseDefaultsToHtmlOutputSyntax() {
        Document doc = Zsoup.parse("x");
        assertEquals(Syntax.html, doc.outputSettings().syntax());
    }

    // Ignored since this test can take awhile to run.
    @Ignore
    @Test public void testOverflowClone() {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < 100000; i++) {
            builder.insert(0, "");
            builder.append("");
        }

        Document doc = Zsoup.parse(builder.toString());
        doc.clone();
    }
}


text:
package org.n52.tsf.serialization.protobuf.test;

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

import org.n52.tsf.serialization.protobuf.gen.GeoProtobuf.Coordinate;
import org.n52.tsf.serialization.protobuf.gen.GeoProtobuf.Geometry;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import static org.junit.Assert.*;

public class GoPointTest {
    private static final String TEST_FILE_LOCATION = "src/test/resources/geo_data";

    @Before
    public void setUp() throws Exception {
        Path filePath = Paths.get(TEST_FILE_LOCATION);
        Files.createFile(filePath);
    }

    @Test
    public void testSerializeGeoPoint() throws Exception {
        Coordinate.Builder cord = Coordinate.newBuilder();
        cord.setX(1);
        cord.setY(2);
        cord.setZ(Double.NaN);
        Geometry.Builder geo = Geometry.newBuilder();
        geo.setType(Geometry.Type.POINT);
        geo.addCoordinates(cord.build());
        System.out.println("-------------- Serializing Geometry Point -------------------------");
        FileOutputStream output = new FileOutputStream(TEST_FILE_LOCATION);
        try {
            geo.build().writeTo(output);
            System.out.println("Successfully Serialized....");
        } finally {
            output.close();
        }
        assertTrue(new File(TEST_FILE_LOCATION).length() > 0);
        System.out.println("-------------- DeSerializing Geometry Point -----------------------");
        Geometry geometry = Geometry.parseFrom(new FileInputStream(TEST_FILE_LOCATION));
        assertEquals(Geometry.Type.POINT, geometry.getType());
        System.out.println(geometry.getType() + "(" + geometry.getCoordinates(0).getX() + "," +
                geometry.getCoordinates(0).getY() + "," + geometry.getCoordinates(0).getZ() + ")");
        System.out.println("Successfully DeSerialized....");
    }

    @After
    public void tearDown() throws Exception {
        Path filePath = Paths.get(TEST_FILE_LOCATION);
        Files.deleteIfExists(filePath);
    }
}


text:
using LynkAdventures.Graphics;
using Microsoft.Xna.Framework;

namespace LynkAdventures.World.Tiles
{

    /// @author Denis Zhidkikh
    /// @version 5.4.2013
    /// <summary>
    /// Bridge tile.
    /// </summary>
    public class TileBridge : Tile
    {

        /// <summary>
        /// Initializes a new instance of the <see cref="TileBridge"/>.
        /// </summary>
        /// <param name="level">The level.</param>
        public TileBridge(Level level)
            : base(level)
        {
            spriteID = 4;
        }

        /// <summary>
        /// Renders the tile.
        /// </summary>
        /// <param name="xTile">The x position of tile.</param>
        /// <param name="yTile">The y position of tile.</param>
        /// <param name="renderer">The renderer.</param>
        /// <param name="level">The level.</param>
        /// <param name="data">The data value.</param>
        public override void Render(int xTile, int yTile, Renderer renderer, Level level, byte data = 0)
        {
            renderer.RenderTile(xTile * TILESIZE, yTile * TILESIZE, data, GameSpriteSheets.SPRITESHEET_TILES, Color.White, RenderLayer.LAYER_TILE + 0.05F);
            renderer.RenderTile(xTile * TILESIZE, yTile * TILESIZE, spriteID, GameSpriteSheets.SPRITESHEET_TILES, Color.White, RenderLayer.LAYER_TILE);
        }
    }
}


text:
package org.apache.jackrabbit.oak.segment;

import java.util.Iterator;

/**
 * An implementation of {@link SegmentReferences} that throws {@link
 * IllegalStateException}s every time it's used. This instance is used in
 * context where accessing a {@link SegmentReferences} is considered a
 * programmer's error.
 */
class IllegalSegmentReferences implements SegmentReferences {

    @Override
    public SegmentId getSegmentId(int reference) {
        throw new IllegalStateException("invalid use");
    }

    @Override
    public Iterator<SegmentId> iterator() {
        throw new IllegalStateException("invalid use");
    }

}


text:
WEBBOOK.App = {
	// Vars
	status: undefined,
	root:   undefined
}


text:
<!DOCTYPE html>
<html>
  <head>
    <title>Beeswax Alpha</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="http://github.com/notmasteryet/audiodata/raw/master/audiodata.js"></script>
    <script type="text/javascript" src="../../utilities/Utilities.js"></script>
    <script type="text/javascript" src="../../graphic_elements/Element.js"></script>
    <script type="text/javascript" src="../../graphic_elements/UI.js"></script>
    <script type="text/javascript" src="../../graphic_elements/Button.js"></script>
    <script type="text/javascript" src="../../graphic_elements/RotKnob.js"></script>
    <script type="text/javascript" src="../../graphic_elements/wrappers/CanvasDraw.js"></script>
    <script type="text/javascript" src="../../graphic_elements/wrappers/Wrappers.js"></script>
    <script type="text/javascript" src="../../dsp/bw_process.js"></script>
    <script type="text/javascript" src="../../audio/ADBeeswax.js"></script>
  </head>
  <body>
    <canvas id="plugin" width="1000" height="900"></canvas>
    <script type="text/javascript">

        // This should fix "console not defined" problem.
        if (typeof console=="undefined"){console={log:function(A){var B=false;if(B){alert(A)}}}}

        var button_img_array = ["button_sm_01.png", "button_sm_02.png"];

        var imageLoader = new loadImageArray ({ID : "button_image_loader",
                                               imageNames: button_img_array,
                                               onComplete: imagesCompleted,
                                               onSingle: imageSingle,
                                               onError: imageError});

        function imageSingle (loaderStatus) {
            var st = loaderStatus.status;
            console.log ("Image number ", st.loaded, " on ", st.total," was loaded, src is ", loaderStatus.obj.src);
        }

        function imageError (loaderStatus) {
            var st = loaderStatus.status;
            console.log ("Image number ", st.error, " on ", st.total," has errors, src is ", loaderStatus.obj.src);
        }

        function imagesCompleted (loaderStatus) {

            var ui;
            var button = [];

            /* INIT */

            var plugin_canvas = document.getElementById("plugin");

            var CWrapper = K2WRAPPER.createWrapper("CANVAS_WRAPPER",
                                                    {canvas: plugin_canvas}
                                                    );

            ui = new UI (plugin_canvas, CWrapper);

            if (loaderStatus.status.error !== 0) {
                throw new Error(loaderStatus.status.error + " elements failed to load on loader " + loaderStatus.status.id);
            }

            //Buttons
            var buttonArgs = {
                /*ID: "note",*/
                left: 0,
                top: 400,
                imagesArray : loaderStatus.imagesArray,
                isClickable: true
            };

            buttonArgs.onValueSet = function () {
                var that = this;
                return function (slot, value) {
                    var note = slot;
                    if (value === 0) {
                        /*this.*/ADBeesWax.noteOff (slot);
                    }
                    else if (value === 1) {
                        /*this.*/ADBeesWax.noteOff (slot);
                    }
                    else {
                        //throw!
                    }
                };
            }();

            for (var i = 0; i < 7; i ++) {
                buttonArgs.ID = i;
                buttonArgs.left = i * 50;
                button[i] = new Button(buttonArgs);
                ui.addElement(button[i]);
            }

            //debugger;
            var ADBeesWax = new AudioDataBeeswax();
            ADBeesWax.init({sampleRate: 44100});

            ui.refresh();

        }

    </script>
  </body>
</html>


text:
layout: page
title: Scholar Scholar Networks Show
date: 2016-05-24
author: Russell Rice
tags: weekly links, java
status: published
summary: Nam placerat id erat vitae consequat. Sed.
banner: images/banner/wedding.jpg
booking:
  startDate: 11/09/2017
  endDate: 11/13/2017
  ctyhocn: YOWATHX
  groupCode: SSNS
published: true
---
Donec malesuada diam id suscipit volutpat. Vestibulum faucibus sapien non finibus imperdiet. Integer ac nibh lectus. Proin mi quam, pharetra et semper vel, suscipit semper ante. Ut imperdiet mauris odio, nec volutpat leo imperdiet eu. In auctor mollis auctor. Curabitur vel ultricies est, sit amet maximus eros. Donec lobortis justo vel nunc hendrerit, et venenatis nunc auctor.

* Aenean iaculis ligula sit amet enim placerat fermentum
* Pellentesque mattis felis quis quam euismod aliquam
* Phasellus ac orci commodo, malesuada ex non, gravida lorem.

In rhoncus sagittis leo, eget tempus urna. Proin placerat lorem ipsum, non convallis turpis mollis ullamcorper. Vestibulum vel augue id ligula posuere ultricies. Proin hendrerit eros a tellus suscipit semper. Phasellus ultricies, mauris iaculis consectetur cursus, tellus lectus ullamcorper elit, vel pharetra elit nulla eu nisi. Nullam vestibulum vestibulum diam vel cursus. In eu rutrum odio. Nunc rutrum vitae purus id euismod. Morbi in blandit augue. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Praesent at odio lacinia, sagittis tortor ut, cursus enim. Suspendisse pharetra venenatis est, nec fermentum felis. Phasellus pharetra ligula id euismod gravida. Pellentesque cursus velit lectus, sed venenatis tortor rutrum eget. Donec fringilla augue id nulla pellentesque pulvinar. Fusce molestie diam ac nisl pretium sodales.


text:
module CliTodo
  class X
  end
end


text:
<?php

import('lib.pkp.classes.submission.Representation');

class ArticleGalley extends Representation {

	/**
	 * Constructor.
	 */
	function ArticleGalley() {
		parent::Representation();
	}

	/**
	 * Check if galley is an HTML galley.
	 * @return boolean
	 */
	function isHTMLGalley() {
		if ($this->getGalleyType() == 'htmlarticlegalleyplugin')
			return true;
		else
			return false;
	}

	/**
	 * Check if galley is a PDF galley.
	 * @return boolean
	 */
	function isPdfGalley() {
		if ($this->getGalleyType() == 'pdfarticlegalleyplugin')
			return true;
		else
			return false;
	}

	/**
	 * Check if the specified file is a dependent file.
	 * @param $fileId int
	 * @return boolean
	 */
	function isDependentFile($fileId) {
		return false;
	}

	//
	// Get/set methods
	//

	/**
	 * Get views count.
	 * @return int
	 */
	function getViews() {
		$application = PKPApplication::getApplication();
		return $application->getPrimaryMetricByAssoc(ASSOC_TYPE_GALLEY, $this->getId());
	}

	/**
	 * Get the localized value of the galley label.
	 * @return $string
	 */
	function getGalleyLabel() {
		$label = $this->getLabel();
		if ($this->getLocale() != AppLocale::getLocale()) {
			$locales = AppLocale::getAllLocales();
			$label .= ' (' . $locales[$this->getLocale()] . ')';
		}
		return $label;
	}

	/**
	 * Get label/title.
	 * @return string
	 */
	function getLabel() {
		return $this->getData('label');
	}

	/**
	 * Set label/title.
	 * @param $label string
	 */
	function setLabel($label) {
		return $this->setData('label', $label);
	}

	/**
	 * Get locale.
	 * @return string
	 */
	function getLocale() {
		return $this->getData('locale');
	}

	/**
	 * Set locale.
	 * @param $locale string
	 */
	function setLocale($locale) {
		return $this->setData('locale', $locale);
	}

	/**
	 * Return the "best" article ID -- If a public article ID is set,
	 * use it; otherwise use the internal article Id. (Checks the journal
	 * settings to ensure that the public ID feature is enabled.)
	 * @param $journal Object the journal this galley is in
	 * @return string
	 */
	function getBestGalleyId($journal) {
		if ($journal->getSetting('enablePublicGalleyId')) {
			$publicGalleyId = $this->getStoredPubId('publisher-id');
			if (!empty($publicGalleyId)) return $publicGalleyId;
		}
		return $this->getId();
	}

	/**
	 * Set remote URL of the galley.
	 * @param $remoteURL string
	 */
	function setRemoteURL($remoteURL) {
		return $this->setData('remoteURL', $remoteURL);
	}

	/**
	 * Get remote URL of the galley.
	 * @return string
	 */
	function getRemoteURL() {
		return $this->getData('remoteURL');
	}

	/**
	 * Determines if a galley is available or not.
	 * @return boolean
	 */
	function getIsAvailable() {
		return $this->getData('isAvailable') ? true : false;
	}

	/**
	 * Sets whether a galley is available or not.
	 * @param boolean $isAvailable
	 */
	function setIsAvailable($isAvailable) {
		return $this->setData('isAvailable', $isAvailable);
	}

	/**
	 * Set the type of this galley, which maps to an articleGalley plugin.
	 * @param string $galleyType
	 */
	function setGalleyType($galleyType) {
		return $this->setData('galleyType', $galleyType);
	}

	/**
	 * Returns the type of this galley.
	 * @return string
	 */
	function getGalleyType() {
		return $this->getData('galleyType');
	}

	/**
	 * Convenience method for fetching the latest revisions of the files for this galley.
	 * @param $fileExtensionMatch string optional limit to specific file type.
	 * @return array SubmissionFile
	 */
	function getLatestGalleyFiles($fileExtensionMatch = null) {
		$submissionFileDao = DAORegistry::getDAO('SubmissionFileDAO');
		$submissionFiles = $submissionFileDao->getLatestRevisionsByAssocId(
			ASSOC_TYPE_GALLEY, $this->getId(),
			$this->getSubmissionId(), SUBMISSION_FILE_PROOF
		);

		if (!$fileExtensionMatch) {
			return $submissionFiles;
		} else {
			$filteredFiles = array();
			foreach ($submissionFiles as $id => $file) {
				if (preg_match('/\.' . preg_quote($fileExtensionMatch) . '[^\.]*$/', $file->getOriginalFileName())) {
					$filteredFiles[$id] = $file;
				}
			}

			return $filteredFiles;
		}
	}

	/**
	 * Attempt to retrieve the first file assigned to this galley.
	 * @param $fileType string optional limit to specific file type.
	 * @param $allFiles whether or not to include non-viewable files.
	 * @return SubmissionFile or null
	 */
	function getFirstGalleyFile($fileType = null, $allFiles = false) {
		$submissionFiles = $this->getLatestGalleyFiles($fileType);
		if (is_array($submissionFiles) && sizeof($submissionFiles) > 0) {
			if ($allFiles) {
				return array_shift($submissionFiles);
			} else { // return first viewable file.
				foreach ($submissionFiles as $id => $file) {
					if ($file->getViewable()) return $file;
				}
			}
		}

		return null;
	}
}

?>


text:
struct Quota
{
  // Holds the quota protobuf, as constructed from an operator's request.
  mesos::quota::QuotaInfo info;
};

#endif // __MESOS_QUOTA_PROTO_HPP__


text:
export default /*@ngInject*/class ChangePasswordController{
  constructor(user, $http, $uibModalInstance){
    this.user = user;
    this.$http = $http;
    this.$uibModalInstance = $uibModalInstance;
    this.data = {};
    this.formOptions = {
      formState: {
        showPasswords: false
      }
    };
    this.fields = [
      {
        key: 'old',
        type: 'horizontalInput',
        templateOptions: {
          type: 'password',
          label: 'Altes Passwort',
          required: true,
          placeholder: 'unlösbar',
          minlength: 8
        },
        expressionProperties: {
          'templateOptions.type': 'formState.showPasswords ? "text" : "password"'
        }
      },
      {
        key: 'new',
        type: 'horizontalInput',
        templateOptions: {
          type: 'password',
          label: 'Neues Passwort',
          required: true,
          placeholder: 'unlösbar',
          minlength: 8
        },
        expressionProperties: {
          'templateOptions.type': 'formState.showPasswords ? "text" : "password"'
        }
      },
      {
        key: 'showPasswords',
        model: this.formOptions.formState,
        type: 'horizontalCheckbox',
        templateOptions: {
          label: 'Passwörter einblenden'
        }
      }
    ];
  }
  change(){
    return this.$http.put(`api/users/${this.user._id}/password`, this.data)
    .then(
      (data) => {
        return this.$uibModalInstance.close(data);
      },
      (e) => {
        this.message = e.data;
        return e;
      }
    );
  }
  cancel(){
    this.$uibModalInstance.dismiss('cancel');
  }
  static get $inject(){
    return ['user', '$http', '$uibModalInstance'];
  }
}


text:
title: Latest Posts

sitemap:
    changefreq: monthly
    priority: 1.03

content:
    items: @self.children
    order:
        by: date
        dir: desc
    limit: 100
    pagination: true

feed:
    description: Sample Blog Description
    limit: 8

pagination: true
---


text:
package com.ctrctr.pointcounter;

/**
 * Created by roycesanto on 6/7/2015.
 */
public class Player
{
    //Object Player
    String playername;
    int score;
    int maxscore;
    boolean usedeuce;

    public Player (String name, int initialscore, int maxscore, boolean usedeuce)
    {
        this.playername = name;
        this.score = initialscore;
        this.maxscore = maxscore;
        this.usedeuce = usedeuce;
    }
    public void resetScore()
    {
        score = 0;
    }
    public void addScore(int value)
    {
        score += value;
    }
    public void deuce(int value)
    {
        maxscore += value;
    }
    public String getName()
    {
        return playername;
    }
    public int getScore()
    {
        return score;
    }
    public int getMaxScore()
    {
        return score;
    }
    public boolean isScoreMax()
    {
        if (score == maxscore)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    public boolean matchPoint()
    {
        if (maxscore-score == 1)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}


text:
.. _zend.navigation.pages:

Pages
=====

``Zend\Navigation`` ships with two page types:

- :ref:`MVC pages <zend.navigation.pages.mvc>` – using the class ``Zend\Navigation\Page\Mvc``
- :ref:`URI pages <zend.navigation.pages.uri>` – using the class ``Zend\Navigation\Page\Uri``

MVC pages are link to on-site web pages, and are defined using MVC parameters (*action*, *controller*,
*route*, *params*). URI pages are defined by a single property *uri*, which give you the full flexibility to link
off-site pages or do other things with the generated links (e.g. an URI that turns into ``<a href="#">foo<a>``).

.. include:: zend.navigation.pages.common.rst
.. include:: zend.navigation.pages.mvc.rst
.. include:: zend.navigation.pages.uri.rst
.. include:: zend.navigation.pages.custom.rst
.. include:: zend.navigation.pages.factory.rst


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

import com.facebook.presto.sql.planner.plan.PlanNodeId;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.ImmutableSet;

import java.util.List;
import java.util.Set;

import static com.facebook.presto.operator.StageExecutionDescriptor.StageExecutionStrategy.DYNAMIC_LIFESPAN_SCHEDULE_GROUPED_EXECUTION;
import static com.facebook.presto.operator.StageExecutionDescriptor.StageExecutionStrategy.FIXED_LIFESPAN_SCHEDULE_GROUPED_EXECUTION;
import static com.facebook.presto.operator.StageExecutionDescriptor.StageExecutionStrategy.UNGROUPED_EXECUTION;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;

public class StageExecutionDescriptor
{
    private final StageExecutionStrategy stageExecutionStrategy;
    private final Set<PlanNodeId> groupedExecutionScanNodes;

    private StageExecutionDescriptor(StageExecutionStrategy stageExecutionStrategy, Set<PlanNodeId> groupedExecutionScanNodes)
    {
        switch (stageExecutionStrategy) {
            case UNGROUPED_EXECUTION:
                checkArgument(groupedExecutionScanNodes.isEmpty(), "groupedExecutionScanNodes must be empty if stage execution strategy is ungrouped execution");
                break;
            case FIXED_LIFESPAN_SCHEDULE_GROUPED_EXECUTION:
            case DYNAMIC_LIFESPAN_SCHEDULE_GROUPED_EXECUTION:
                checkArgument(!groupedExecutionScanNodes.isEmpty(), "groupedExecutionScanNodes cannot be empty if stage execution strategy is grouped execution");
                break;
            default:
                throw new IllegalArgumentException("Unsupported stage execution strategy: " + stageExecutionStrategy);
        }

        this.stageExecutionStrategy = requireNonNull(stageExecutionStrategy, "stageExecutionStrategy is null");
        this.groupedExecutionScanNodes = requireNonNull(groupedExecutionScanNodes, "groupedExecutionScanNodes is null");
    }

    public static StageExecutionDescriptor ungroupedExecution()
    {
        return new StageExecutionDescriptor(UNGROUPED_EXECUTION, ImmutableSet.of());
    }

    public static StageExecutionDescriptor fixedLifespanScheduleGroupedExecution(List<PlanNodeId> capableScanNodes)
    {
        requireNonNull(capableScanNodes, "capableScanNodes is null");
        checkArgument(!capableScanNodes.isEmpty(), "capableScanNodes cannot be empty if stage execution strategy is grouped execution");
        return new StageExecutionDescriptor(FIXED_LIFESPAN_SCHEDULE_GROUPED_EXECUTION, ImmutableSet.copyOf(capableScanNodes));
    }

    public static StageExecutionDescriptor dynamicLifespanScheduleGroupedExecution(List<PlanNodeId> capableScanNodes)
    {
        requireNonNull(capableScanNodes, "capableScanNodes is null");
        checkArgument(!capableScanNodes.isEmpty(), "capableScanNodes cannot be empty if stage execution strategy is grouped execution");
        return new StageExecutionDescriptor(DYNAMIC_LIFESPAN_SCHEDULE_GROUPED_EXECUTION, ImmutableSet.copyOf(capableScanNodes));
    }

    public StageExecutionStrategy getStageExecutionStrategy()
    {
        return stageExecutionStrategy;
    }

    public boolean isStageGroupedExecution()
    {
        return stageExecutionStrategy != UNGROUPED_EXECUTION;
    }

    public boolean isDynamicLifespanSchedule()
    {
        return stageExecutionStrategy == DYNAMIC_LIFESPAN_SCHEDULE_GROUPED_EXECUTION;
    }

    public boolean isScanGroupedExecution(PlanNodeId scanNodeId)
    {
        return groupedExecutionScanNodes.contains(scanNodeId);
    }

    @JsonCreator
    public static StageExecutionDescriptor jsonCreator(
            @JsonProperty("stageExecutionStrategy") StageExecutionStrategy stageExecutionStrategy,
            @JsonProperty("groupedExecutionScanNodes") Set<PlanNodeId> groupedExecutionCapableScanNodes)
    {
        return new StageExecutionDescriptor(
                requireNonNull(stageExecutionStrategy, "stageExecutionStrategy is null"),
                ImmutableSet.copyOf(requireNonNull(groupedExecutionCapableScanNodes, "groupedExecutionScanNodes is null")));
    }

    @JsonProperty("stageExecutionStrategy")
    public StageExecutionStrategy getJsonSerializableStageExecutionStrategy()
    {
        return stageExecutionStrategy;
    }

    @JsonProperty("groupedExecutionScanNodes")
    public Set<PlanNodeId> getJsonSerializableGroupedExecutionScanNodes()
    {
        return groupedExecutionScanNodes;
    }

    public enum StageExecutionStrategy
    {
        UNGROUPED_EXECUTION,
        FIXED_LIFESPAN_SCHEDULE_GROUPED_EXECUTION,
        DYNAMIC_LIFESPAN_SCHEDULE_GROUPED_EXECUTION
    }
}


text:
package com.github.blackrush.acara;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * Mark a method as an event listener.
 */
@Retention(RUNTIME)
@Target(METHOD)
public @interface Listen {
    /**
     * Enable or disable this method. {@code false} by default.
     * @return whether or not the method is disabled
     */
    boolean disabled() default false;
}


text:
<?php
Mock::Generate('Csv_Dialect', 'Mock_Dialect');
Mock::Generate('Csv_Dialect', 'Mock_Dialect_Two');
/**
 * Csv Writer unit tests
 */
class Test_Of_Csv_Writer extends UnitTestCase {

    public function setUp() {

        $this->dialect = new Mock_Dialect;
        $this->dialect->delimiter = ",";
        $this->dialect->quotechar = '"';
        $this->dialect->escapechar = "\\";
        $this->dialect->skipblanklines = true;
        $this->dialect->lineterminator = "\r\n";

        $this->file = realpath('../') . '/tests/data/writer1.csv';
        $this->file2 = realpath('../') . '/tests/data/writer2.csv';
        $this->file3 = realpath('../') . '/tests/data/writer3.csv';

        $this->testdata = array(

            array(
                'This contains the quote "character" because it\'s cool like that',
                1,
                2,
            ),
            array(
                "This one contains some commas, and some \t\t tabs and stuff",
                45,
                2009,
            ),
            array(
                'I have "several" different kinds of \'quotes\'',
                133,
                2234234,
            ),
            array(
                "I am regular\n\r text but with a line break in me",
                21,
                "Num123412342",
            ),

        );

    }
    public function tearDown() {

        if (file_exists($this->file)) unlink($this->file);
        if (file_exists($this->file2)) unlink($this->file2);
        if (file_exists($this->file3)) unlink($this->file3);

    }
    /**
     *
     */
    public function test_Csv_Writer_Accepts_Filename_In_Constructor() {

        $writer = new Csv_Writer($this->file);
        $this->assertEqual($this->file, $writer->getPath());

    }
    /**
     *
     */
    public function test_Csv_Writer_Uses_Default_Dialect() {

        $writer = new Csv_Writer($this->file);
        $this->assertIsA($writer->getDialect(), 'Csv_Dialect');

    }
    /**
     * Csv_Writer should also be able to accept a csv dialect in its constructor or by setDialect()
    */
    public function test_Csv_Writer_Accepts_Custom_Dialect() {

        $reader = new Csv_Writer($this->file, new Mock_Dialect());
        $this->assertIsA($reader->getDialect(), 'Csv_Dialect');

        $reader->setDialect(new Mock_Dialect_Two());
        $this->assertIsA($reader->getDialect(), 'Mock_Dialect_Two');

    }
    /**
     * Writer should create the file if it doesnt exist (the close method will write changes to the db)
     */
    public function test_Csv_Writer_Constructor_Creates_File_If_Nonexistant() {

        $this->assertFalse(file_exists($this->file));
        $writer = new Csv_Writer($this->file);
        $writer->writeRow(array('one','two','three'));
        $this->assertTrue(file_exists($this->file));

    }
    /**
     * An exception should be thrown if there is an error writing to the csv file
     */
    public function test_Csv_Writer_Throws_Exception_If_Cant_Write() {

        $path = './';
        $this->expectException(new Csv_Exception_FileNotFound(sprintf('Unable to create/access file: "%s".', $path)));
        $writer = new Csv_Writer($path);
        $writer->writeRow(array('one','two','three'));

    }
    /**
     * Test that writeRow writes one row to the file
     */
    public function test_Csv_Writer_Writes_Row_Immediately() {

        $row = array('ONE', 'TWO', 'THREE');
        $writer = new Csv_Writer($this->file2);
        $writer->writeRow($row);
        $this->assertEqual(file_get_contents($this->file2), 'ONE,TWO,THREE' . $writer->getDialect()->lineterminator);

    }
    /**
     * Test that all pending changes are written to the file when the object is destroyed
     */
    public function test_Csv_Writer_Writes_Row_When_Destroyed() {

        $row = array('ONE', 'TWO', 'THREE');
        $writer = new Csv_Writer($this->file3);
        $writer->writeRow($row);
        $lineterm = $writer->getDialect()->lineterminator;
        unset($writer);
        $this->assertEqual(file_get_contents($this->file3), 'ONE,TWO,THREE' . $lineterm);

    }

    public function test_Can_Change_delimiter() {

        $dialect = new Mock_Dialect;
        $dialect->delimiter = "#";
        $writer = new Csv_Writer($this->file, $dialect);
        $writer->writeRow(array(1,2,3));
        $this->assertEqual(file_get_contents($this->file), '1#2#3' . $writer->getDialect()->lineterminator);

    }
    /**
     * Test that dialects work correctly with quoting and escaping things
     */
    public function test_Dialect_Quote_None() {

        $this->dialect->quoting = Csv_Dialect::QUOTE_NONE;

        $writer = new Csv_Writer($this->file, $this->dialect);
        $writer->writeRow($this->testdata[0]);
        $this->assertEqual('This contains the quote "character" because it\'s cool like that,1,2' . $writer->getDialect()->lineterminator, file_get_contents($this->file));

    }
    /**
     *
     */
    public function test_Dialect_Quote_All() {

        $this->dialect->quoting = Csv_Dialect::QUOTE_ALL;
        $writer = new Csv_Writer($this->file, $this->dialect);
        $writer->writeRow($this->testdata[0]);
        $this->assertEqual('"This contains the quote \\"character\\" because it\'s cool like that","1","2"' . $writer->getDialect()->lineterminator, file_get_contents($this->file));

    }
    /**
     *
     */
    public function test_Dialect_Quote_Minimum() {

        $this->dialect->quoting = Csv_Dialect::QUOTE_MINIMAL;
        $writer = new Csv_Writer($this->file, $this->dialect);
        $writer->writeRow($this->testdata[0]);
        // check that quotes cause text to be quoted
        $this->assertEqual('"This contains the quote \\"character\\" because it\'s cool like that",1,2' . $writer->getDialect()->lineterminator, file_get_contents($this->file));

        // check that line breaks cause text to be quoted
        $writer = new Csv_Writer($this->file2, $this->dialect);
        $writer->writeRow($this->testdata[3]);
        $this->assertEqual('"I am regular' . "\n\r" . ' text but with a line break in me",21,Num123412342' . $writer->getDialect()->lineterminator, file_get_contents($this->file2));

        // check that commas (if they are the delim char) cause text to be quoted
        $writer = new Csv_Writer($this->file3, $this->dialect);
        $writer->writeRow($this->testdata[1]);
        $this->assertEqual("\"This one contains some commas, and some \t\t tabs and stuff\",45,2009" . $writer->getDialect()->lineterminator, file_get_contents($this->file3));

    }
    /**
     *
     */
    public function test_Dialect_Quote_Nonnumeric() {

        $this->dialect->quoting = Csv_Dialect::QUOTE_NONNUMERIC;
        $writer = new Csv_Writer($this->file, $this->dialect);
        $writer->writeRow($this->testdata[3]);
        $this->assertEqual('"I am regular' . "\n\r" . ' text but with a line break in me",21,"Num123412342"' . $writer->getDialect()->lineterminator, file_get_contents($this->file));

    }
    /**
     * Test that writer accepts a multi-dimensional array of rows to write to disk
     */
    public function test_Writer_Accepts_Array() {

        $writer = new Csv_Writer($this->file);
        $data = array(
            array(1,2,3),
            array(4,5,6),
            array(7,8,9),
        );
        $writer->writeRows($data);
        $this->assertEqual("1,2,3" . $writer->getDialect()->lineterminator . "4,5,6" . $writer->getDialect()->lineterminator . "7,8,9" . $writer->getDialect()->lineterminator, file_get_contents($this->file));

    }
    /**
     * Test that writer accepts a reader object to read from instead of an array
     * @todo For some reason not having a line-ending char causes the reader to not read the last line - find out why
     */
    public function test_Writer_WriteRows_Accepts_Reader() {

        file_put_contents($this->file, "1,2,3\r\n4,5,6\r\n7,8,9\r\n"); // test csv file
        $reader = new Csv_Reader($this->file, new Csv_Dialect());
        $writer = new Csv_Writer($this->file2);
        $dialect = $writer->getDialect();
        $dialect->delimiter = "\t";
        $writer->setDialect($dialect);
        $writer->writeRows($reader);
        $this->assertEqual("1\t2\t3\r\n4\t5\t6\r\n7\t8\t9" . $writer->getDialect()->lineterminator, file_get_contents($this->file2));

    }
    /**
     * @todo When appending a file, there should be a way to detect if you need to prepend a newline char
     *       maybe check to see if the last char in the file is a newline char and if not, prepend one?
     */
    public function test_Writer_Accepts_Handle() {

        $content = "1,2,3\r\n4,5,6\r\n7,8,9\r\n";
        file_put_contents($this->file, $content);
        $file = fopen($this->file, 'ab');
        $writer = new Csv_Writer($file);
        $writer->writeRow(array(10,11,12));
        $this->assertEqual(file_get_contents($this->file), $content . "10,11,12" . $writer->getDialect()->lineterminator);

    }

}


text:
package com.frostwire.jlibtorrent.demo;

import com.frostwire.jlibtorrent.AlertListener;
import com.frostwire.jlibtorrent.EnumNet;
import com.frostwire.jlibtorrent.SessionManager;
import com.frostwire.jlibtorrent.alerts.Alert;

import java.util.List;

/**
 * @author gubatron
 * @author aldenml
 */
public final class EnumNetTest {

    public static void main(String[] args) throws Throwable {

        SessionManager s = new SessionManager();

        s.addListener(new AlertListener() {
            @Override
            public int[] types() {
                return null;
            }

            @Override
            public void alert(Alert<?> alert) {
                //System.out.println(alert);
            }
        });

        s.start();

        System.out.println("Enum interfaces");
        List<EnumNet.IpInterface> ipInterfaces = EnumNet.enumInterfaces(s);
        for (EnumNet.IpInterface iface : ipInterfaces) {
            System.out.println(iface);
        }

        System.out.println("Enum routers");
        List<EnumNet.IpRoute> ipRoutes = EnumNet.enumRoutes(s);
        for (EnumNet.IpRoute route : ipRoutes) {
            System.out.println(route);
        }

        System.out.println("Default gateway: " + EnumNet.defaultGateway(s, "", false));

        System.out.println("Press ENTER to exit");
        System.in.read();

        s.stop();
    }
}


text:
typedef struct _EFI_TIME EFI_TIME;

// EFI Device Path Protocol

#define EFI_DEVICE_PATH_PROTOCOL_GUID \
	{0x09576e91,0x6d3f,0x11d2, {0x8e,0x39,0x00,0xa0,0xc9,0x69,0x72,0x3b}}
#define EFI_LOADED_IMAGE_DEVICE_PATH_PROTOCOL_GUID \
	{0xbc62157e,0x3e33,0x4fec, {0x99,0x20,0x2d,0x3b,0x36,0xd7,0x50,0xdf}}

typedef struct _EFI_DEVICE_PATH_PROTOCOL {
	UINT8 Type;
	UINT8 SubType;
	UINT8 Length[2];
} EFI_DEVICE_PATH_PROTOCOL;

// Device Path Utilities Protocol

#define EFI_DEVICE_PATH_UTILITIES_PROTOCOL_GUID \
	{0x379be4e,0xd706,0x437d, {0xb0,0x37,0xed,0xb8,0x2f,0xb7,0x72,0xa4 }}

typedef struct _EFI_DEVICE_PATH_UTILITIES_PROTOCOL EFI_DEVICE_PATH_UTILITIES_PROTOCOL;

typedef
UINTN
(EFIAPI *EFI_DEVICE_PATH_UTILS_GET_DEVICE_PATH_SIZE) (
	IN CONST EFI_DEVICE_PATH_PROTOCOL *DevicePath
);

typedef
EFI_DEVICE_PATH_PROTOCOL*
(EFIAPI *EFI_DEVICE_PATH_UTILS_DUP_DEVICE_PATH) (
	IN CONST EFI_DEVICE_PATH_PROTOCOL *DevicePath
);

typedef
EFI_DEVICE_PATH_PROTOCOL*
(EFIAPI *EFI_DEVICE_PATH_UTILS_APPEND_PATH) (
	IN CONST EFI_DEVICE_PATH_PROTOCOL *Src1,
	IN CONST EFI_DEVICE_PATH_PROTOCOL *Src2
);

typedef
EFI_DEVICE_PATH_PROTOCOL*
(EFIAPI *EFI_DEVICE_PATH_UTILS_APPEND_NODE) (
	IN CONST EFI_DEVICE_PATH_PROTOCOL *DevicePath,
	IN CONST EFI_DEVICE_PATH_PROTOCOL *DeviceNode
);

typedef
EFI_DEVICE_PATH_PROTOCOL*
(EFIAPI *EFI_DEVICE_PATH_UTILS_APPEND_INSTANCE) (
	IN CONST EFI_DEVICE_PATH_PROTOCOL *DevicePath,
	IN CONST EFI_DEVICE_PATH_PROTOCOL *DevicePathInstance
);

typedef
EFI_DEVICE_PATH_PROTOCOL*
(EFIAPI *EFI_DEVICE_PATH_UTILS_GET_NEXT_INSTANCE) (
	IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePathInstance,
	OUT UINTN *DevicePathInstanceSize OPTIONAL
);

typedef
EFI_DEVICE_PATH_PROTOCOL*
(EFIAPI *EFI_DEVICE_PATH_UTILS_CREATE_NODE) (
	IN UINT8 NodeType,
	IN UINT8 NodeSubType,
	IN UINT16 NodeLength
);

typedef
BOOLEAN
(EFIAPI *EFI_DEVICE_PATH_UTILS_IS_MULTI_INSTANCE) (
	IN CONST EFI_DEVICE_PATH_PROTOCOL *DevicePath
);

typedef struct _EFI_DEVICE_PATH_UTILITIES_PROTOCOL {
	EFI_DEVICE_PATH_UTILS_GET_DEVICE_PATH_SIZE GetDevicePathSize;
	EFI_DEVICE_PATH_UTILS_DUP_DEVICE_PATH DuplicateDevicePath;
	EFI_DEVICE_PATH_UTILS_APPEND_PATH AppendDevicePath;
	EFI_DEVICE_PATH_UTILS_APPEND_NODE AppendDeviceNode;
	EFI_DEVICE_PATH_UTILS_APPEND_INSTANCE AppendDevicePathInstance;
	EFI_DEVICE_PATH_UTILS_GET_NEXT_INSTANCE GetNextDevicePathInstance;
	EFI_DEVICE_PATH_UTILS_IS_MULTI_INSTANCE IsDevicePathMultiInstance;
	EFI_DEVICE_PATH_UTILS_CREATE_NODE CreateDeviceNode;
} EFI_DEVICE_PATH_UTILITIES_PROTOCOL;

// Device Path to Text Protocol

#define EFI_DEVICE_PATH_TO_TEXT_PROTOCOL_GUID \
	{0x8b843e20,0x8132,0x4852, {0x90,0xcc,0x55,0x1a,0x4e,0x4a,0x7f,0x1c}}

typedef
CHAR16*
(EFIAPI *EFI_DEVICE_PATH_TO_TEXT_NODE) (
	IN CONST EFI_DEVICE_PATH_PROTOCOL* DeviceNode,
	IN BOOLEAN DisplayOnly,
	IN BOOLEAN AllowShortcuts
);

typedef
CHAR16*
(EFIAPI *EFI_DEVICE_PATH_TO_TEXT_PATH) (
	IN CONST EFI_DEVICE_PATH_PROTOCOL *DevicePath,
	IN BOOLEAN DisplayOnly,
	IN BOOLEAN AllowShortcuts
);

typedef struct _EFI_DEVICE_PATH_TO_TEXT_PROTOCOL {
	EFI_DEVICE_PATH_TO_TEXT_NODE ConvertDeviceNodeToText;
	EFI_DEVICE_PATH_TO_TEXT_PATH ConvertDevicePathToText;
} EFI_DEVICE_PATH_TO_TEXT_PROTOCOL;

// Device Path from Text Protocol

#define EFI_DEVICE_PATH_FROM_TEXT_PROTOCOL_GUID \
	{0x5c99a21,0xc70f,0x4ad2, {0x8a,0x5f,0x35,0xdf,0x33,0x43,0xf5, 0x1e}}

typedef
EFI_DEVICE_PATH_PROTOCOL*
(EFIAPI *EFI_DEVICE_PATH_FROM_TEXT_NODE) (
	IN CONST CHAR16* TextDeviceNode
);

typedef
EFI_DEVICE_PATH_PROTOCOL*
(EFIAPI *EFI_DEVICE_PATH_FROM_TEXT_PATH) (
	IN CONST CHAR16* TextDevicePath
);

typedef struct _EFI_DEVICE_PATH_FROM_TEXT_PROTOCOL {
	EFI_DEVICE_PATH_FROM_TEXT_NODE ConvertTextToDevicNode;
	EFI_DEVICE_PATH_FROM_TEXT_PATH ConvertTextToDevicPath;
} EFI_DEVICE_PATH_FROM_TEXT_PROTOCOL;

// EFI Loaded Image Protocol

#define EFI_LOADED_IMAGE_PROTOCOL_GUID\
	{0x5B1B31A1,0x9562,0x11d2, {0x8E,0x3F,0x00,0xA0,0xC9,0x69,0x72,0x3B}}

#define EFI_LOADED_IMAGE_PROTOCOL_REVISION 0x1000

typedef
EFI_STATUS
(EFIAPI *EFI_IMAGE_UNLOAD) (
	IN EFI_HANDLE ImageHandle
);

typedef struct {
	UINT32 Revision;
	EFI_HANDLE ParentHandle;
	EFI_SYSTEM_TABLE *SystemTable;
	// Source location of the image
	EFI_HANDLE DeviceHandle;
	EFI_DEVICE_PATH_PROTOCOL *FilePath;
	VOID *Reserved;
	// Image's load options
	UINT32 LoadOptionsSize;
	VOID *LoadOptions;
	// Location where image was loaded
	VOID *ImageBase;
	UINT64 ImageSize;
	EFI_MEMORY_TYPE ImageCodeType;
	EFI_MEMORY_TYPE ImageDataType;
	EFI_IMAGE_UNLOAD Unload;
} EFI_LOADED_IMAGE_PROTOCOL;

// EFI_LOAD_FILE_PROTOCOL

#define EFI_LOAD_FILE_PROTOCOL_GUID \
	{0x56EC3091,0x954C,0x11d2, {0x8e,0x3f,0x00,0xa0, 0xc9,0x69,0x72,0x3b}}
#define EFI_LOAD_FILE2_PROTOCOL_GUID \
	{ 0x4006c0c1, 0xfcb3, 0x403e, { 0x99, 0x6d, 0x4a, 0x6c, 0x87, 0x24, 0xe0, 0x6d }}

typedef struct _EFI_LOAD_FILE_PROTOCOL EFI_LOAD_FILE_PROTOCOL;

typedef
EFI_STATUS
(EFIAPI *EFI_LOAD_FILE) (
	IN EFI_LOAD_FILE_PROTOCOL *This,
	IN EFI_DEVICE_PATH_PROTOCOL *FilePath,
	IN BOOLEAN BootPolicy,
	IN OUT UINTN *BufferSize,
	IN VOID *Buffer OPTIONAL
);

typedef struct _EFI_LOAD_FILE_PROTOCOL {
	EFI_LOAD_FILE LoadFile;
} EFI_LOAD_FILE_PROTOCOL;

typedef EFI_LOAD_FILE_PROTOCOL EFI_LOAD_FILE2_PROTOCOL;

// Simple File System Protocol

#define EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_GUID \
	{0x0964e5b22,0x6459,0x11d2, {0x8e,0x39,0x00,0xa0,0xc9,0x69,0x72,0x3b}}
#define EFI_FILE_INFO_ID \
	{0x09576e92,0x6d3f,0x11d2, {0x8e,0x39,0x00,0xa0,0xc9,0x69,0x72,0x3b}}
#define EFI_FILE_SYSTEM_INFO_ID \
	{0x09576e93,0x6d3f,0x11d2, {0x8e,0x39,0x00,0xa0,0xc9,0x69,0x72,0x3b}}
#define EFI_FILE_SYSTEM_VOLUME_LABEL_ID \
	{0xdb47d7d3,0xfe81,0x11d3, {0x9a, 0x35, 0x00,0x90,0x27,0x3f,0xC1,0x4d}}

typedef struct _EFI_SIMPLE_FILE_SYSTEM_PROTOCOL EFI_SIMPLE_FILE_SYSTEM_PROTOCOL;
typedef struct _EFI_FILE_PROTOCOL EFI_FILE_PROTOCOL;
typedef struct _EFI_FILE_PROTOCOL *EFI_FILE_HANDLE;

#define EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_REVISION 0x00010000

#define EFI_FILE_PROTOCOL_REVISION 0x00010000
#define EFI_FILE_PROTOCOL_REVISION2 0x00020000
#define EFI_FILE_PROTOCOL_LATEST_REVISION EFI_FILE_PROTOCOL_REVISION2

#define EFI_FILE_MODE_READ 0x0000000000000001
#define EFI_FILE_MODE_WRITE 0x0000000000000002
#define EFI_FILE_MODE_CREATE 0x8000000000000000

#define EFI_FILE_READ_ONLY 0x0000000000000001
#define EFI_FILE_HIDDEN 0x0000000000000002
#define EFI_FILE_SYSTEM 0x0000000000000004
#define EFI_FILE_RESERVED 0x0000000000000008
#define EFI_FILE_DIRECTORY 0x0000000000000010
#define EFI_FILE_ARCHIVE 0x0000000000000020
#define EFI_FILE_VALID_ATTR 0x0000000000000037

typedef struct {
	EFI_EVENT Event;
	EFI_STATUS Status;
	UINTN BufferSize;
	VOID *Buffer;
} EFI_FILE_IO_TOKEN;

typedef struct {
	UINT64 Size;
	UINT64 FileSize;
	UINT64 PhysicalSize;
	EFI_TIME CreateTime;
	EFI_TIME LastAccessTime;
	EFI_TIME ModificationTime;
	UINT64 Attribute;
	CHAR16 FileName[1];
} EFI_FILE_INFO;

typedef struct {
	UINT64 Size;
	BOOLEAN ReadOnly;
	UINT64 VolumeSize;
	UINT64 FreeSpace;
	UINT32 BlockSize;
	CHAR16 VolumeLabel[1];
} EFI_FILE_SYSTEM_INFO;

typedef struct {
	CHAR16 VolumeLabel[1];
} EFI_FILE_SYSTEM_VOLUME_LABEL;

typedef
EFI_STATUS
(EFIAPI *EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_OPEN_VOLUME) (
	IN EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *This,
	OUT EFI_FILE_PROTOCOL **Root
);

typedef struct _EFI_SIMPLE_FILE_SYSTEM_PROTOCOL {
	UINT64 Revision;
	EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_OPEN_VOLUME OpenVolume;
} EFI_SIMPLE_FILE_SYSTEM_PROTOCOL;

typedef
EFI_STATUS
(EFIAPI *EFI_FILE_OPEN) (
	IN EFI_FILE_PROTOCOL *This,
	OUT EFI_FILE_PROTOCOL **NewHandle,
	IN CONST CHAR16 *FileName,
	IN UINT64 OpenMode,
	IN UINT64 Attributes
);

typedef
EFI_STATUS
(EFIAPI *EFI_FILE_CLOSE) (
	IN EFI_FILE_PROTOCOL *This
);

typedef
EFI_STATUS
(EFIAPI *EFI_FILE_DELETE) (
	IN EFI_FILE_PROTOCOL *This
);

typedef
EFI_STATUS
(EFIAPI *EFI_FILE_READ) (
	IN EFI_FILE_PROTOCOL *This,
	IN OUT UINTN *BufferSize,
	OUT VOID *Buffer
);

typedef
EFI_STATUS
(EFIAPI *EFI_FILE_WRITE) (
	IN EFI_FILE_PROTOCOL *This,
	IN OUT UINTN *BufferSize,
	IN VOID *Buffer
);

typedef
EFI_STATUS
(EFIAPI *EFI_FILE_OPEN_EX) (
	IN EFI_FILE_PROTOCOL *This,
	OUT EFI_FILE_PROTOCOL **NewHandle,
	IN CHAR16 *FileName,
	IN UINT64 OpenMode,
	IN UINT64 Attributes,
	IN OUT EFI_FILE_IO_TOKEN *Token
);

typedef
EFI_STATUS
(EFIAPI *EFI_FILE_READ_EX) (
	IN EFI_FILE_PROTOCOL *This,
	IN OUT EFI_FILE_IO_TOKEN *Token
);

typedef
EFI_STATUS
(EFIAPI *EFI_FILE_WRITE_EX) (
	IN EFI_FILE_PROTOCOL *This,
	IN OUT EFI_FILE_IO_TOKEN *Token
);

typedef
EFI_STATUS
(EFIAPI *EFI_FILE_FLUSH_EX) (
	IN EFI_FILE_PROTOCOL *This,
	IN OUT EFI_FILE_IO_TOKEN *Token
);

typedef
EFI_STATUS
(EFIAPI *EFI_FILE_SET_POSITION) (
	IN EFI_FILE_PROTOCOL *This,
	IN UINT64 Position
);

typedef
EFI_STATUS
(EFIAPI *EFI_FILE_GET_POSITION) (
	IN EFI_FILE_PROTOCOL *This,
	OUT UINT64 *Position
);

typedef
EFI_STATUS
(EFIAPI *EFI_FILE_GET_INFO) (
	IN EFI_FILE_PROTOCOL *This,
	IN EFI_GUID *InformationType,
	IN OUT UINTN *BufferSize,
	OUT VOID *Buffer
);

typedef
EFI_STATUS
(EFIAPI *EFI_FILE_SET_INFO) (
	IN EFI_FILE_PROTOCOL *This,
	IN EFI_GUID *InformationType,
	IN UINTN BufferSize,
	IN VOID *Buffer
);

typedef
EFI_STATUS
(EFIAPI *EFI_FILE_FLUSH) (
	IN EFI_FILE_PROTOCOL *This
);

typedef struct _EFI_FILE_PROTOCOL {
	UINT64 Revision;
	EFI_FILE_OPEN Open;
	EFI_FILE_CLOSE Close;
	EFI_FILE_DELETE Delete;
	EFI_FILE_READ Read;
	EFI_FILE_WRITE Write;
	EFI_FILE_GET_POSITION GetPosition;
	EFI_FILE_SET_POSITION SetPosition;
	EFI_FILE_GET_INFO GetInfo;
	EFI_FILE_SET_INFO SetInfo;
	EFI_FILE_FLUSH Flush;
	EFI_FILE_OPEN_EX OpenEx;
	EFI_FILE_READ_EX ReadEx;
	EFI_FILE_WRITE_EX WriteEx;
	EFI_FILE_FLUSH_EX FlushEx;
} EFI_FILE_PROTOCOL;

#endif


text:
<?php

namespace Magento\Catalog\Api;

use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\WebapiAbstract;

/**
 * @magentoAppIsolation enabled
 */
class ProductLinkManagementInterfaceTest extends WebapiAbstract
{
    const SERVICE_NAME = 'catalogProductLinkManagementV1';
    const SERVICE_VERSION = 'V1';
    const RESOURCE_PATH = '/V1/products/';

    /**
     * @var \Magento\Framework\ObjectManagerInterface
     */
    protected $objectManager;

    protected function setUp()
    {
        $this->objectManager = Bootstrap::getObjectManager();
    }

    /**
     * @magentoApiDataFixture Magento/Catalog/_files/products_crosssell.php
     */
    public function testGetLinkedProductsCrossSell()
    {
        $productSku = 'simple_with_cross';
        $linkType = 'crosssell';

        $this->assertLinkedProducts($productSku, $linkType);
    }

    /**
     * @magentoApiDataFixture Magento/Catalog/_files/products_related.php
     */
    public function testGetLinkedProductsRelated()
    {
        $productSku = 'simple_with_cross';
        $linkType = 'related';

        $this->assertLinkedProducts($productSku, $linkType);
    }

    /**
     * @magentoApiDataFixture Magento/Catalog/_files/products_upsell.php
     */
    public function testGetLinkedProductsUpSell()
    {
        $productSku = 'simple_with_upsell';
        $linkType = 'upsell';

        $this->assertLinkedProducts($productSku, $linkType);
    }

    /**
     * @param string $productSku
     * @param int $linkType
     */
    protected function assertLinkedProducts($productSku, $linkType)
    {
        $serviceInfo = [
            'rest' => [
                'resourcePath' => self::RESOURCE_PATH . $productSku . '/links/' . $linkType,
                'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
            ],
            'soap' => [
                'service' => self::SERVICE_NAME,
                'serviceVersion' => self::SERVICE_VERSION,
                'operation' => self::SERVICE_NAME . 'GetLinkedItemsByType',
            ],
        ];

        $actual = $this->_webApiCall($serviceInfo, ['sku' => $productSku, 'type' => $linkType]);

        $this->assertEquals('simple', $actual[0]['linked_product_type']);
        $this->assertEquals('simple', $actual[0]['linked_product_sku']);
        $this->assertEquals(1, $actual[0]['position']);
    }

    /**
     * @magentoApiDataFixture Magento/Catalog/_files/products_related.php
     * @magentoApiDataFixture Magento/Catalog/_files/product_virtual_in_stock.php
     */
    public function testAssign()
    {
        $linkType = 'related';
        $productSku = 'simple';
        $linkData = [
            'linked_product_type' => 'virtual',
            'linked_product_sku' => 'virtual-product',
            'position' => 100,
            'sku' => 'simple',
            'link_type' => 'related',
        ];

        $serviceInfo = [
            'rest' => [
                'resourcePath' => self::RESOURCE_PATH . $productSku . '/links',
                'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST,
            ],
            'soap' => [
                'service' => self::SERVICE_NAME,
                'serviceVersion' => self::SERVICE_VERSION,
                'operation' => self::SERVICE_NAME . 'SetProductLinks',
            ],
        ];

        $arguments = [
            'sku' => $productSku,
            'items' => [$linkData],
            'type' => $linkType,
        ];

        $this->_webApiCall($serviceInfo, $arguments);
        $actual = $this->getLinkedProducts($productSku, 'related');
        array_walk($actual, function (&$item) {
            $item = $item->__toArray();
        });
        $this->assertEquals([$linkData], $actual);
    }

    /**
     * Get list of linked products
     *
     * @param string $sku
     * @param string $linkType
     * @return \Magento\Catalog\Api\Data\ProductLinkInterface[]
     */
    protected function getLinkedProducts($sku, $linkType)
    {
        /** @var \Magento\Catalog\Model\ProductLink\Management $linkManagement */
        $linkManagement = $this->objectManager->get('Magento\Catalog\Api\ProductLinkManagementInterface');
        $linkedProducts = $linkManagement->getLinkedItemsByType($sku, $linkType);

        return $linkedProducts;
    }
}


text:
using namespace arangodb;
using namespace arangodb::application_features;

AgencyCallback::AgencyCallback(ArangodServer& server, std::string key,
                               CallbackType cb, bool needsValue,
                               bool needsInitialValue)
    : key(std::move(key)),
      _server(server),
      _cb(std::move(cb)),
      _needsValue(needsValue),
      _needsInitialValue(needsInitialValue) {}

AgencyCallback::AgencyCallback(ArangodServer& server, std::string const& key,
                               std::function<bool(VPackSlice const&)> const& cb,
                               bool needsValue, bool needsInitialValue)
    : AgencyCallback(
          server, key,
          [cb](VPackSlice slice, consensus::index_t) { return cb(slice); },
          needsValue, needsInitialValue) {}

void AgencyCallback::local(bool b) {
  _local = b;
  if (!b) {
    _agency = std::make_unique<AgencyComm>(_server);
  }
}

bool AgencyCallback::local() const { return _local; }

void AgencyCallback::refetchAndUpdate(bool needToAcquireMutex,
                                      bool forceCheck) {
  if (!_needsValue) {
    // no need to pass any value to the callback
    if (needToAcquireMutex) {
      CONDITION_LOCKER(locker, _cv);
      executeEmpty();
    } else {
      executeEmpty();
    }
    return;
  }

  VPackSlice result;
  std::shared_ptr<VPackBuilder> builder;
  consensus::index_t idx = 0;
  AgencyCommResult tmp;

  LOG_TOPIC("a6344", TRACE, Logger::CLUSTER)
      << "Refetching and update for " << AgencyCommHelper::path(key);

  if (_local) {
    auto& _cache = _server.getFeature<ClusterFeature>().agencyCache();
    std::tie(builder, idx) =
        _cache.read(std::vector<std::string>{AgencyCommHelper::path(key)});
    result = builder->slice();
    if (!result.isArray()) {
      if (!_server.isStopping()) {
        // only log errors if we are not already shutting down...
        // in case of shutdown this error is somewhat expected
        LOG_TOPIC("ec320", ERR, arangodb::Logger::CLUSTER)
            << "Callback to get agency cache was not successful: "
            << result.toJson();
      }
      return;
    }
  } else {
    TRI_ASSERT(_agency.get() != nullptr);
    tmp = _agency->getValues(key);
    if (!tmp.successful()) {
      if (!_server.isStopping()) {
        // only log errors if we are not already shutting down...
        // in case of shutdown this error is somewhat expected
        LOG_TOPIC("fb402", ERR, arangodb::Logger::CLUSTER)
            << "Callback getValues to agency was not successful: "
            << tmp.errorCode() << " " << tmp.errorMessage();
      }
      return;
    }
    result = tmp.slice();
  }

  std::vector<std::string> kv =
      basics::StringUtils::split(AgencyCommHelper::path(key), '/');
  kv.erase(std::remove(kv.begin(), kv.end(), ""), kv.end());

  auto newData = std::make_shared<VPackBuilder>();
  newData->add(result[0].get(kv));

  auto const callCheckValue = [&] {
    if (_lastSeenIndex < idx) {
      _lastSeenIndex = idx;
      checkValue(std::move(newData), idx, forceCheck);
    }
  };

  if (needToAcquireMutex) {
    CONDITION_LOCKER(locker, _cv);
    callCheckValue();
  } else {
    callCheckValue();
  }
}

void AgencyCallback::checkValue(std::shared_ptr<VPackBuilder> newData,
                                consensus::index_t raftIndex, bool forceCheck) {
  // Only called from refetchAndUpdate, we always have the mutex when
  // we get here!
  if (!_lastData || forceCheck ||
      !arangodb::basics::VelocyPackHelper::equal(_lastData->slice(),
                                                 newData->slice(), false)) {
    LOG_TOPIC("2bd14", TRACE, Logger::CLUSTER)
        << "AgencyCallback: Got new value " << newData->slice().typeName()
        << " " << newData->toJson() << " forceCheck=" << forceCheck;
    if (execute(newData->slice(), raftIndex)) {
      _lastData = newData;
    } else {
      LOG_TOPIC("337dc", DEBUG, Logger::CLUSTER)
          << "Callback was not successful for " << newData->toJson();
    }
  }
}

bool AgencyCallback::executeEmpty() {
  // only called from refetchAndUpdate, we always have the mutex when
  // we get here! No value is needed, so this is just a notify.
  // No index available in that case.
  return execute(VPackSlice::noneSlice(), 0);
}

bool AgencyCallback::execute(velocypack::Slice newData,
                             consensus::index_t raftIndex) {
  // only called from refetchAndUpdate, we always have the mutex when
  // we get here!
  LOG_TOPIC("add4e", TRACE, Logger::CLUSTER)
      << "Executing" << (newData.isNone() ? " (empty)" : "");
  try {
    bool result = _cb(newData, raftIndex);
    if (result) {
      _wasSignaled = true;
      _cv.signal();
    }
    return result;
  } catch (std::exception const& ex) {
    LOG_TOPIC("1de99", WARN, Logger::CLUSTER)
        << "AgencyCallback execution failed: " << ex.what();
    throw;
  }
}

bool AgencyCallback::executeByCallbackOrTimeout(double maxTimeout) {
  // One needs to acquire the mutex of the condition variable
  // before entering this function!
  if (!_server.isStopping()) {
    if (_wasSignaled) {
      // ok, we have been signaled already, so there is no need to wait at all
      // directly refetch the values
      _wasSignaled = false;
      LOG_TOPIC("67690", DEBUG, Logger::CLUSTER) << "We were signaled already";
      return false;
    }

    // we haven't yet been signaled. so let's wait for a signal or
    // the timeout to occur
    if (!_cv.wait(static_cast<uint64_t>(maxTimeout * 1000000.0))) {
      LOG_TOPIC("1514e", DEBUG, Logger::CLUSTER)
          << "Waiting done and nothing happended. Refetching to be sure";
      // mop: watches have not triggered during our sleep...recheck to be sure
      refetchAndUpdate(false, true);  // Force a check
      return true;
    }
  }
  return false;
}


text:
<?php

namespace app\views;

use app\models\OfficeHoursQueueModel;

class OfficeHoursQueueView extends AbstractView {
    public function showTheQueue($viewer) {
        $this->core->getOutput()->addBreadcrumb("Office Hours Queue");
        $this->core->getOutput()->addInternalCss('officeHoursQueue.css');
        $this->core->getOutput()->addInternalJs('office-hours-queue.js');
        $this->core->getOutput()->addInternalJs('websocket.js');
        $this->core->getOutput()->addInternalJs('notification-sound.js');
        $this->core->getOutput()->enableMobileViewport();

        return $this->renderPart($viewer, "officeHoursQueue/QueueHeader.twig");
    }

    public function renderCurrentQueue($viewer) {
        return $this->renderPart($viewer, "officeHoursQueue/CurrentQueue.twig");
    }

    public function renderQueueHistory($viewer) {
        return $this->renderPart($viewer, "officeHoursQueue/QueueHistory.twig");
    }

    public function renderNewStatus($viewer) {
        return $this->renderPart($viewer, "officeHoursQueue/QueueStatus.twig");
    }

    public function showQueueStats($overallData, $todayData, $weekDayThisWeekData, $weekDayData, $queueData, $weekNumberData): string {
        $this->core->getOutput()->addBreadcrumb("Office Hours/Lab Queue", $this->core->buildCourseUrl(["office_hours_queue"]));
        $this->core->getOutput()->addBreadcrumb("Statistics");
        $this->core->getOutput()->enableMobileViewport();
        return $this->core->getOutput()->renderTwigTemplate('officeHoursQueue/QueueStats.twig', [
          'csrf_token' => $this->core->getCsrfToken(),
          'access_full_grading' => $this->core->getUser()->accessFullGrading(),
          'overall_data' => $overallData,
          'today_data' => $todayData,
          'week_day_this_week_data' => $weekDayThisWeekData,
          'week_day_data' => $weekDayData,
          'queue_data' => $queueData,
          'week_number_data' => $weekNumberData,
          'viewer' => new OfficeHoursQueueModel($this->core),
          'base_url' => $this->core->buildCourseUrl() . '/office_hours_queue'
        ]);
    }

    public function showQueueStudentStats($studentData) {
        $this->core->getOutput()->addBreadcrumb("Office Hours/Lab Queue", $this->core->buildCourseUrl(["office_hours_queue"]));
        $this->core->getOutput()->addBreadcrumb("Statistics");
        $this->core->getOutput()->enableMobileViewport();
        return $this->core->getOutput()->renderTwigTemplate("officeHoursQueue/QueueStatsStudents.twig", [
          'csrf_token' => $this->core->getCsrfToken(),
          'access_full_grading' => $this->core->getUser()->accessFullGrading(),
          'student_data' => $studentData,
          'viewer' => new OfficeHoursQueueModel($this->core),
          'base_url' => $this->core->buildCourseUrl() . '/office_hours_queue'
        ]);
    }

    public function renderNewAnnouncement($viewer) {
        return $this->renderPart($viewer, "officeHoursQueue/AnnouncementMsg.twig");
    }

    private function renderPart($viewer, $twig_location) {
        return $this->core->getOutput()->renderTwigTemplate($twig_location, [
          'csrf_token' => $this->core->getCsrfToken(),
          'access_full_grading' => $this->core->getUser()->accessFullGrading(),
          'viewer' => $viewer,
          'base_url' => $this->core->buildCourseUrl() . '/office_hours_queue'
        ]);
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
org.gradle.language.jvm.tasks
</TITLE>

<META NAME="keywords" CONTENT="org/gradle/language/jvm/tasks package">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

org.gradle.language.jvm.tasks

Classes

ProcessResources


text:
package pageobjects

import (
	. "github.com/onsi/gomega"
	"github.com/sclevine/agouti"
	. "github.com/sclevine/agouti/matchers"
)

type NewJobPage struct {
	page *agouti.Page
}

func NewNewJobPage(page *agouti.Page) *NewJobPage {
	return &NewJobPage{page: page}
}

func (p *NewJobPage) CreateJob(name, cmd, dockerImage, gitRepo string) *ShowBuildPage {
	Expect(p.page.Find("form input#name").Fill(name)).To(Succeed())
	Expect(p.page.Find("form input#command").Fill(cmd)).To(Succeed())
	Expect(p.page.Find("form input#dockerImage").Fill(dockerImage)).To(Succeed())
	Expect(p.page.Find("form input#gitRepo").Fill(gitRepo)).To(Succeed())
	Expect(p.page.Find("form button[type=submit]").Click()).To(Succeed())
	Eventually(p.page.Find("#jobTitle")).Should(HaveText(name))
	return NewShowBuildPage(p.page)
}


text:
#include <sysdep.h>
#include <tls.h>
#ifndef __ASSEMBLER__
# include <nptl/pthreadP.h>
#endif

#if !defined NOT_IN_libc || defined IS_IN_libpthread || defined IS_IN_librt

/* The code to disable cancellation depends on the fact that the called
   functions are special.  They don't modify registers other than %rax
   and %r11 if they return.  Therefore we don't have to preserve other
   registers around these calls.  */
# undef PSEUDO
# define PSEUDO(name, syscall_name, args)				      \
  .text;								      \
  ENTRY (name)								      \
    SINGLE_THREAD_P;							      \
    jne L(pseudo_cancel);						      \
  .type __##syscall_name##_nocancel,@function;				      \
  .globl __##syscall_name##_nocancel;					      \
  __##syscall_name##_nocancel:						      \
    DO_CALL (syscall_name, args);					      \
    cmpq $-4095, %rax;							      \
    jae SYSCALL_ERROR_LABEL;						      \
    ret;								      \
  .size __##syscall_name##_nocancel,.-__##syscall_name##_nocancel;	      \
  L(pseudo_cancel):							      \
    /* We always have to align the stack before calling a function.  */	      \
    subq $8, %rsp; cfi_adjust_cfa_offset (8);				      \
    CENABLE								      \
    /* The return value from CENABLE is argument for CDISABLE.  */	      \
    movq %rax, (%rsp);							      \
    DO_CALL (syscall_name, args);					      \
    movq (%rsp), %rdi;							      \
    /* Save %rax since it's the error code from the syscall.  */	      \
    movq %rax, %rdx;							      \
    CDISABLE								      \
    movq %rdx, %rax;							      \
    addq $8,%rsp; cfi_adjust_cfa_offset (-8);				      \
    cmpq $-4095, %rax;							      \
    jae SYSCALL_ERROR_LABEL;						      \
  L(pseudo_end):

# ifdef IS_IN_libpthread
#  define CENABLE	call __pthread_enable_asynccancel;
#  define CDISABLE	call __pthread_disable_asynccancel;
#  define __local_multiple_threads __pthread_multiple_threads
# elif !defined NOT_IN_libc
#  define CENABLE	call __libc_enable_asynccancel;
#  define CDISABLE	call __libc_disable_asynccancel;
#  define __local_multiple_threads __libc_multiple_threads
# elif defined IS_IN_librt
#  define CENABLE	call __librt_enable_asynccancel;
#  define CDISABLE	call __librt_disable_asynccancel;
# else
#  error Unsupported library
# endif

# if defined IS_IN_libpthread || !defined NOT_IN_libc
#  ifndef __ASSEMBLER__
extern int __local_multiple_threads attribute_hidden;
#   define SINGLE_THREAD_P \
  __builtin_expect (__local_multiple_threads == 0, 1)
#  else
#   define SINGLE_THREAD_P cmpl $0, __local_multiple_threads(%rip)
#  endif

# else

#  ifndef __ASSEMBLER__
#   define SINGLE_THREAD_P \
  __builtin_expect (THREAD_GETMEM (THREAD_SELF, \
				   header.multiple_threads) == 0, 1)
#  else
#   define SINGLE_THREAD_P cmpl $0, %fs:MULTIPLE_THREADS_OFFSET
#  endif

# endif

#elif !defined __ASSEMBLER__

# define SINGLE_THREAD_P (1)
# define NO_CANCELLATION 1

#endif

#ifndef __ASSEMBLER__
# define RTLD_SINGLE_THREAD_P \
  __builtin_expect (THREAD_GETMEM (THREAD_SELF, \
				   header.multiple_threads) == 0, 1)
#endif


text:
package ctci;

/*
 * Implementation of CTCI
 * Link:http://geeksquiz.com/binary-heap/
 */
public class _18Heap{
	//use arrays to implement this
	public static void main(String[] args) {

	}

	static class Heap{
		int capacity,noOfElements=0;
		int heapArray[];
		public Heap(int capacity) {
			this.capacity=capacity;
			heapArray=new int[capacity];
		}
		public void insert(int value){

		}

		public int extractMax(){
			return 0;
		}
		public int delete(){
			return 0;
		}

	}
}


text:
package uaa

import (
	"fmt"
	"net/http"
	"net/http/httputil"

	"github.com/fatih/color"
)

func is2XX(status int) bool {
	if status >= 200 && status < 300 {
		return true
	}
	return false
}

func logResponse(response *http.Response) {
	dumped, _ := httputil.DumpResponse(response, true)

	if is2XX(response.StatusCode) {
		fmt.Println(color.New(color.FgGreen).SprintFunc()(string(dumped)) + "\n")
	} else {
		fmt.Println(color.New(color.FgRed).SprintFunc()(string(dumped)) + "\n")
	}
}

func logRequest(request *http.Request) {
	dumped, _ := httputil.DumpRequest(request, true)
	fmt.Println(string(dumped))
}


text:
@import XCTest;

@interface XCTestCase (TestCaseName)

@property (nonatomic, nonnull, readonly) NSString *testCaseName;

@end


text:
using Lib_K_Relay.Networking.Packets.DataObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FameBot.Data.Models
{
    public class Portal
    {
        public int ObjectId { get; set; }
        public int PlayerCount { get; set; }
        public string Name { get; set; }
        public Location Location { get; set; }
        public bool Connected { get; set; }

        public Portal(int objectId, int playerCount, string name, Location location)
        {
            ObjectId = objectId;
            PlayerCount = playerCount;
            Name = name;
            Location = location;
        }
    }
}


text:
#pragma once

#include <codecvt>
#include <iostream>
#include <locale>
#include <string>
#include <unordered_map>
#include <vector>

namespace paddle {
namespace framework {

using String = std::string;
using Strings = std::vector<std::string>;
using Vocab = std::unordered_map<std::wstring, std::int32_t>;

// Convert the std::string type to the std::string type.
bool ConvertStrToWstr(const std::string& src, std::wstring* res);
// Convert the std::wstring type to the std::string type.
void ConvertWstrToStr(const std::wstring& src, std::string* res);
// Normalization Form Canonical Decomposition.
void NFD(const std::string& s, std::string* ret);

// Write the data which is type of
// std::unordered_map<td::string, int32_t> to ostream.
void StringMapToStream(std::ostream& os,
                       const std::unordered_map<std::string, int32_t>& data);

// Read the data which is type of
// std::unordered_map<td::string, int32_t> from istream.
void StringMapFromStream(std::istream& is,
                         std::unordered_map<std::string, int32_t>* data);
}  // namespace framework
}  // namespace paddle


text:
JBRIDGE_OPTIONS = {:classpath =>  CLASS_PATH.join(":")}

require 'yajb/jbridge'
require 'yajb/jlambda'

include JavaBridge

module YajbInterface
  def self.included(klass)
    klass.class_eval do

      def j_import(klass_name)
        jimport klass_name
      end

      def j_new(klass_name, package = nil, params = nil)
        if params
          jnew klass_name.to_sym, params
        else
          jnew klass_name.to_sym
        end
      end

      def j_class(klass_name, package = nil)
              klass_name.to_sym.jclass
      end

    end
  end
end


text:
module StrongerParameters
  class InvalidValue
    attr_reader :value, :message

    def initialize(value, message)
      @value = value
      @message = message
    end
  end

  class InvalidParameter < StandardError
    attr_reader :key, :value

    def initialize(invalid_value, key)
      @value = invalid_value.value
      @key = key
      super("Invalid parameter: #{@key} #{invalid_value.message}")
    end
  end
end