text:
package by.vorokhobko.models;

import javax.persistence.*;

/**
 * Year.
 *
 * Class Year create element in area car sales part 010, lesson 2.
 * @author Evgeny Vorokhobko (vorokhobko2011@yandex.ru).
 * @since 14.10.2018.
 * @version 1.
 */
@Entity
@Table(name = "year")
public class Year {
    /**
     * The class field.
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;
    /**
     * The class field.
     */
    @Column(name = "releaseYear")
    private int releaseYear;
    /**
     * Add constructor.
     */
    public Year() {}
    /**
     * Add constructor.
     */
    public Year(int id) {
        this.id = id;
    }
    /**
     * Add getter getId.
     * @return tag.
     */
    public int getId() {
        return id;
    }
    /**
     * Add setter setId.
     * @param id - id.
     */
    public void setId(int id) {
        this.id = id;
    }
    /**
     * Add getter getReleaseYear.
     * @return tag.
     */
    public int getReleaseYear() {
        return releaseYear;
    }
    /**
     * Add setter setReleaseYear.
     * @param releaseYear - releaseYear.
     */
    public void setReleaseYear(int releaseYear) {
        this.releaseYear = releaseYear;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.microsoft.azure.management.logic.v2016_06_01.implementation;

import retrofit2.Retrofit;
import com.google.common.reflect.TypeToken;
import com.microsoft.azure.CloudException;
import com.microsoft.rest.ServiceCallback;
import com.microsoft.rest.ServiceFuture;
import com.microsoft.rest.ServiceResponse;
import java.io.IOException;
import okhttp3.ResponseBody;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.Response;
import rx.functions.Func1;
import rx.Observable;

/**
 * An instance of this class provides access to all the operations defined
 * in WorkflowRunOperations.
 */
public class WorkflowRunOperationsInner {
    /** The Retrofit service to perform REST calls. */
    private WorkflowRunOperationsService service;
    /** The service client containing this operation class. */
    private LogicManagementClientImpl client;

    /**
     * Initializes an instance of WorkflowRunOperationsInner.
     *
     * @param retrofit the Retrofit instance built from a Retrofit Builder.
     * @param client the instance of the service client containing this operation class.
     */
    public WorkflowRunOperationsInner(Retrofit retrofit, LogicManagementClientImpl client) {
        this.service = retrofit.create(WorkflowRunOperationsService.class);
        this.client = client;
    }

    /**
     * The interface defining all the services for WorkflowRunOperations to be
     * used by Retrofit to perform actually REST calls.
     */
    interface WorkflowRunOperationsService {
        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.logic.v2016_06_01.WorkflowRunOperations get" })
        @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/workflows/{workflowName}/runs/{runName}/operations/{operationId}")
        Observable<Response<ResponseBody>> get(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("workflowName") String workflowName, @Path("runName") String runName, @Path("operationId") String operationId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);

    }

    /**
     * Gets an operation for a run.
     *
     * @param resourceGroupName The resource group name.
     * @param workflowName The workflow name.
     * @param runName The workflow run name.
     * @param operationId The workflow operation id.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws CloudException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     * @return the WorkflowRunInner object if successful.
     */
    public WorkflowRunInner get(String resourceGroupName, String workflowName, String runName, String operationId) {
        return getWithServiceResponseAsync(resourceGroupName, workflowName, runName, operationId).toBlocking().single().body();
    }

    /**
     * Gets an operation for a run.
     *
     * @param resourceGroupName The resource group name.
     * @param workflowName The workflow name.
     * @param runName The workflow run name.
     * @param operationId The workflow operation id.
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<WorkflowRunInner> getAsync(String resourceGroupName, String workflowName, String runName, String operationId, final ServiceCallback<WorkflowRunInner> serviceCallback) {
        return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, workflowName, runName, operationId), serviceCallback);
    }

    /**
     * Gets an operation for a run.
     *
     * @param resourceGroupName The resource group name.
     * @param workflowName The workflow name.
     * @param runName The workflow run name.
     * @param operationId The workflow operation id.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the WorkflowRunInner object
     */
    public Observable<WorkflowRunInner> getAsync(String resourceGroupName, String workflowName, String runName, String operationId) {
        return getWithServiceResponseAsync(resourceGroupName, workflowName, runName, operationId).map(new Func1<ServiceResponse<WorkflowRunInner>, WorkflowRunInner>() {
            @Override
            public WorkflowRunInner call(ServiceResponse<WorkflowRunInner> response) {
                return response.body();
            }
        });
    }

    /**
     * Gets an operation for a run.
     *
     * @param resourceGroupName The resource group name.
     * @param workflowName The workflow name.
     * @param runName The workflow run name.
     * @param operationId The workflow operation id.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the WorkflowRunInner object
     */
    public Observable<ServiceResponse<WorkflowRunInner>> getWithServiceResponseAsync(String resourceGroupName, String workflowName, String runName, String operationId) {
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (workflowName == null) {
            throw new IllegalArgumentException("Parameter workflowName is required and cannot be null.");
        }
        if (runName == null) {
            throw new IllegalArgumentException("Parameter runName is required and cannot be null.");
        }
        if (operationId == null) {
            throw new IllegalArgumentException("Parameter operationId is required and cannot be null.");
        }
        if (this.client.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
        }
        return service.get(this.client.subscriptionId(), resourceGroupName, workflowName, runName, operationId, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<WorkflowRunInner>>>() {
                @Override
                public Observable<ServiceResponse<WorkflowRunInner>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<WorkflowRunInner> clientResponse = getDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

    private ServiceResponse<WorkflowRunInner> getDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
        return this.client.restClient().responseBuilderFactory().<WorkflowRunInner, CloudException>newInstance(this.client.serializerAdapter())
                .register(200, new TypeToken<WorkflowRunInner>() { }.getType())
                .registerError(CloudException.class)
                .build(response);
    }

}


text:
<?php

namespace Line;

use Line\LineCurlClient;
use Thrift\Transport\TSocket;
use Thrift\Transport\TBufferedTransport;
use Thrift\Protocol\TCompactProtocol;
use Line\TalkServiceClient;
use Line\Types;
use Thrift\Exception\TException;

class LineApiException extends \Exception {

}

class LineApi {

	protected $socket;
	protected $trasport;
	protected $protocol;
	protected $client;
	protected $auth_query_path = '/api/v4/TalkService.do';
	protected $http_query_path = '/S4';
	protected $wait_for_mobile_path = '/Q';
	protected $host = 'gd2.line.naver.jp';
	protected $port = 443;

	public function __construct() {
		$this->socket = new LineCurlClient($this->host, $this->port, $this->auth_query_path, 'https');
//		$this->socket = new LineCurlClient($host, $port, $http_query_path, 'http');
		$this->transport = new TBufferedTransport($this->socket, 1024, 1024);
		$this->protocol = new TCompactProtocol($this->transport);
		$this->client = new TalkServiceClient($this->protocol);
		$this->transport->open();
		$this->transport->close();
	}

	public function open() {
		$this->trasport->open();
	}

	public function close() {
		$this->trasport->close();
	}

	protected function loginWithIdentityCredentialForCertificate($email, $password) {

		$identityProvider = IdentityProvider::LINE;
		$identifier = $email;
		$password = $password;
		$keepLoggedIn = true;
		$accessLocation = "127.0.0.1";
		$systemName = 'systemName';
		$certificate = '';

		return $this->client->loginWithIdentityCredentialForCertificate(
				$identityProvider
				, $identifier
				, $password
				, $keepLoggedIn
				, $accessLocation
				, $systemName
				, $certificate
		);
	}

	protected function getAuthToken() {
		$secret = json_decode(file_get_contents(__DIR__ . '/../../secret.json'), true);
		if (isset($secret['authToken']) && $secret['authToken'] != '') {
			return $secret['authToken'];
		} else {
			return $this->loginWithIdentityCredentialForCertificate($secret['email'], $secret['password']);
		}
	}

	public function login($email, $password) {

		return $this->getAuthToken();
		//after pincode currect
		//loginWithVerifierForCertificate($verifier);
	}

}


text:
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using NLog;
using OuiGui.Lib.Model;
using OuiGui.Lib.Services;
using OuiGui.WPF.Util;
using OuiGui.WPF.ViewModels.Messages;
using System.Collections.ObjectModel;

namespace OuiGui.WPF.ViewModels
{
    public class PackageDetailsViewModel : ViewModelBase
    {
        #region Private Data Members

        private static readonly Logger log = LogManager.GetCurrentClassLogger();
        private readonly Package package;
        private readonly ObservableCollection<PackageVersion> versionHistory = new ObservableCollection<PackageVersion>();
        private readonly IPackageService packageService;
        private readonly IMessenger messenger;
        private bool versionHistoryLoading = false;

        #endregion

        #region Public Constructor Definition

        public PackageDetailsViewModel(Package package, IPackageService packageService, IMessenger messenger)
        {
            this.package = package;
            this.packageService = packageService;
            this.messenger = messenger;

            this.InstallCommand = new RelayCommand(() =>
            {
                log.Trace("Install Command invoked");

                log.Trace("Sending Install request to Install Action ViewModel");
                this.messenger.Send(new InstallAction(this.Package, InstallActionType.Install));
            }, () => !this.package.IsInstalled && !this.package.IsInstallPending);

            this.UpdateCommand = new RelayCommand(() =>
            {
                log.Trace("Update Command invoked");

                log.Trace("Sending update request to Install Action ViewModel");
                this.messenger.Send(new InstallAction(this.Package, InstallActionType.Update));
            }, () => this.package.IsInstalled && !this.package.IsInstallPending && !this.Package.InstalledVersion.Equals(this.Package.Version));

            this.UninstallCommand = new RelayCommand(() =>
            {
                log.Trace("Uninstall Command invoked");

                log.Trace("Sending uninstall request to Install Action ViewModel");
                this.messenger.Send(new InstallAction(this.Package, InstallActionType.Uninstall));
            }, () => !this.package.IsInstallPending && this.package.IsInstalled && !this.package.Title.Equals("chocolatey", System.StringComparison.CurrentCultureIgnoreCase));

            this.InstallVersionCommand = new RelayCommand<PackageVersion>(p =>
            {
                log.Trace("Install Version Command invoked ({0} v{1})", p.Title, p.Version);

                log.Trace("Sending install request to Install Action ViewModel");
                this.messenger.Send(new InstallAction(p, InstallActionType.Install));
            }, p => p != null && !p.IsInstalled && !p.IsInstallPending);

            this.UninstallVersionCommand = new RelayCommand<PackageVersion>(p =>
            {
                log.Trace("Uninstall Version Command invoked ({0} v{1})", p.Title, p.Version);

                log.Trace("Sending uninstall request to Install Action ViewModel");
                this.messenger.Send(new InstallAction(p, InstallActionType.Uninstall));
            }, p => p != null && p.IsInstalled && !p.IsInstallPending && !p.Title.Equals("chocolatey", System.StringComparison.CurrentCultureIgnoreCase));

            this.SearchCommand = new RelayCommand<string>(s =>
            {
                log.Trace("Search Command issued for string: {0}", s);
                this.messenger.Send(new SearchMessage(s));
            }, s => !string.IsNullOrWhiteSpace(s));

            this.LoadVersionHistory();
        }

        #endregion

        #region Command Declarations

        public RelayCommand InstallCommand { get; private set; }

        public RelayCommand UpdateCommand { get; private set; }

        public RelayCommand UninstallCommand { get; private set; }

        public RelayCommand LoadCommand { get; private set; }

        public RelayCommand<PackageVersion> InstallVersionCommand { get; private set; }

        public RelayCommand<PackageVersion> UninstallVersionCommand { get; private set; }

        public RelayCommand<string> SearchCommand { get; private set; }

        #endregion

        #region Public Property Definitions

        public Package Package
        {
            get { return this.package; }
        }

        public ObservableCollection<PackageVersion> VersionHistory
        {
            get { return this.versionHistory; }
        }

        public bool VersionHistoryLoading
        {
            get { return this.versionHistoryLoading; }
            set
            {
                if (this.versionHistoryLoading != value)
                {
                    this.versionHistoryLoading = value;
                    base.RaisePropertyChanged(() => this.VersionHistoryLoading);
                }
            }
        }

        #endregion

        #region Private Function Definitions

        private async void LoadVersionHistory()
        {
            this.VersionHistoryLoading = true;

            log.Trace("Loading version history for package {0}", string.IsNullOrWhiteSpace(this.package.Title) ? "<Untitled Package>" : this.package.Title);
            var versions = await this.packageService.GetVersionHistory(this.package);

            log.Trace("Clearing current version history");
            this.versionHistory.Clear();

            if (versions != null)
            {
                log.Trace("Adding version history to collection");
                foreach (var version in versions)
                    this.versionHistory.Add(version);
            }

            log.Trace("Version history loaded successfully");
            this.VersionHistoryLoading = false;
        }

        #endregion
    }
}


text:
<?php

class Google_Service_Sheets_DeleteFilterViewRequest extends Google_Model
{
  public $filterId;

  public function setFilterId($filterId)
  {
    $this->filterId = $filterId;
  }
  public function getFilterId()
  {
    return $this->filterId;
  }
}


text:
require "pathname"
require "json"

module ActionText
  module Generators
    class InstallGenerator < ::Rails::Generators::Base
      source_root File.expand_path("templates", __dir__)

      def install_javascript_dependencies
        rails_command "app:binstub:yarn", inline: true

        say "Installing JavaScript dependencies", :green
        run "bin/yarn add #{js_dependencies.map { |name, version| "#{name}@#{version}" }.join(" ")}",
          abort_on_failure: true, capture: true
      end

      def append_dependencies_to_package_file
        if (app_javascript_pack_path = Pathname.new("app/javascript/packs/application.js")).exist?
          js_dependencies.each_key do |dependency|
            line = %[require("#{dependency}")]

            unless app_javascript_pack_path.read.include? line
              say "Adding #{dependency} to #{app_javascript_pack_path}", :green
              append_to_file app_javascript_pack_path, "\n#{line}"
            end
          end
        else
          say <<~WARNING, :red
            WARNING: Action Text can't locate your JavaScript bundle to add its package dependencies.

            Add these lines to any bundles:

            require("trix")
            require("@rails/actiontext")

            Alternatively, install and setup the webpacker gem then rerun `bin/rails action_text:install`
            to have these dependencies added automatically.
          WARNING
        end
      end

      def create_actiontext_files
        template "actiontext.scss", "app/assets/stylesheets/actiontext.scss"

        copy_file "#{GEM_ROOT}/app/views/active_storage/blobs/_blob.html.erb",
          "app/views/active_storage/blobs/_blob.html.erb"
      end

      def create_migrations
        rails_command "railties:install:migrations FROM=active_storage,action_text", inline: true
      end

      hook_for :test_framework

      private
        GEM_ROOT = "#{__dir__}/../../../.."

        def js_dependencies
          js_package = JSON.load(Pathname.new("#{GEM_ROOT}/package.json"))
          js_package["peerDependencies"].merge \
            js_package["name"] => "^#{js_package["version"]}"
        end
    end
  end
end


text:
var mongoModel = require("./mongoModel.js");

exports.init = function(app)
{
    app.get("/classes/create", isLoggedIn, function(request, response)
    {
        response.render("classes/create", { navData: {breadcrumb: [["Classes", "/profile"]],
                                                           currentPage: "Create"}});
    });

    app.post("/classes/create", isLoggedIn, createClass);

    app.get("/classes/:className", isLoggedIn, oneClass);
    app.get("/classes/:className/train", isLoggedIn, training)
}

getUsersClasses = function(email, response)
{
    mongoModel.retrieve("classes",
    {creator: email},
    function(classes)
    {
        response.render('users/profile', { currentUser : email,
                                           classes : classes,
                                           navData: {breadcrumb: [["Profile", "#!"]],
                                                           currentPage: email} });
    })
}

createClass = function(request, response)
{
    mongoModel.create("classes",
    { creator: request.user.local.email, className: request.body.classname },
    function(modelData)
    {
        getUsersClasses(request.user.local.email, response);
    });
}

oneClass = function(request, response)
{
    query = {
        creator : request.user.local.email,
        className : request.params.className
    }

    mongoModel.retrieve("enrollments",
        {className: request.params.className},
        function(enrollments)
        {
            mongoModel.retrieve("classes",
            query,
            function(classes)
            {
                response.render('classes/one', { classData : classes[0],
                                                 enrollments: enrollments,
                                                 navData: {breadcrumb: [["Classes", "/profile"]],
                                                           currentPage: request.params.className}
                                                });
            });
        }
    );
}

training = function(request, response)
{
    response.render("classes/train", {navData: {breadcrumb: [["Classes", "/profile"], [request.params.className, "/classes/" + request.params.className]],
                                                           currentPage: "Train"}})
}

function isLoggedIn(req, res, next)
{

    // if user is authenticated in the session, carry on
    if (req.isAuthenticated())
        return next();

    // if they aren't redirect them to the home page
    res.redirect('/');
}


text:
function Preview(container){
    this.div = jQuery('<div>').appendTo(container)
        .css('min-height', '400px')
        .hide();
};

module.exports = Preview;


text:
namespace pythonic
{

  namespace operator_
  {

    template <class A, class B>
    A ipow(A a, B const &b);

    DECLARE_FUNCTOR(pythonic::operator_, ipow);
  }
}

#endif


text:
namespace sandbox {

namespace {

bool IsRunningOnValgrind() { return RUNNING_ON_VALGRIND; }

// Checks that the set of RES-uids and the set of RES-gids have
// one element each and return that element in |resuid| and |resgid|
// respectively. It's ok to pass NULL as one or both of the ids.
bool GetRESIds(uid_t* resuid, gid_t* resgid) {
  uid_t ruid, euid, suid;
  gid_t rgid, egid, sgid;
  PCHECK(sys_getresuid(&ruid, &euid, &suid) == 0);
  PCHECK(sys_getresgid(&rgid, &egid, &sgid) == 0);
  const bool uids_are_equal = (ruid == euid) && (ruid == suid);
  const bool gids_are_equal = (rgid == egid) && (rgid == sgid);
  if (!uids_are_equal || !gids_are_equal) return false;
  if (resuid) *resuid = euid;
  if (resgid) *resgid = egid;
  return true;
}

const int kExitSuccess = 0;

int ChrootToSelfFdinfo(void*) {
  RAW_CHECK(sys_chroot("/proc/self/fdinfo/") == 0);

  // CWD is essentially an implicit file descriptor, so be careful to not
  // leave it behind.
  RAW_CHECK(chdir("/") == 0);
  _exit(kExitSuccess);
}

// chroot() to an empty dir that is "safe". To be safe, it must not contain
// any subdirectory (chroot-ing there would allow a chroot escape) and it must
// be impossible to create an empty directory there.
// We achieve this by doing the following:
// 1. We create a new process sharing file system information.
// 2. In the child, we chroot to /proc/self/fdinfo/
// This is already "safe", since fdinfo/ does not contain another directory and
// one cannot create another directory there.
// 3. The process dies
// After (3) happens, the directory is not available anymore in /proc.
bool ChrootToSafeEmptyDir() {
  // We need to chroot to a fdinfo that is unique to a process and have that
  // process die.
  // 1. We don't want to simply fork() because duplicating the page tables is
  // slow with a big address space.
  // 2. We do not use a regular thread (that would unshare CLONE_FILES) because
  // when we are in a PID namespace, we cannot easily get a handle to the
  // /proc/tid directory for the thread (since /proc may not be aware of the
  // PID namespace). With a process, we can just use /proc/self.
  pid_t pid = -1;
  char stack_buf[PTHREAD_STACK_MIN];
#if defined(ARCH_CPU_X86_FAMILY) || defined(ARCH_CPU_ARM_FAMILY) || \
    defined(ARCH_CPU_MIPS64_FAMILY) || defined(ARCH_CPU_MIPS_FAMILY)
  // The stack grows downward.
  void* stack = stack_buf + sizeof(stack_buf);
#else
#error "Unsupported architecture"
#endif
  pid = clone(ChrootToSelfFdinfo, stack,
              CLONE_VM | CLONE_VFORK | CLONE_FS | SIGCHLD, nullptr, nullptr,
              nullptr, nullptr);
  PCHECK(pid != -1);

  int status = -1;
  PCHECK(HANDLE_EINTR(waitpid(pid, &status, 0)) == pid);

  return WIFEXITED(status) && WEXITSTATUS(status) == kExitSuccess;
}

// CHECK() that an attempt to move to a new user namespace raised an expected
// errno.
void CheckCloneNewUserErrno(int error) {
  // EPERM can happen if already in a chroot. EUSERS if too many nested
  // namespaces are used. EINVAL for kernels that don't support the feature.
  // Valgrind will ENOSYS unshare().
  PCHECK(error == EPERM || error == EUSERS || error == EINVAL ||
         error == ENOSYS);
}

// Converts a Capability to the corresponding Linux CAP_XXX value.
int CapabilityToKernelValue(Credentials::Capability cap) {
  switch (cap) {
    case Credentials::Capability::SYS_CHROOT:
      return CAP_SYS_CHROOT;
    case Credentials::Capability::SYS_ADMIN:
      return CAP_SYS_ADMIN;
  }

  LOG(FATAL) << "Invalid Capability: " << static_cast<int>(cap);
  return 0;
}

}  // namespace.

// static
bool Credentials::DropAllCapabilities(int proc_fd) {
  if (!SetCapabilities(proc_fd, std::vector<Capability>())) {
    return false;
  }

  CHECK(!HasAnyCapability());
  return true;
}

// static
bool Credentials::DropAllCapabilities() {
  base::ScopedFD proc_fd(ProcUtil::OpenProc());
  return Credentials::DropAllCapabilities(proc_fd.get());
}

// static
bool Credentials::DropAllCapabilitiesOnCurrentThread() {
  return SetCapabilitiesOnCurrentThread(std::vector<Capability>());
}

// static
bool Credentials::SetCapabilitiesOnCurrentThread(
    const std::vector<Capability>& caps) {
  struct cap_hdr hdr = {};
  hdr.version = _LINUX_CAPABILITY_VERSION_3;
  struct cap_data data[_LINUX_CAPABILITY_U32S_3] = {{}};

  // Initially, cap has no capability flags set. Enable the effective and
  // permitted flags only for the requested capabilities.
  for (const Capability cap : caps) {
    const int cap_num = CapabilityToKernelValue(cap);
    const size_t index = CAP_TO_INDEX(cap_num);
    const uint32_t mask = CAP_TO_MASK(cap_num);
    data[index].effective |= mask;
    data[index].permitted |= mask;
  }

  return sys_capset(&hdr, data) == 0;
}

// static
bool Credentials::SetCapabilities(int proc_fd,
                                  const std::vector<Capability>& caps) {
  DCHECK_LE(0, proc_fd);

#if !defined(THREAD_SANITIZER)
  // With TSAN, accept to break the security model as it is a testing
  // configuration.
  CHECK(ThreadHelpers::IsSingleThreaded(proc_fd));
#endif

  return SetCapabilitiesOnCurrentThread(caps);
}

bool Credentials::HasAnyCapability() {
  struct cap_hdr hdr = {};
  hdr.version = _LINUX_CAPABILITY_VERSION_3;
  struct cap_data data[_LINUX_CAPABILITY_U32S_3] = {{}};

  PCHECK(sys_capget(&hdr, data) == 0);

  for (size_t i = 0; i < arraysize(data); ++i) {
    if (data[i].effective || data[i].permitted || data[i].inheritable) {
      return true;
    }
  }

  return false;
}

bool Credentials::HasCapability(Capability cap) {
  struct cap_hdr hdr = {};
  hdr.version = _LINUX_CAPABILITY_VERSION_3;
  struct cap_data data[_LINUX_CAPABILITY_U32S_3] = {{}};

  PCHECK(sys_capget(&hdr, data) == 0);

  const int cap_num = CapabilityToKernelValue(cap);
  const size_t index = CAP_TO_INDEX(cap_num);
  const uint32_t mask = CAP_TO_MASK(cap_num);

  return (data[index].effective | data[index].permitted |
          data[index].inheritable) &
         mask;
}

// static
bool Credentials::CanCreateProcessInNewUserNS() {
  // Valgrind will let clone(2) pass-through, but doesn't support unshare(),
  // so always consider UserNS unsupported there.
  if (IsRunningOnValgrind()) {
    return false;
  }

#if defined(THREAD_SANITIZER)
  // With TSAN, processes will always have threads running and can never
  // enter a new user namespace with MoveToNewUserNS().
  return false;
#endif

  // This is roughly a fork().
  const pid_t pid = sys_clone(CLONE_NEWUSER | SIGCHLD, 0, 0, 0, 0);

  if (pid == -1) {
    CheckCloneNewUserErrno(errno);
    return false;
  }

  // The parent process could have had threads. In the child, these threads
  // have disappeared. Make sure to not do anything in the child, as this is a
  // fragile execution environment.
  if (pid == 0) {
    _exit(kExitSuccess);
  }

  // Always reap the child.
  int status = -1;
  PCHECK(HANDLE_EINTR(waitpid(pid, &status, 0)) == pid);
  CHECK(WIFEXITED(status));
  CHECK_EQ(kExitSuccess, WEXITSTATUS(status));

  // clone(2) succeeded, we can use CLONE_NEWUSER.
  return true;
}

bool Credentials::MoveToNewUserNS() {
  uid_t uid;
  gid_t gid;
  if (!GetRESIds(&uid, &gid)) {
    // If all the uids (or gids) are not equal to each other, the security
    // model will most likely confuse the caller, abort.
    DVLOG(1) << "uids or gids differ!";
    return false;
  }
  int ret = sys_unshare(CLONE_NEWUSER);
  if (ret) {
    const int unshare_errno = errno;
    VLOG(1) << "Looks like unprivileged CLONE_NEWUSER may not be available "
            << "on this kernel.";
    CheckCloneNewUserErrno(unshare_errno);
    return false;
  }

  if (NamespaceUtils::KernelSupportsDenySetgroups()) {
    PCHECK(NamespaceUtils::DenySetgroups());
  }

  // The current {r,e,s}{u,g}id is now an overflow id (c.f.
  // /proc/sys/kernel/overflowuid). Setup the uid and gid maps.
  DCHECK(GetRESIds(NULL, NULL));
  const char kGidMapFile[] = "/proc/self/gid_map";
  const char kUidMapFile[] = "/proc/self/uid_map";
  PCHECK(NamespaceUtils::WriteToIdMapFile(kGidMapFile, gid));
  PCHECK(NamespaceUtils::WriteToIdMapFile(kUidMapFile, uid));
  DCHECK(GetRESIds(NULL, NULL));
  return true;
}

bool Credentials::DropFileSystemAccess(int proc_fd) {
  CHECK_LE(0, proc_fd);

  CHECK(ChrootToSafeEmptyDir());
  CHECK(!base::DirectoryExists(base::FilePath("/proc")));
  CHECK(!ProcUtil::HasOpenDirectory(proc_fd));
  // We never let this function fail.
  return true;
}

}  // namespace sandbox.


text:
package shapeless
package syntax
package std

import scala.collection.GenTraversable

/**
 * Conversions between `Traversables` and `HLists`.
 *
 * The implicit defined by this object enhances `Traversables` with a `toHList` method which constructs an equivalently
 * typed [[shapeless.HList]] if possible.
 *
 * @author Miles Sabin
 */
object traversable {
  implicit def traversableOps[T <% GenTraversable[_]](t : T) = new TraversableOps(t)
}

final class TraversableOps[T <% GenTraversable[_]](t : T) {
  import ops.traversable._

  def toHList[L <: HList](implicit fl : FromTraversable[L]) : Option[L] = fl(t)
}


text:
!SLIDE

## What is it?

* "open source project to pack, ship and run any application as a lightweight container".

* it works much like a virtual machine, wraps everything (filesystem, process management, environment variables, etc.)
into a container.

* Unlike a VM, it uses LXC (Linux kernel container) instead of a hypervisor.

* LXC doesn't have its own kernel, but shares the Linux kernel with the host and other containers instead. Based on LXC,
Docker is so lightweight, that it introduces almost no performance drawback while running the application.

* provides a smart way to manage your images. Through Dockerfile and its caching mechanism, one can easily redeploy
an updated image without transferring large amounts of data.

## When it make sense to use?

* With VM You have to upload the whole new image even if you just made a small update. With Docker
you don't have to upload the whole image again. Docker is based on AuFS, which tracks the diff of the whole filesystem.

* There is a significant performance loss. With Docker The performance loss is ignorable since it runs on the host kernel.

* Your probably run your application on a VPS, which is already a virtualized environment.
You can't run a VM on top of another. You can run Docker on a VM because Docker is not a VM

## How it works?

* Docker needs to be run with root privilege.

Docker DOESN'T write into the image. Instead, it creates a layer with each Dockerfile line on top of the existing image,
which contains the modifications you made to the filesystem. Migrating from a previous state of filesystem to
a recent one is applying one or more layers on top of the old image, just like patching files.

When a container is stopped, you can commit it. Committing a container is creating an additional layer on top
of the base image. As expected, the official ubuntu image is also made up of several layers.

## What is Boot2Docker?

Boot2Docker is a lightweight Linux distribution made specifically to run Docker containers. It runs
completely from RAM, is a small ~24MB download and boots in ~5s (YMMV).

Installation instructions for OS X and Windows available on the Docker documentation site.

## How to use Boot2Docker

The boot2docker managment tool leverages VirtualBox's VBoxManage to initialise, start, stop and delete
the VM right from the command line.

# Initialize

$ boot2docker init

# Start VM

$ boot2docker up

# Upgrade the Boot2docker VM image

$ boot2docker stop
$ boot2docker download
$ boot2docker up

If your Boot2Docker virtual machine was created prior to 0.11.1-pre1, its best to delete -
boot2docker delete and then boot2docker init to create a new VM.

The main changes are to add a /var/lib/boot2docker/userdata.tar file that is un-tarred
into the /home/docker directory on boot. This file contains a .ssh/authorized_keys and .ssh/authorized_keys2
files containing a public sshkey.

## Installation

* Download and install VirtualBox for OSX

https://www.virtualbox.org/wiki/Downloads

* Install boot2docker and docker via homebrew:

```bash
brew install boot2docker
```
Docker will be installed as an dependency.

Initialize boot2docker virtual machine:

```bash
boot2docker init
```

Update .bash_profile file:

```bash
export DOCKER_HOST=tcp://192.168.59.103:2375
```

Start the docker daemon:

```bash
boot2docker up
```

or down:

```bash
boot2docker down
```

ssh it:

```bash
boot2docker ssh

# User: docker
# Pwd:  tcuser
```

Download the small base image named busybox:

```bash
docker pull busybox
docker pull ubuntu
docker pull centos
```

Run and test as separate command:

```bash
docker run ubuntu /bin/echo hello world
```

and interactively:

```bash
docker run -t -i ubuntu /bin/bash
```

```bash
docker stop $(docker ps -a -q)
docker rm $(docker ps -a -q)

# Build containers from Dockerfiles
docker build -t postgres docker/postgres
docker build -t demo demo

# Run and link the containers
docker run -d -p 5432:5432 --name postgres postgres

docker run --rm -p 42222:22 -p 9292:9292 -e POSTGRESQL_HOST='192.168.59.103' --name demo demo:latest /bin/bash -l -c "rackup"

--link postgres:db

docker run -d -p 9292:9292 --name demo demo:latest /bin/bash -l -c "rackup"
```

```bash
boot2docker ip # 192.168.59.103

open http://192.168.59.103

docker run --rm ubuntu env

docker port demo 22

ssh root@localhost -p 49153

 VBoxManage modifyvm "boot2docker-vm" --natpf1 "containerssh,tcp,,42222,,42222"

```

-d means run in the background

--name xyz gives the container the friendly name xyz which we can use to refer to it later when we want to
stop it or link it to another container

-p 3000:3000 makes port 3000 from the container available as port 3000 on the host (the Virtualbox VM). Since we have Vagrant configured to forward port 3000 of the VM to your local machine 3000, you can access this container on port 3000 on your development machine as you would the normal Rails dev server (e.g. http://localhost:3000).

--link postgres:db establishes a link between the container you're starting (your Rails app) and the
Postgres container you started previously. This is in the format name:alias and will make ports exposed by the
Postgres container available to the Rails container.

!SLIDE

## Links

* Installing Docker on Mac OS X https://docs.docker.com/installation/mac/
* [Docker sources project = *https://github.com/dotcloud/docker*](https://github.com/dotcloud/docker)
* [Deploy Rails Applications Using Docker - *http://steveltn.me/blog/2014/03/15/deploy-rails-applications-using-docker*](http://steveltn.me/blog/2014/03/15/deploy-rails-applications-using-docker)
* [How to Skip Bundle Install When Deploying a Rails App to Docker if the Gemfile Hasn't Changed - *http://ilikestuffblog.com/2014/01/06/how-to-skip-bundle-install-when-deploying-a-rails-app-to-docker*](http://ilikestuffblog.com/2014/01/06/how-to-skip-bundle-install-when-deploying-a-rails-app-to-docker)

http://www.talkingquickly.co.uk/2014/06/rails-development-environment-with-vagrant-and-docker
https://github.com/TalkingQuickly/docker_rails_dev_env/
https://coreos.com/docs/launching-containers/building/getting-started-with-docker
http://docs.docker.io/installation/binaries/#dockergroup
http://blog.gemnasium.com/post/65599561888/rails-meets-docker
https://github.com/gemnasium/rails-meets-docker
https://medium.com/@flawless_retard/a-osx-vagrant-docker-ruby-on-rails-setup-117daf4ef0a5
Docker Cheat Sheet - https://gist.github.com/wsargent/7049221


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.hoonboon</groupId>
	<artifactId>demo-kafkaStream</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>demo-kafkaStream</name>
	<description>Demo project for Kafka Stream</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.2.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>io.confluent</groupId>
			<artifactId>kafka-avro-serializer</artifactId>
			<version>3.2.0</version>
		</dependency>

		<dependency>
			<groupId>org.apache.avro</groupId>
			<artifactId>avro</artifactId>
			<version>1.7.7</version>
		</dependency>

		<dependency>
			<groupId>org.apache.kafka</groupId>
			<artifactId>kafka-clients</artifactId>
			<version>0.10.2.0-cp1</version>
		</dependency>

		<dependency>
			<groupId>org.apache.kafka</groupId>
			<artifactId>kafka-streams</artifactId>
			<version>0.10.2.0-cp1</version>
		</dependency>

	</dependencies>

	<repositories>
		<repository>
			<id>confluent</id>
			<url>http://packages.confluent.io/maven/</url>
		</repository>

	</repositories>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>


text:
package io.github.hidroh.materialistic.data;

import java.io.IOException;

import javax.inject.Inject;
import javax.inject.Named;

import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import io.github.hidroh.materialistic.ActivityModule;
import io.github.hidroh.materialistic.DataModule;
import io.github.hidroh.materialistic.annotation.Synthetic;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
import rx.Observable;
import rx.Scheduler;

public class AlgoliaClient implements ItemManager {

    public static boolean sSortByTime = true;
    public static final String HOST = "hn.algolia.com";
    private static final String BASE_API_URL = "https://" + HOST + "/api/v1/";
    static final String MIN_CREATED_AT = "created_at_i>";
    RestService mRestService;
    @Inject @Named(ActivityModule.HN) ItemManager mHackerNewsClient;
    @Inject @Named(DataModule.MAIN_THREAD) Scheduler mMainThreadScheduler;

    @Inject
    public AlgoliaClient(RestServiceFactory factory) {
        mRestService = factory.rxEnabled(true).create(BASE_API_URL, RestService.class);
    }

    @Override
    public void getStories(String filter, @CacheMode int cacheMode,
                           final ResponseListener<Item[]> listener) {
        if (listener == null) {
            return;
        }
        searchRx(filter)
                .map(this::toItems)
                .observeOn(mMainThreadScheduler)
                .subscribe(listener::onResponse,
                        t -> listener.onError(t != null ? t.getMessage() : ""));
    }

    @Override
    public void getItem(String itemId, @CacheMode int cacheMode, ResponseListener<Item> listener) {
        mHackerNewsClient.getItem(itemId, cacheMode, listener);
    }

    @Override
    public Item[] getStories(String filter, @CacheMode int cacheMode) {
        try {
            return toItems(search(filter).execute().body());
        } catch (IOException e) {
            return new Item[0];
        }
    }

    @Override
    public Item getItem(String itemId, @CacheMode int cacheMode) {
        return mHackerNewsClient.getItem(itemId, cacheMode);
    }

    protected Observable<AlgoliaHits> searchRx(String filter) {
        // TODO add ETag header
        return sSortByTime ? mRestService.searchByDateRx(filter) : mRestService.searchRx(filter);
    }

    protected Call<AlgoliaHits> search(String filter) {
        return sSortByTime ? mRestService.searchByDate(filter) : mRestService.search(filter);
    }

    @NonNull
    private Item[] toItems(AlgoliaHits algoliaHits) {
        if (algoliaHits == null) {
            return new Item[0];
        }
        Hit[] hits = algoliaHits.hits;
        Item[] stories = new Item[hits == null ? 0 : hits.length];
        for (int i = 0; i < stories.length; i++) {
            //noinspection ConstantConditions
            HackerNewsItem item = new HackerNewsItem(
                    Long.parseLong(hits[i].objectID));
            item.rank = i + 1;
            stories[i] = item;
        }
        return stories;
    }

    interface RestService {
        @GET("search_by_date?hitsPerPage=100&tags=story&attributesToRetrieve=objectID&attributesToHighlight=none")
        Observable<AlgoliaHits> searchByDateRx(@Query("query") String query);

        @GET("search?hitsPerPage=100&tags=story&attributesToRetrieve=objectID&attributesToHighlight=none")
        Observable<AlgoliaHits> searchRx(@Query("query") String query);

        @GET("search?hitsPerPage=100&tags=story&attributesToRetrieve=objectID&attributesToHighlight=none")
        Observable<AlgoliaHits> searchByMinTimestampRx(@Query("numericFilters") String timestampSeconds);

        @GET("search_by_date?hitsPerPage=100&tags=story&attributesToRetrieve=objectID&attributesToHighlight=none")
        Call<AlgoliaHits> searchByDate(@Query("query") String query);

        @GET("search?hitsPerPage=100&tags=story&attributesToRetrieve=objectID&attributesToHighlight=none")
        Call<AlgoliaHits> search(@Query("query") String query);

        @GET("search?hitsPerPage=100&tags=story&attributesToRetrieve=objectID&attributesToHighlight=none")
        Call<AlgoliaHits> searchByMinTimestamp(@Query("numericFilters") String timestampSeconds);
    }

    static class AlgoliaHits {
        @Keep @Synthetic
        Hit[] hits;
    }

    static class Hit {
        @Keep @Synthetic
        String objectID;
    }
}


text:
import d from 'debug'
import utils from 'mongo-utils'
import url from 'url'
import path from 'path'
let p = url.parse
let debug = d('db')
let { MONGOHQ_URL, COPY_MONGO_URL } = process.env

utils.log = debug
let tmpDir = path.resolve(__dirname, '../../', 'tmp')

debug(`copying ${p(COPY_MONGO_URL).hostname} to ${p(MONGOHQ_URL).hostname}...`)
utils.dumpDatabase(COPY_MONGO_URL, tmpDir, (err, stdout, stderr) => {
  if (err || stderr) return debug(err || stderr)
  debug('finished dump, restoring...')
  utils.restoreDatabase(MONGOHQ_URL, tmpDir, (err, stdout, stderr) => {
    if (err || stderr) return debug(err || stderr)
    debug('finished!')
  }).stdout.on('data', debug)
}).stdout.on('data', debug)


text:
import sys

from pyasn1.codec.der.decoder import decode as der_decode
from pyasn1.codec.der.encoder import encode as der_encode

from pyasn1_modules import pem
from pyasn1_modules import rfc5915
from pyasn1_modules import rfc5480

try:
    import unittest2 as unittest
except ImportError:
    import unittest

class MUDCertTestCase(unittest.TestCase):
    private_key_pem_text = """\
MIGkAgEBBDDLjzGbbLrR3T13lrrVum7WC/4Ua4Femc1RhhNVe1Q5XsArQ33kn9kx
3lOUfOcG+qagBwYFK4EEACKhZANiAAT4zZ8HL+xEDpXWkoWp5xFMTz4u4Ae1nF6z
XCYlmsEGD5vPu5hl9hDEjd1UHRgJIPoy3fJcWWeZ8FHCirICtuMgFisNscG/aTwK
yDYOFDuqz/C2jyEwqgWCRyxyohuJXtk=
"""

    def setUp(self):
        self.asn1Spec = rfc5915.ECPrivateKey()

    def testDerCodec(self):
        substrate = pem.readBase64fromText(self.private_key_pem_text)
        asn1Object, rest = der_decode(substrate, asn1Spec=self.asn1Spec)
        assert not rest
        assert asn1Object.prettyPrint()
        assert der_encode(asn1Object) == substrate

        assert asn1Object['parameters']['namedCurve'] == rfc5480.secp384r1

suite = unittest.TestLoader().loadTestsFromModule(sys.modules[__name__])

if __name__ == '__main__':
    import sys

    result = unittest.TextTestRunner(verbosity=2).run(suite)
    sys.exit(not result.wasSuccessful())


text:
require "xcodeproj"

class Refactor
  class Project < Xcodeproj::Project
    #
    # This is the main entry point for *refactor*, which is a subclass of Xcodeproj::Project
    # When parse is called on an instance of this type, we fetch all swift files that are
    # part of the project and start searching for parsing "tokens".
    # When tokens are found the enclosing text is collecting and assigned a filename (and) path
    #
    # Each result is encapsulated into a Parser::Result object
    # The parse method uses those results to create each new file and inject
    # the parsed text into them
    #
    # Once all files are successfully created, we use Xcodeproj native functionality to insert
    # them into the appropriate groups within the project, and finally save the resulting project
    #
    def parse
      swift_files.each do |f|
        original_filepath = f.real_path
        results, modified_text = parse_file(original_filepath)
        next unless results && results.count > 0
        target = find_target_for_file(f)
        original_file_dir = File.dirname(original_filepath)
        # Create new files starting from the original file folder and appending the
        # relative filename specified in the each of the results array
        new_files = create_new_files(original_file_dir, results)
        # Update and save the xcodeproj with the new files and their respective groups
        new_files.each { |nf| update_with(nf, target) }
        # Once all the new files have been created, we need to remove the parsed text
        # from the original file
        FileUtil.create(original_filepath, modified_text, overwrite = true)
        # And finally save
        save
      end
    end

    # Filter all project files by extension and reject anything that doesn't end with .swift
    def swift_files
      files.reject { |f| f.path.end_with?(".swift") == false }
    end

    private

    def find_target_for_file(file)
      targets.each do |t|
        match = t.source_build_phase.files.any? \
          { |bf| bf.file_ref.real_path == file.real_path }
        return t if match == true
      end
    end

    def update_with(new_file, target)
      pathname = Pathname(new_file).expand_path
      xcpath = self.path.split.first
      unless pathname.is_underneath?(xcpath)
        puts "#{pathname} is outside of the project folder hierarchy, skipping...".red
        return
      end
      f_split = pathname.split
      filename = f_split.last
      base = f_split.first
      relative_path_components = []
      while xcpath != base
        relative_path_components.unshift(base.split.last.to_s)
        base = base.split.first
      end
      file_group = self.main_group
      relative_path_components.each do |p|
        unless new_file_group = file_group[p]
          new_file_group = file_group.new_group(p)
        end
        file_group = new_file_group
      end
      file_ref = file_group.new_file(pathname)
      file_ref.source_tree = "<group>"
      unless target.resources_build_phase.files_references.include?(file_ref)
        target.add_resources([file_ref])
      end
    end

    def create_new_files(dir, parser_results)
      files = []
      parser_results.each do |p|
        filename = p.name
        contents = p.lines
        file_path = Pathname(File.join(dir, filename)).expand_path
        unless is_underneath_project_path?(file_path)
          puts "#{file_path} is outside of the project folder hierarchy, skipping...".red
          next
        end
        puts "Creating new file: #{file_path}".yellow
        FileUtil.create(file_path, contents)
        files << file_path
      end
      files
    end

    def parse_file(file)
      return unless text = File.readlines(file).join
      Parser.process(text)
    end

    def is_underneath_project_path?(pathname)
      pathname.is_underneath?(self.path.dirname)
    end

  end
end


text:
 [](#skip-navbar_top "Skip navigation links")

<colgroup>
<col width="50%" />
<col width="50%" />
</colgroup>

Overview
Package
 Class
Use
Tree
Deprecated
Index
Help

 PREV CLASS   NEXT CLASS
FRAMES    NO FRAMES
All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

------------------------------------------------------------------------

org.apache.struts.webapp.example
 Class LinkSubscriptionTag
--------------------------------

    java.lang.Object
      javax.faces.webapp.UIComponentTag
          org.apache.struts.webapp.example.LinkSubscriptionTag

**All Implemented Interfaces:**
[Tag](http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/jsp/tagext/Tag.html.md?is-external=true "class or interface in javax.servlet.jsp.tagext")

------------------------------------------------------------------------

    public class LinkSubscriptionTag

extends javax.faces.webapp.UIComponentTag

Generate a URL-encoded hyperlink to the specified URI, with associated query parameters selecting a specified Subscription.

**Version:**
$Rev: 471754 $ $Date: 2006-11-06 08:55:09 -0600 (Mon, 06 Nov 2006) $

**Author:**
Craig R. McClanahan

------------------------------------------------------------------------

**Field Summary**

`protected  String`

` name`
           The attribute name.

`protected  String`

` page`
           The context-relative URI.

| **Fields inherited from class javax.faces.webapp.UIComponentTag** |
|-------------------------------------------------------------------|
| `pageContext`                                                     |

| **Fields inherited from interface javax.servlet.jsp.tagext.[Tag](http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/jsp/tagext/Tag.html.md?is-external=true "class or interface in javax.servlet.jsp.tagext")** |
|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `EVAL_BODY_INCLUDE, EVAL_PAGE, SKIP_BODY, SKIP_PAGE`                                                                                |

| **Constructor Summary**  |
|--------------------------|
| ` LinkSubscriptionTag()`
                           |

**Method Summary**

` String`

` getComponentType()`
           Return the component type for this tag.

` String`

` getRendererType()`
           Return the renderer type associated with this tag.

` void`

` release()`
           Release resources allocated to this tag instance.

` void`

` setName(String name)`

` void`

` setPage(String page)`

`protected  void`

` setProperties(javax.faces.component.UIComponent component)`
           Override attributes set on this tag instance.

| **Methods inherited from class javax.faces.webapp.UIComponentTag**                                                                                |
|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `doEndTag, doStartTag, encodeBegin, encodeChildren, encodeEnd, findComponent, getComponentInstance, getCreated, getDoEndValue, getDoStartValue, getFacesContext, getFacetName, getId, getParent, getParentUIComponentTag, getPathToComponent, isSuppressed, isValueReference, setBinding, setId, setPageContext, setParent, setRendered, setupResponseWriter` |

| **Methods inherited from class java.lang.[Object](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html.md?is-external=true "class or interface in java.lang")** |
|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`                                                                          |

**Field Detail**

### name

    protected String name

The attribute name.

------------------------------------------------------------------------

### page

    protected String page

The context-relative URI.

**Constructor Detail**

### LinkSubscriptionTag

    public LinkSubscriptionTag()

**Method Detail**

### setName

    public void setName(String name)

------------------------------------------------------------------------

### setPage

    public void setPage(String page)

------------------------------------------------------------------------

### getComponentType

    public String getComponentType()

Return the component type for this tag.

**Specified by:**
`getComponentType` in class `javax.faces.webapp.UIComponentTag`

------------------------------------------------------------------------

### getRendererType

    public String getRendererType()

Return the renderer type associated with this tag.

**Specified by:**
`getRendererType` in class `javax.faces.webapp.UIComponentTag`

------------------------------------------------------------------------

### release

    public void release()

Release resources allocated to this tag instance.

**Specified by:**
`release` in interface `Tag`

**Overrides:**
`release` in class `javax.faces.webapp.UIComponentTag`

------------------------------------------------------------------------

### setProperties

    protected void setProperties(javax.faces.component.UIComponent component)

Override attributes set on this tag instance.

**Overrides:**
`setProperties` in class `javax.faces.webapp.UIComponentTag`

**Parameters:**
`component` - Component whose attributes should be overridden

------------------------------------------------------------------------

 [](#skip-navbar_bottom "Skip navigation links")

<colgroup>
<col width="50%" />
<col width="50%" />
</colgroup>

Overview
Package
 Class
Use
Tree
Deprecated
Index
Help

 PREV CLASS   NEXT CLASS
FRAMES    NO FRAMES
All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

------------------------------------------------------------------------

Copyright © 2000-2008 [Apache Software Foundation](http://www.apache.org/). All Rights Reserved.


text:
import * as fs from 'fs';
import * as path from 'path';

const data = JSON.parse(fs.readFileSync(path.join(__dirname, '../../publish-typings/data/definitions.json'), 'utf-8'));

Object.keys(data).forEach(libName => {
	const libData = data[libName];
	if(libData.kind === 'ProperModule') {
		if (libData.definitionFilename !== 'index.d.ts') {
			console.log(`${libName} needs renaming from ${libData.definitionFilename}`);
			const src = path.join(__dirname, '..', libName, libData.definitionFilename);
			const dst = path.join(__dirname, '..', libName, 'index.d.ts');
			fs.rename(src, dst);
		}
	}
});


text:
export declare type Scheme = "http" | "https" | string;
export declare type Domain = string | {
    http: string;
    https: string;
};


text:
package test.demo.gyniu.v2ex.loader;

import android.content.Context;
import java.util.Collections;
import java.util.List;

import test.demo.gyniu.v2ex.BuildConfig;
import test.demo.gyniu.v2ex.dao.NodeDao;
import test.demo.gyniu.v2ex.model.Node;
import test.demo.gyniu.v2ex.network.HttpRequestHelper;
import test.demo.gyniu.v2ex.utils.LogUtil;

/**
 * Created by uiprj on 17-7-5.
 */
public class NodeListLoader extends AsyncTaskLoader<List<Node>> {
    private static final boolean DEBUG = LogUtil.LOGD;
    private static final String TAG = "NodeListLoader";

    public NodeListLoader(Context context) {
        super(context);
    }

    @Override
    public List<Node> loadInBackgroundWithException() throws Exception {
        List<Node> nodes;
        //for debug
        long startTime = 0;
        if (BuildConfig.DEBUG) startTime = System.nanoTime();
        //////////////////////////
        nodes = NodeDao.getAllNodes();
        //for debug
        if (BuildConfig.DEBUG) {
            long consumingTime = System.nanoTime() - startTime;
            LogUtil.d(TAG, "!!!consuming time : " + consumingTime/1000 + "μs");
        }
        ///////////////////////
        if (nodes != null && nodes.size() > 0) {
            Collections.sort(nodes);
        }
        return nodes;
    }
}


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

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using CharpHat.Services;
using Java.IO;
using Android.Net;

// Source: http://www.goxuni.com/how-to-save-an-image-to-a-device-using-xuni-and-xamarin-forms/

[assembly: Xamarin.Forms.Dependency(typeof(CharpHat.Droid.Services.PictureManager))]
namespace CharpHat.Droid.Services
{
    public class PictureManager : IPictureManager
    {
		public string SavePictureToDisk(string filename, string folder, byte[] imageData)
        {
			var dir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures);
			string picsFolder = System.String.Empty;
			var externalStorage = Android.OS.Environment.ExternalStorageState;
			if (!System.String.IsNullOrEmpty (folder)) {
				picsFolder = System.IO.Path.Combine (dir.AbsolutePath, folder);
			} else {
				picsFolder = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim).AbsolutePath;
			}
            var pck = new File(picsFolder);
            if (!pck.Exists())
                pck.Mkdirs();
            //adding a time stamp time file name to allow saving more than one image… otherwise it overwrites the previous saved image of the same name
            string name = filename + System.DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg";
			string filePath = System.IO.Path.Combine(picsFolder, name);
            try
            {
                System.IO.File.WriteAllBytes(filePath, imageData);
                //mediascan adds the saved image into the gallery
                var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
                mediaScanIntent.SetData(Uri.FromFile(new File(filePath)));
                Xamarin.Forms.Forms.Context.SendBroadcast(mediaScanIntent);
            }
            catch(System.Exception e)
            {
                System.Console.WriteLine(e.ToString());
            }
			return filePath;
        }
    }
}


text:
<?php

namespace Juice\UploadBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class JuiceUploadExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $container->setParameter('tmp_upload_dir', $config['tmp_upload_dir']);
        $container->setParameter('final_upload_dir', $config['final_upload_dir']);
        $container->setParameter('absolute_path', $config['absolute_path']);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');
    }
}


text:
package org.apache.cassandra.db;

import java.nio.ByteBuffer;
import java.util.Arrays;

import org.apache.cassandra.SchemaLoader;
import org.junit.Test;

import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.fail;
import org.apache.cassandra.db.marshal.AsciiType;
import static org.apache.cassandra.Util.column;
import org.apache.cassandra.utils.ByteBufferUtil;

public class RowTest extends SchemaLoader
{
    @Test
    public void testDiffColumnFamily()
    {
        ColumnFamily cf1 = ColumnFamily.create("Keyspace1", "Standard1");
        cf1.addColumn(column("one", "onev", 0));

        ColumnFamily cf2 = ColumnFamily.create("Keyspace1", "Standard1");
        cf2.delete(0, 0);

        ColumnFamily cfDiff = cf1.diff(cf2);
        assertEquals(cfDiff.getColumnsMap().size(), 0);
        assertEquals(cfDiff.getMarkedForDeleteAt(), 0);
    }

    @Test
    public void testDiffSuperColumn()
    {
        SuperColumn sc1 = new SuperColumn(ByteBufferUtil.bytes("one"), AsciiType.instance);
        sc1.addColumn(column("subcolumn", "A", 0));

        SuperColumn sc2 = new SuperColumn(ByteBufferUtil.bytes("one"), AsciiType.instance);
        sc2.markForDeleteAt(0, 0);

        SuperColumn scDiff = (SuperColumn)sc1.diff(sc2);
        assertEquals(scDiff.getSubColumns().size(), 0);
        assertEquals(scDiff.getMarkedForDeleteAt(), 0);
    }

    @Test
    public void testResolve()
    {
        ColumnFamily cf1 = ColumnFamily.create("Keyspace1", "Standard1");
        cf1.addColumn(column("one", "A", 0));

        ColumnFamily cf2 = ColumnFamily.create("Keyspace1", "Standard1");
        cf2.addColumn(column("one", "B", 1));
        cf2.addColumn(column("two", "C", 1));

        cf1.resolve(cf2);
        assert Arrays.equals(cf1.getColumn(ByteBufferUtil.bytes("one")).value().array(), "B".getBytes());
        assert Arrays.equals(cf1.getColumn(ByteBufferUtil.bytes("two")).value().array(), "C".getBytes());
    }

    @Test
    public void testExpiringColumnExpiration()
    {
        Column c = new ExpiringColumn(ByteBufferUtil.bytes("one"), ByteBufferUtil.bytes("A"), 0, 1);
        assert !c.isMarkedForDelete();

        try
        {
            // Because we keep the local deletion time with a precision of a
            // second, we could have to wait 2 seconds in worst case scenario.
            Thread.sleep(2000);
        }
        catch (InterruptedException e)
        {
            fail("Cannot test column expiration if you wake me up too early");
        }

        assert c.isMarkedForDelete() && c.getMarkedForDeleteAt() == 0;
    }
}


text:
var express = require('express');
var path = require('path');

var Album = require(path.join(process.cwd(),
                             '/models/Album'));
var Song = require(path.join(process.cwd(),
                             '/models/Song'));
var router = express.Router();

router.get('/add', function(req,res) {
  res.render('templates/song-add');
});

router.post('/', function(req,res) {
  var s = req.body;
  var song = new Song(s);
  song.save(function(err,result) {
    if(err) console.log(err);
    var albumId = result.ops[0].albumId;
    res.redirect('/album/'+albumId);
  });
});

router.get('/add/:albumId', function(req,res) {
  Album.findById(req.params.albumId,
    function(err,album) {
      if(err) console.log(err);
      album.getArtist(
        function(err, artist) {
          album.artist = artist;
          res.render('song/add',
                    { album : album });
        });
    });
});

router.post('/add/:albumId', function(req,res) {
  req.body.albumId = req.params.albumId;
  var song = new Song(req.body);
  song.save(function(err,result) {
    var albumId = result.ops[0].albumId;
    res.redirect('/album/'+albumId);
  });
});

router.get('/:_id/edit', function(req,res) {
  var _id = req.params._id;
  var song = Song.findById(_id,
    function(err,song) {
      if(err) console.log(err);
      res.render('song/edit',
                { song : song });
    });
});

router.post('/:_id/delete', function(req,res) {
  var _id = req.params._id;
  Song.findById(_id,
    function(err,song) {
      if(err) console.log(err);
      song.getAlbum(
        function(err,album) {
          if(err) console.log(err);
          song.remove(
            function(err,result) {
              if(err) console.log(err);
              res.redirect('/album/'+album._id);
            });
        });
    });
});

router.post('/:_id/edit', function(req,res) {
  var _id = req.params._id;
  var updatedSong = req.body;
  var song = Song.findById(_id,
    function(err,song) {
      if(err) console.log(err);
      song.update(updatedSong,
        function(err,result) {
          Album.findById(song.albumId,
            function(err,album) {
              res.redirect('/album/'+album._id);
            });
        });
    });
});

module.exports = router;


text:
namespace common {

RecursiveLock::RecursiveLock()
    : lock_is_free_(&lock_), thread_id_(0), recursion_(0) {
}

void RecursiveLock::AssertAcquired() {
  DWORD thread_id = ::GetCurrentThreadId();
  base::AutoLock lock(lock_);

  DCHECK_EQ(thread_id, thread_id_);
  DCHECK_LE(0u, recursion_);
}

void RecursiveLock::Acquire() {
  TryImpl(true);
}

void RecursiveLock::Release() {
  DWORD thread_id = ::GetCurrentThreadId();
  base::AutoLock lock(lock_);

  DCHECK_EQ(thread_id, thread_id_);
  DCHECK_LT(0u, recursion_);

  // Decrement the recursion count. If the lock is now free then clear the
  // thread ID and notify a waiting thread.
  --recursion_;
  if (recursion_ == 0) {
    thread_id_ = 0;
    lock_is_free_.Signal();
  }
}

bool RecursiveLock::Try() {
  return TryImpl(false);
}

bool RecursiveLock::TryImpl(bool wait) {
  DWORD thread_id = ::GetCurrentThreadId();
  base::AutoLock lock(lock_);

  // Reentrancy on the same thread.
  if (thread_id_ == thread_id) {
    ++recursion_;
    return true;
  }

  // If we're not willing to wait and the lock is not free to acquire then
  // bail out.
  if (!wait && thread_id_ != 0)
    return false;

  // Somebody else has the lock so let's wait for them to release it.
  while (thread_id_ != 0)
    // This releases lock_ and waits for a signal, thus 'Acquire' does not busy
    // loop.
    lock_is_free_.Wait();

  // Acquire the lock.
  DCHECK_EQ(0u, thread_id_);
  DCHECK_EQ(0u, recursion_);
  thread_id_ = thread_id;
  recursion_ = 1;

  return true;
}

}  // namespace common


text:
package com.astronautlabs.mc.rezolve.bundleBuilder;

import com.astronautlabs.mc.rezolve.RezolveMod;
import com.astronautlabs.mc.rezolve.common.ItemBase;

import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.registry.GameRegistry;

public class BlankBundlePatternItem extends ItemBase {
	public BlankBundlePatternItem() {
		super("item_bundle_pattern_blank");
	}

	@Override
	public void registerRecipes() {

		if (Item.REGISTRY.getObject(new ResourceLocation("enderio:itemAlloy")) != null) {

			RezolveMod.addRecipe(new ItemStack(this),
				"PSP",
				"GFG",
				"PSP",

				'P', "item|enderio:itemAlloy|5",
				'S', "item|enderio:itemMaterial",
				'G', Items.GLOWSTONE_DUST,
				'F', "item|enderio:itemBasicFilterUpgrade"
			);

		} else {
			RezolveMod.addRecipe(new ItemStack(this),
				"OSO",
				"GIG",
				"OSO",

				'O', Blocks.OBSIDIAN,
				'S', Items.SLIME_BALL,
				'G', Items.GLOWSTONE_DUST,
				'I', Items.ITEM_FRAME
			);
		}
	}
}


text:
\section{Discussion}

\section{Conclusion}

\section{Supporting Information}

\bibliographystyle{plos2015}
\bibliography{bibliography}

\end{document}


text:
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Masuit.Tools.AspNetCore.Mime;

namespace Masuit.Tools.Files.FileDetector.Detectors;

[FormatCategory(FormatCategory.Document)]
internal class PFXDetector : AbstractSignatureDetector
{
    private static readonly SignatureInformation[] PfxSignatureInfo = {
        new() { Position = 0, Signature = new byte [] { 0x30, 0x82, 0x06 } },
    };

    public override string Extension => "pfx";

    protected override SignatureInformation[] SignatureInformations => PfxSignatureInfo;

    public override string MimeType => new MimeMapper().GetMimeFromExtension("." + Extension);

    public override List<FormatCategory> FormatCategories => GetType().GetCustomAttributes<FormatCategoryAttribute>().Select(a => a.Category).ToList();

    public override string ToString() => "Microsoft Personal inFormation eXchange Certificate Detector";
}


text:
set -e

# base folder is used to mount some files (e.g. certificates) from the server into the containers
export base_folder=/home/won/matchat

# create a password file for the certificates, variable ${won_certificate_passwd} must be set from outside the script
# note: name of the password file is fixed in won-docker/image/nginx/nginx.conf
echo ${won_certificate_passwd} > won_certificate_passwd_file
ssh won@satvm01 mkdir -p $base_folder/won-server-certs
scp won_certificate_passwd_file won@satvm01:$base_folder/won-server-certs/won_certificate_passwd_file
rm won_certificate_passwd_file

# copy the openssl.conf file to the server where the certificates are generated
# the conf file is needed to specify alternative server names, see conf file in won-docker/image/gencert/openssl.conf
# for entries of alternative server names: matchat.org, www.matchat.org, satvm01.researchstudio.at
scp $WORKSPACE/webofneeds/won-docker/image/gencert/openssl.conf won@satvm01:$base_folder/openssl.conf

# copy the nginx.conf file to the proxy server
scp $WORKSPACE/webofneeds/won-docker/image/nginx/nginx.conf won@satvm01:$base_folder/nginx.conf

# create the solr data directories (if not available yet) with full rights for every user.
# This is done so that the directory on the host can be written by the solr user from inside the container
ssh won@satvm01 mkdir -p $base_folder/solr/won/data
ssh won@satvm01 mkdir -p $base_folder/solr/wontest/data
ssh won@satvm01 chmod 777 $base_folder/solr/won/data
ssh won@satvm01 chmod 777 $base_folder/solr/wontest/data

# copy the matchat skin to the custom skin folder that get used by this instance
ssh won@satvm01 mkdir -p $base_folder/custom_owner_skin
scp -r $WORKSPACE/webofneeds/won-owner-webapp/src/main/webapp/skin/matchat/* won@satvm01:$base_folder/custom_owner_skin/

echo build the docker containers
docker --tlsverify -H satvm01.researchstudio.at:2376 pull webofneeds/bigdata
docker --tlsverify -H satvm01.researchstudio.at:2376 pull webofneeds/won-debugbot:latest
docker --tlsverify -H satvm01.researchstudio.at:2376 pull webofneeds/won-jobbot:latest
docker --tlsverify -H satvm01.researchstudio.at:2376 pull webofneeds/won-spoco-raidbot:latest

# TODO: change the explicit passing of tls params when docker-compose bug is fixed: https://github.com/docker/compose/issues/1427
cd deploy/live_satvm01
docker-compose --tlsverify --tlscacert=/var/lib/jenkins/.docker/ca.pem --tlscert=/var/lib/jenkins/.docker/cert.pem --tlskey=/var/lib/jenkins/.docker/key.pem -H satvm01.researchstudio.at:2376 build

echo run docker containers using docker-compose:
docker-compose --tlsverify --tlscacert=/var/lib/jenkins/.docker/ca.pem --tlscert=/var/lib/jenkins/.docker/cert.pem --tlskey=/var/lib/jenkins/.docker/key.pem -H satvm01.researchstudio.at:2376 down
docker-compose --tlsverify --tlscacert=/var/lib/jenkins/.docker/ca.pem --tlscert=/var/lib/jenkins/.docker/cert.pem --tlskey=/var/lib/jenkins/.docker/key.pem -H satvm01.researchstudio.at:2376 up -d

if test -z $DEPLOY_TO_DOCKERHUB
then
    echo push automatically built webobofneeds images to docker hub
    #
    docker --tlsverify -H satvm01.researchstudio.at:2376 login --username=$DOCKER_USER --password=$DOCKER_PASS
    docker --tlsverify -H satvm01.researchstudio.at:2376 push webofneeds/gencert:live
    docker --tlsverify -H satvm01.researchstudio.at:2376 push webofneeds/wonnode:live
    docker --tlsverify -H satvm01.researchstudio.at:2376 push webofneeds/owner:live
    docker --tlsverify -H satvm01.researchstudio.at:2376 push webofneeds/matcher_service:live
    docker --tlsverify -H satvm01.researchstudio.at:2376 push webofneeds/matcher_solr:live
    # docker --tlsverify -H satvm01.researchstudio.at:2376 push webofneeds/matcher_rescal:live
    docker --tlsverify -H satvm01.researchstudio.at:2376 push webofneeds/solr:live
    docker --tlsverify -H satvm01.researchstudio.at:2376 push webofneeds/postgres:live
    docker --tlsverify -H satvm01.researchstudio.at:2376 push webofneeds/bots:live
else
    echo skipping push built webobofneeds images to docker hub because of DEPLOY_TO_DOCKERHUB not enabled
fi


text:
package edu.internet2.middleware.openid.extensions.ax.impl;

import javax.xml.namespace.QName;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import edu.internet2.middleware.openid.common.ParameterMap;
import edu.internet2.middleware.openid.extensions.ax.AttributeExchange;
import edu.internet2.middleware.openid.extensions.ax.AttributeExchangeUnmarshaller;
import edu.internet2.middleware.openid.extensions.ax.FetchRequest;
import edu.internet2.middleware.openid.extensions.ax.AttributeExchange.Parameter;
import edu.internet2.middleware.openid.util.DatatypeHelper;

/**
 * FetchRequestUnmarshaller.
 */
public class FetchRequestUnmarshaller implements AttributeExchangeUnmarshaller<FetchRequest> {

    /** Logger. */
    private final Logger log = LoggerFactory.getLogger(FetchRequestUnmarshaller.class);

    /** {@inheritDoc} */
    public void unmarshall(FetchRequest request, ParameterMap parameters) {

        String required = parameters.get(Parameter.required.QNAME);
        if (!DatatypeHelper.isEmpty(required)) {
            String[] requiredAliases = required.split(",");
            for (String alias : requiredAliases) {
                String typeURI = unmarshallAttribute(request, parameters, alias);
                if (typeURI != null) {
                    request.getRequiredAttributes().add(typeURI);
                }
            }
        }

        String optional = parameters.get(Parameter.if_available.QNAME);
        if (!DatatypeHelper.isEmpty(optional)) {
            String[] optionalAliases = optional.split(",");
            for (String alias : optionalAliases) {
                String typeURI = unmarshallAttribute(request, parameters, alias);
                if (typeURI != null) {
                    request.getOptionalAttributes().add(typeURI);
                }
            }
        }

        String updateURL = parameters.get(Parameter.update_url.QNAME);
        if (!DatatypeHelper.isEmpty(updateURL)) {
            request.setUpdateURL(updateURL);

        }
    }

    /**
     * Unmarshall the AX request attribute.
     *
     * @param request AX fetch request
     * @param parameters parameter map
     * @param alias alias of the attribute to unmarshall
     * @return type URI for the attribute
     */
    protected String unmarshallAttribute(FetchRequest request, ParameterMap parameters, String alias) {
        QName typeQName = new QName(AttributeExchange.AX_10_NS, "type." + alias);

        if (!parameters.containsKey(typeQName)) {
            log.error("Attribute Exchange alias '{}' not assigned to a type URI", alias);
            return null;
        }

        String typeURI = parameters.get(typeQName);

        // add attribute count
        QName countQName = new QName(AttributeExchange.AX_10_NS, "count." + alias);
        if (parameters.containsKey(countQName)) {
            request.getAttributeCount().put(typeURI, Integer.parseInt(parameters.get(countQName)));
        }

        return typeURI;
    }

}


text:
package hashcode2016.processor;

import hashcode2016.command.PaintCellCommand;
import hashcode2016.model.Board;
import hashcode2016.model.SingleCell;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by nasko on 11/02/2016.
 */
public class SingleCellProcessor {

    public Board board;
    public final List<SingleCell> singleCellList;
    public final List<PaintCellCommand> cellCommands;

    public SingleCellProcessor(Board board) {
        this.board = board;
        this.singleCellList = new ArrayList<>();
        this.cellCommands = new ArrayList<>();
    }

    public void process() {
        for (int row = 0; row < board.rowNum; row++) {
            for (int col = 0; col < board.colNum; col++) {
                if (board.cells[row][col] == '#') {
                    SingleCell singleCell = new SingleCell(row, col);
                    singleCellList.add(singleCell);
                    //System.out.println(singleCell);

                    cellCommands.add(new PaintCellCommand(singleCell));
                    // remove from board
                    board.cells[row][col] = '.';
                }
            }
        }
    }
}


text:
package org.apache.geode.internal.admin.remote;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.geode.CancelException;
import org.apache.geode.DataSerializer;
import org.apache.geode.cache.CacheFactory;
import org.apache.geode.cache.Region;
import org.apache.geode.distributed.internal.DistributionManager;
import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
import org.apache.geode.internal.admin.GemFireVM;
import org.apache.geode.internal.cache.InternalCache;
import org.apache.geode.internal.serialization.DeserializationContext;
import org.apache.geode.internal.serialization.SerializationContext;
import org.apache.geode.util.internal.GeodeGlossary;

/**
 * Responds to {@link RootRegionResponse}.
 */
public class RootRegionResponse extends AdminResponse {

  private String[] regions;
  private String[] userAttrs;

  /**
   * Returns a {@code RootRegionResponse} that will be returned to the specified recipient. The
   * message will contains a copy of the local manager's system config.
   */
  public static RootRegionResponse create(DistributionManager dm,
      InternalDistributedMember recipient) {
    RootRegionResponse m = new RootRegionResponse();
    try {
      InternalCache cache = (InternalCache) CacheFactory.getInstance(dm.getSystem());
      final Collection roots;
      if (!Boolean.getBoolean(GeodeGlossary.GEMFIRE_PREFIX + "PRDebug")) {
        roots = cache.rootRegions();
      } else {
        roots = cache.rootRegions(true);
      }

      List regionNames = new ArrayList();
      List userAttributes = new ArrayList();
      for (Object root : roots) {
        Region r = (Region) root;
        regionNames.add(r.getName());
        userAttributes.add(CacheDisplay.getCachedObjectDisplay(r.getUserAttribute(),
            GemFireVM.LIGHTWEIGHT_CACHE_VALUE));
      }

      String[] temp = new String[0];
      m.regions = (String[]) regionNames.toArray(temp);
      m.userAttrs = (String[]) userAttributes.toArray(temp);;

    } catch (CancelException ignore) {
      /* no cache yet */
    }

    m.setRecipient(recipient);
    return m;
  }

  public Region[] getRegions(RemoteGemFireVM vm) {
    if (this.regions.length > 0) {
      Region[] roots = new Region[this.regions.length];
      for (int i = 0; i < this.regions.length; i++) {
        roots[i] = new AdminRegion(this.regions[i], vm, this.userAttrs[i]);
      }
      return roots;
    } else {
      return new Region[0];
    }
  }

  @Override
  public int getDSFID() {
    return ROOT_REGION_RESPONSE;
  }

  @Override
  public void toData(DataOutput out,
      SerializationContext context) throws IOException {
    super.toData(out, context);
    DataSerializer.writeObject(this.regions, out);
    DataSerializer.writeObject(this.userAttrs, out);
  }

  @Override
  public void fromData(DataInput in,
      DeserializationContext context) throws IOException, ClassNotFoundException {
    super.fromData(in, context);
    this.regions = DataSerializer.readObject(in);
    this.userAttrs = DataSerializer.readObject(in);
  }

  @Override
  public String toString() {
    return "RootRegionResponse from " + this.getRecipient();
  }
}