text:
import { CDPSession } from './Connection.js';
import { Viewport } from './PuppeteerViewport.js';
import { Protocol } from 'devtools-protocol';

export class EmulationManager {
  _client: CDPSession;
  _emulatingMobile = false;
  _hasTouch = false;

  constructor(client: CDPSession) {
    this._client = client;
  }

  async emulateViewport(viewport: Viewport): Promise<boolean> {
    const mobile = viewport.isMobile || false;
    const width = viewport.width;
    const height = viewport.height;
    const deviceScaleFactor = viewport.deviceScaleFactor || 1;
    const screenOrientation: Protocol.Emulation.ScreenOrientation = viewport.isLandscape
      ? { angle: 90, type: 'landscapePrimary' }
      : { angle: 0, type: 'portraitPrimary' };
    const hasTouch = viewport.hasTouch || false;

    await Promise.all([
      this._client.send('Emulation.setDeviceMetricsOverride', {
        mobile,
        width,
        height,
        deviceScaleFactor,
        screenOrientation,
      }),
      this._client.send('Emulation.setTouchEmulationEnabled', {
        enabled: hasTouch,
      }),
    ]);

    const reloadNeeded =
      this._emulatingMobile !== mobile || this._hasTouch !== hasTouch;
    this._emulatingMobile = mobile;
    this._hasTouch = hasTouch;
    return reloadNeeded;
  }
}


text:
  {{name}}

    (
      {{?optional}}optional{{/}}
      {{+partials.variable_type}}
    )

{{?description}}

  {{{description}}}

{{/description}}

redpajama_set_name: RedPajamaGithub


text:
@import '../colors';

.Button {
  background: transparent;
  padding: 8px;
  text-transform: uppercase;
  text-align: center;
  border-radius: 3px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  min-width: 100px;
  transition: all 0.25s ease-in-out;
}

.Button:hover:enabled {
  color: var(--color-background);
  background: var(--color-primary);
}

.Button:disabled {
  cursor: initial;
  color: var(--color-grey-dark);
  border: 2px solid var(--color-grey-dark);
}

.Button-default {
  color: var(--color-grey-lightest);
  border: 2px solid var(--color-grey-lightest);
}

.Button-info {
  padding: 6px;
  font-size: 12px;
  color: var(--color-grey-lightest);
  border: 2px solid var(--color-grey-lightest);
}

.Button-medium {
}

.Button-big {
  font-weight: bold;
  padding: 14px 42px;
}

.Button-big:hover:enabled,
.Button-big:focus {
  transform: scale(1.05);
}

.Button-flat {
  font-weight: bold;
  border: none;
}

.Button-warn {
  color: #fdbc72;
}

.Button-danger {
  color: #c23d4b;
}

.Button-fill {
  width: 100%;
}


text:
namespace AutoResponse.Core.ApiEvents
{
    using System;

    /// <summary>
    /// Unauthenticated API event.
    /// </summary>
    /// <seealso cref="AutoResponse.Core.ApiEvents.IAutoResponseApiEvent" />
    public class UnauthenticatedApiEvent : IAutoResponseApiEvent
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="UnauthenticatedApiEvent"/> class.
        /// </summary>
        /// <param name="code">The code.</param>
        /// <param name="message">The message.</param>
        public UnauthenticatedApiEvent(string code, string message)
        {
            if (string.IsNullOrWhiteSpace(message))
            {
                throw new ArgumentNullException(nameof(message));
            }

            this.Code = code;
            this.Message = message;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="UnauthenticatedApiEvent"/> class.
        /// </summary>
        /// <param name="message">The message.</param>
        public UnauthenticatedApiEvent(string message)
            : this("AR401", message)
        {
        }

        /// <summary>
        /// Gets the code.
        /// </summary>
        /// <value>
        /// The code.
        /// </value>
        public string Code { get; }

        /// <summary>
        /// Gets the message.
        /// </summary>
        /// <value>
        /// The message.
        /// </value>
        public string Message { get; }
    }
}


text:
<?php namespace API;
require_once dirname(__FILE__) . '/groups.data.php';
require_once dirname(dirname(dirname(__FILE__))) . '/services/api.auth.php';

use \Respect\Validation\Validator as v;

class GroupController {

    static function getGroup($app, $groupId) {
        if(!v::intVal()->validate($groupId)) {
            return $app->render(400,  array('msg' => 'Could not select group. Check your parameters and try again.'));
        }
        $group = GroupData::getGroup($groupId);
        if($group) {
            return $app->render(200, array('group' => $group));
        } else {
            return $app->render(400,  array('msg' => 'Could not select group.'));
        }
    }

    static function addGroup($app) {
        // Validate parameters
        if(!v::key('group', v::stringType())->validate($app->request->post()) ||
           !v::key('desc', v::stringType())->validate($app->request->post())) {
            // Validate input parameters
            return $app->render(400, array('msg' => 'Add failed. Check your parameters and try again.'));
        }

        // Verify a unique slug
        $slug = self::makeSlug($app->request->post('group'));
        $existing = GroupData::selectGroupBySlug($slug);
        if ($existing) {
            return $app->render(400,  array('msg' => 'Could not add group. A group with that name already exists.', 'group' => $existing));
        }

        // Add the verifed group
        $groupId = GroupData::insertGroup(array(
            ":group" => $app->request->post('group'),
            ":slug" => $slug,
            ":desc" => $app->request->post('desc'),
            ":created_user_id" => APIAuth::getUserId(),
            ":last_updated_by" => APIAuth::getUserId()
        ));

        // Return success
        if($groupId) {
            GroupData::addPublicRoleToNewGroup($groupId);
            $group = GroupData::getGroup($groupId);
            return $app->render(200, array('group' => $group));
        } else {
            return $app->render(400,  array('msg' => 'Could not add group.'));
        }
    }

    static function saveGroup($app, $groupId) {
        // Validate parameters
        if(!v::intVal()->validate($groupId) ||
           !v::key('group', v::stringType())->validate($app->request->post()) ||
           !v::key('desc', v::stringType())->validate($app->request->post())) {
            // Validate input parameters
            return $app->render(400, array('msg' => 'Update failed. Check your parameters and try again.'));
        }

        // Verify a unique slug
        $slug = self::makeSlug($app->request->post('group'));
        $existing = GroupData::selectGroupBySlug($slug, $groupId);
        if ($existing) {
            return $app->render(400,  array('msg' => 'Could not update group. A group with that name already exists.', 'group' => $existing));
        }

        // Update the verifed group
        $saved = GroupData::updateGroup(array(
            ':id' => $groupId,
            ":group" => $app->request->post('group'),
            ":slug" => $slug,
            ":desc" => $app->request->post('desc'),
            ":last_updated_by" => APIAuth::getUserId()
        ));

        // Return success
        if($saved) {
            $group = GroupData::getGroup($groupId);
            return $app->render(200, array('group' => $group));
        } else {
            return $app->render(400,  array('msg' => 'Could not update group.'));
        }
    }

    static function deleteGroup($app, $groupId) {
        if(!v::intVal()->validate($groupId)) {
            return $app->render(400,  array('msg' => 'Could not delete group. Check your parameters and try again.'));
        } else if(GroupData::deleteGroup($groupId)) {
            return $app->render(200,  array('msg' => 'Group has been deleted.'));
        } else {
            return $app->render(400,  array('msg' => 'Could not delete group.'));
        }
    }

    static function makeSlug($string) {
        return preg_replace('/[^a-zA-Z0-9-_.]/', '', str_replace(' ', '-', strtolower(trim($string))));
    }

    static function unassignRole($app) {
        if(!v::key('groupId', v::stringType())->validate($app->request->post()) ||
           !v::key('roleId', v::stringType())->validate($app->request->post())) {
            return $app->render(400,  array('msg' => 'Could not unassign role from group. Check your parameters and try again.'));
        }

        $data = array (
            ':auth_group_id' => $app->request->post('groupId'),
            ':auth_role_id' => $app->request->post('roleId')
        );

        if(GroupData::deleteRoleAssignment($data)) {
            return $app->render(200,  array('msg' => 'Role has been unassigned from group.'));
        } else {
            return $app->render(400,  array('msg' => 'Could not unassign role from group.'));
        }
    }

    static function assignRole($app) {
        if(!v::key('groupId', v::stringType())->validate($app->request->post()) ||
           !v::key('roleId', v::stringType())->validate($app->request->post())) {
            return $app->render(400,  array('msg' => 'Could not assign role from group. Check your parameters and try again.'));
        }

        $data = array (
            ':auth_group_id' => $app->request->post('groupId'),
            ':auth_role_id' => $app->request->post('roleId'),
            ":created_user_id" => APIAuth::getUserId()
        );

        if(GroupData::insertRoleAssignment($data)) {
            return $app->render(200,  array('msg' => 'Role has been assigned from group.'));
        } else {
            return $app->render(400,  array('msg' => 'Could not assign role to group.'));
        }
    }
}


text:
template <class T>
std::ostream &vnl_matlab_print(std::ostream &,
                              T const *array,
                              unsigned length,
                              vnl_matlab_print_format =vnl_matlab_print_format_default);

//: print a 2D array.
template <class T>
std::ostream &vnl_matlab_print(std::ostream &,
                              T const * const *array,
                              unsigned rows, unsigned cols,
                              vnl_matlab_print_format =vnl_matlab_print_format_default);

//-------------------- "named" forms.

//: print a vnl_diagonal_matrix<T>.
//  \relatesalso vnl_diag_matrix
template <class T>
std::ostream &vnl_matlab_print(std::ostream &,
                              vnl_diag_matrix<T> const&,
                              char const *variable_name =0,
                              vnl_matlab_print_format =vnl_matlab_print_format_default);

//: print a vnl_matrix<T>.
//  \relatesalso vnl_matrix
template <class T>
std::ostream &vnl_matlab_print(std::ostream &,
                              vnl_matrix<T> const&,
                              char const *variable_name =0,
                              vnl_matlab_print_format =vnl_matlab_print_format_default);

//: print a vnl_matrix_fixed<T>.
//  \relatesalso vnl_matrix_fixed
template <class T, unsigned int n, unsigned int m>
std::ostream &vnl_matlab_print(std::ostream &,
                              vnl_matrix_fixed<T,n,m> const&,
                              char const *variable_name =0,
                              vnl_matlab_print_format =vnl_matlab_print_format_default);

//: print a vnl_matrix_ref<T>.
//  \relatesalso vnl_matrix_ref
template <class T>
std::ostream &vnl_matlab_print(std::ostream &,
                              vnl_matrix_ref<T> const &,
                              char const *variable_name =0,
                              vnl_matlab_print_format =vnl_matlab_print_format_default);

//: print a vnl_vector<T>.
//  \relatesalso vnl_vector
template <class T>
std::ostream &vnl_matlab_print(std::ostream &,
                              vnl_vector<T> const &,
                              char const *variable_name =0,
                              vnl_matlab_print_format =vnl_matlab_print_format_default);

//: print a vnl_vector_fixed<T>.
//  \relatesalso vnl_vector_fixed
template <class T, unsigned int n>
std::ostream &vnl_matlab_print(std::ostream &,
                              vnl_vector_fixed<T,n> const &,
                              char const *variable_name =0,
                              vnl_matlab_print_format =vnl_matlab_print_format_default);

//: naughty naming-convention-defying-but-handy macro.
#define MATLABPRINT(X) (vnl_matlab_print(std::cerr, (X).as_ref(), #X))

#endif // vnl_matlab_print_h_


text:
package org.apache.camel.ruby;

import org.jruby.Main;

/**
 * @version
 */
public final class RunScript {
    private RunScript() {
        // helper class
    }
    public static void main(String[] args) {
        if (args.length == 0) {
            runScript("src/test/java/org/apache/camel/ruby/example.rb");
        } else {
            for (String arg : args) {
                runScript(arg);
            }
        }
    }

    public static void runScript(String name) {
        String[] args = {name};
        Main.main(args);
    }
}


text:
<?php

/**
 * docPage admin form
 *
 * @package    diemSite
 * @subpackage docPage
 * @author     Your name here
 */
class DocPageAdminForm extends BaseDocPageForm
{
  public function configure()
  {
    parent::configure();

    $this->widgetSchema['doc_id']->setOption('method', 'getFullName');

    // Unset automatic fields like 'created_at', 'updated_at', 'created_by', 'updated_by'
    $this->unsetAutoFields();
  }
}


text:
package com.linecorp.armeria.client;

import static com.google.common.base.Preconditions.checkState;
import static com.linecorp.armeria.internal.common.RequestContextUtil.newIllegalContextPushingException;
import static com.linecorp.armeria.internal.common.RequestContextUtil.noopSafeCloseable;
import static java.util.Objects.requireNonNull;

import java.net.URI;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

import com.google.errorprone.annotations.MustBeClosed;

import com.linecorp.armeria.client.endpoint.EndpointGroup;
import com.linecorp.armeria.common.ContentTooLargeException;
import com.linecorp.armeria.common.ExchangeType;
import com.linecorp.armeria.common.HttpHeaders;
import com.linecorp.armeria.common.HttpHeadersBuilder;
import com.linecorp.armeria.common.HttpRequest;
import com.linecorp.armeria.common.Request;
import com.linecorp.armeria.common.RequestContext;
import com.linecorp.armeria.common.RequestId;
import com.linecorp.armeria.common.Response;
import com.linecorp.armeria.common.RpcRequest;
import com.linecorp.armeria.common.annotation.Nullable;
import com.linecorp.armeria.common.annotation.UnstableApi;
import com.linecorp.armeria.common.logging.RequestLog;
import com.linecorp.armeria.common.util.SafeCloseable;
import com.linecorp.armeria.common.util.TimeoutMode;
import com.linecorp.armeria.internal.common.RequestContextUtil;
import com.linecorp.armeria.server.ServiceRequestContext;

import io.netty.util.Attribute;

/**
 * Provides information about a {@link Request}, its {@link Response} and its related utilities.
 * Every client request has its own {@link ClientRequestContext} instance.
 */
public interface ClientRequestContext extends RequestContext {

    /**
     * Returns the client-side context of the {@link Request} that is being handled in the current thread.
     *
     * @throws IllegalStateException if the context is unavailable in the current thread or
     *                               the current context is not a {@link ClientRequestContext}.
     */
    static ClientRequestContext current() {
        final RequestContext ctx = RequestContext.current();
        checkState(ctx instanceof ClientRequestContext,
                   "The current context is not a client-side context: %s", ctx);
        return (ClientRequestContext) ctx;
    }

    /**
     * Returns the client-side context of the {@link Request} that is being handled in the current thread.
     *
     * @return the {@link ClientRequestContext} available in the current thread, or {@code null} if unavailable.
     */
    @Nullable
    static ClientRequestContext currentOrNull() {
        final RequestContext ctx = RequestContext.currentOrNull();
        if (ctx instanceof ClientRequestContext) {
            return (ClientRequestContext) ctx;
        }
        return null;
    }

    /**
     * Maps the client-side context of the {@link Request} that is being handled in the current thread.
     *
     * @param mapper the {@link Function} that maps the {@link ClientRequestContext}
     * @param defaultValueSupplier the {@link Supplier} that provides the value when the context is unavailable
     *                             in the current thread. If {@code null}, the {@code null} will be returned
     *                             when the context is unavailable in the current thread.
     * @throws IllegalStateException if the current context is not a {@link ClientRequestContext}.
     */
    @Nullable
    static <T> T mapCurrent(
            Function<? super ClientRequestContext, T> mapper, @Nullable Supplier<T> defaultValueSupplier) {

        final ClientRequestContext ctx = currentOrNull();
        if (ctx != null) {
            return mapper.apply(ctx);
        }

        final ServiceRequestContext serviceRequestContext = ServiceRequestContext.currentOrNull();
        if (serviceRequestContext != null) {
            throw new IllegalStateException("The current context is not a client-side context: " +
                                            serviceRequestContext);
        }

        if (defaultValueSupplier != null) {
            return defaultValueSupplier.get();
        }

        return null;
    }

    /**
     * Returns a new {@link ClientRequestContext} created from the specified {@link HttpRequest}.
     * Note that it is not usually required to create a new context by yourself, because Armeria
     * will always provide a context object for you. However, it may be useful in some cases such as
     * unit testing.
     *
     * @see ClientRequestContextBuilder
     */
    static ClientRequestContext of(HttpRequest request) {
        return builder(request).build();
    }

    /**
     * Returns a new {@link ClientRequestContext} created from the specified {@link RpcRequest} and URI.
     * Note that it is not usually required to create a new context by yourself, because Armeria
     * will always provide a context object for you. However, it may be useful in some cases such as
     * unit testing.
     *
     * @see ClientRequestContextBuilder
     */
    static ClientRequestContext of(RpcRequest request, String uri) {
        return builder(request, URI.create(requireNonNull(uri, "uri"))).build();
    }

    /**
     * Returns a new {@link ClientRequestContext} created from the specified {@link RpcRequest} and {@link URI}.
     * Note that it is not usually required to create a new context by yourself, because Armeria
     * will always provide a context object for you. However, it may be useful in some cases such as
     * unit testing.
     *
     * @see ClientRequestContextBuilder
     */
    static ClientRequestContext of(RpcRequest request, URI uri) {
        return builder(request, uri).build();
    }

    /**
     * Returns a new {@link ClientRequestContextBuilder} created from the specified {@link HttpRequest}.
     */
    static ClientRequestContextBuilder builder(HttpRequest request) {
        return new ClientRequestContextBuilder(request);
    }

    /**
     * Returns a new {@link ClientRequestContextBuilder} created from the specified {@link RpcRequest} and
     * {@code uri}.
     */
    static ClientRequestContextBuilder builder(RpcRequest request, String uri) {
        return builder(request, URI.create(requireNonNull(uri, "uri")));
    }

    /**
     * Returns a new {@link ClientRequestContextBuilder} created from the specified {@link RpcRequest} and
     * {@link URI}.
     */
    static ClientRequestContextBuilder builder(RpcRequest request, URI uri) {
        return new ClientRequestContextBuilder(request, uri);
    }

    /**
     * {@inheritDoc} For example, when you send an RPC request, this method will return {@code null} until
     * the RPC request is translated into an HTTP request.
     */
    @Nullable
    @Override
    HttpRequest request();

    /**
     * {@inheritDoc} For example, this method will return {@code null} when you are not sending an RPC request
     * but just a plain HTTP request.
     */
    @Nullable
    @Override
    RpcRequest rpcRequest();

    /**
     * Pushes this context to the thread-local stack. To pop the context from the stack, call
     * {@link SafeCloseable#close()}, which can be done using a {@code try-with-resources} block:
     *
{@code
     * try (SafeCloseable ignored = ctx.push()) {
     *     ...
     * }
     * }

     *
     *
In order to call this method, the current thread-local state must meet one of the
     * following conditions:
     *

     *
the thread-local does not have any {@link RequestContext} in it

     *
the thread-local has the same {@link ClientRequestContext} as this - reentrance

     *
the thread-local has the {@link ServiceRequestContext} which is the same as {@link #root()}

     *
the thread-local has the {@link ClientRequestContext} whose {@link #root()}
     *       is the same {@link #root()}

     *
the thread-local has the {@link ClientRequestContext} whose {@link #root()} is {@code null}
     *       and this {@link #root()} is {@code null}

     *

     * Otherwise, this method will throw an {@link IllegalStateException}.
     */
    @Override
    @MustBeClosed
    default SafeCloseable push() {
        final RequestContext oldCtx = RequestContextUtil.getAndSet(this);
        if (oldCtx == this) {
            // Reentrance
            return noopSafeCloseable();
        }

        if (oldCtx == null) {
            return RequestContextUtil.invokeHookAndPop(this, null);
        }

        final ServiceRequestContext root = root();
        if (oldCtx.root() == root) {
            return RequestContextUtil.invokeHookAndPop(this, oldCtx);
        }

        // Put the oldCtx back before throwing an exception.
        RequestContextUtil.pop(this, oldCtx);
        throw newIllegalContextPushingException(this, oldCtx);
    }

    /**
     * Creates a new {@link ClientRequestContext} whose properties and {@link Attribute}s are copied from this
     * {@link ClientRequestContext}, except having different {@link Request}, {@link Endpoint} and its own
     * {@link RequestLog}.
     *
     *
Note that this method does not copy the {@link RequestLog} properties to the derived context.
     */
    ClientRequestContext newDerivedContext(RequestId id, @Nullable HttpRequest req, @Nullable RpcRequest rpcReq,
                                           @Nullable Endpoint endpoint);

    /**
     * Returns the {@link EndpointGroup} used for the current {@link Request}.
     *
     * @return the {@link EndpointGroup} if a user specified an {@link EndpointGroup} when initiating
     *         a {@link Request}. {@code null} if a user specified an {@link Endpoint}.
     */
    @Nullable
    EndpointGroup endpointGroup();

    /**
     * Returns the remote {@link Endpoint} of the current {@link Request}.
     *
     * @return the remote {@link Endpoint}, or {@code null} if the {@link Request} has failed
     *         because its remote {@link Endpoint} couldn't be determined.
     */
    @Nullable
    Endpoint endpoint();

    /**
     * Returns the {@link ClientOptions} of the current {@link Request}.
     */
    ClientOptions options();

    /**
     * Returns the fragment part of the URI of the current {@link Request}, as defined in
     * the section 3.5 of RFC3986.
     *
     * @return the fragment part of the request URI, or {@code null} if no fragment was specified
     */
    @Nullable
    String fragment();

    /**
     * Returns the amount of time allowed until the initial write attempt of the current {@link Request}
     * succeeds. This value is initially set from {@link ClientOptions#WRITE_TIMEOUT_MILLIS}.
     */
    long writeTimeoutMillis();

    /**
     * Sets the amount of time allowed until the initial write attempt of the current {@link Request}
     * succeeds. This value is initially set from {@link ClientOptions#WRITE_TIMEOUT_MILLIS}.
     */
    void setWriteTimeoutMillis(long writeTimeoutMillis);

    /**
     * Sets the amount of time allowed until the initial write attempt of the current {@link Request}
     * succeeds. This value is initially set from {@link ClientOptions#WRITE_TIMEOUT_MILLIS}.
     */
    void setWriteTimeout(Duration writeTimeout);

    /**
     * Returns the amount of time allowed until receiving the {@link Response} completely
     * since the transfer of the {@link Response} started or the {@link Request} was fully sent. This value is
     * initially set from {@link ClientOptions#RESPONSE_TIMEOUT_MILLIS}.
     */
    long responseTimeoutMillis();

    /**
     * Clears the previously scheduled response timeout, if any.
     * Note that calling this will prevent the response from ever being timed out.
     */
    void clearResponseTimeout();

    /**
     * Schedules the response timeout that is triggered when the {@link Response} is not fully received within
     * the specified {@link TimeoutMode} and the specified {@code responseTimeoutMillis} since
     * the {@link Response} started or {@link Request} was fully sent.
     * This value is initially set from {@link ClientOptions#RESPONSE_TIMEOUT_MILLIS}.
     *
     *

     *
timeout mode description

     *
Timeout mode	description

     *
{@link TimeoutMode#SET_FROM_NOW}
     *     Sets a given amount of timeout from the current time.

     *
{@link TimeoutMode#SET_FROM_START}
     *     Sets a given amount of timeout since the current {@link Response} began processing.

     *
{@link TimeoutMode#EXTEND}
     *     Extends the previously scheduled timeout by the given amount of timeout.

     *

     *
     *
For example:
     *
{@code
     * ClientRequestContext ctx = ...;
     * // Schedules a timeout from the start time of the response
     * ctx.setResponseTimeoutMillis(TimeoutMode.SET_FROM_START, 2000);
     * assert ctx.responseTimeoutMillis() == 2000;
     * ctx.setResponseTimeoutMillis(TimeoutMode.SET_FROM_START, 1000);
     * assert ctx.responseTimeoutMillis() == 1000;
     *
     * // Schedules timeout after 3 seconds from now.
     * ctx.setResponseTimeoutMillis(TimeoutMode.SET_FROM_NOW, 3000);
     *
     * // Extends the previously scheduled timeout.
     * long oldResponseTimeoutMillis = ctx.responseTimeoutMillis();
     * ctx.setResponseTimeoutMillis(TimeoutMode.EXTEND, 1000);
     * assert ctx.responseTimeoutMillis() == oldResponseTimeoutMillis + 1000;
     * ctx.extendResponseTimeoutMillis(TimeoutMode.EXTEND, -500);
     * assert ctx.responseTimeoutMillis() == oldResponseTimeoutMillis + 500;
     * }

     */
    void setResponseTimeoutMillis(TimeoutMode mode, long responseTimeoutMillis);

    /**
     * Schedules the response timeout that is triggered when the {@link Response} is not
     * fully received within the specified amount of time from now.
     * Note that the specified {@code responseTimeoutMillis} must be positive.
     * This value is initially set from {@link ClientOptions#RESPONSE_TIMEOUT_MILLIS}.
     * This method is a shortcut for
     * {@code setResponseTimeoutMillis(TimeoutMode.SET_FROM_NOW, responseTimeoutMillis)}.
     *
     *
For example:
     *
{@code
     * ClientRequestContext ctx = ...;
     * // Schedules timeout after 1 seconds from now.
     * ctx.setResponseTimeoutMillis(1000);
     * }

     *
     * @param responseTimeoutMillis the amount of time allowed in milliseconds from now
     */
    default void setResponseTimeoutMillis(long responseTimeoutMillis) {
        setResponseTimeoutMillis(TimeoutMode.SET_FROM_NOW, responseTimeoutMillis);
    }

    /**
     * Schedules the response timeout that is triggered when the {@link Response} is not fully received within
     * the specified {@link TimeoutMode} and the specified {@code responseTimeoutMillis} since
     * the {@link Response} started or {@link Request} was fully sent.
     * This value is initially set from {@link ClientOptions#RESPONSE_TIMEOUT_MILLIS}.
     *
     *

     *
timeout mode description

     *
Timeout mode	description

     *
{@link TimeoutMode#SET_FROM_NOW}
     *     Sets a given amount of timeout from the current time.

     *
{@link TimeoutMode#SET_FROM_START}
     *     Sets a given amount of timeout since the current {@link Response} began processing.

     *
{@link TimeoutMode#EXTEND}
     *     Extends the previously scheduled timeout by the given amount of timeout.

     *

     *
     *
For example:
     *
{@code
     * ClientRequestContext ctx = ...;
     * // Schedules a timeout from the start time of the response
     * ctx.setResponseTimeoutMillis(TimeoutMode.SET_FROM_START, Duration.ofSeconds(2));
     * assert ctx.responseTimeoutMillis() == 2000;
     * ctx.setResponseTimeoutMillis(TimeoutMode.SET_FROM_START, Duration.ofSeconds(1));
     * assert ctx.responseTimeoutMillis() == 1000;
     *
     * // Schedules timeout after 3 seconds from now.
     * ctx.setResponseTimeoutMillis(TimeoutMode.SET_FROM_NOW, Duration.ofSeconds(3));
     *
     * // Extends the previously scheduled timeout.
     * long oldResponseTimeoutMillis = ctx.responseTimeoutMillis();
     * ctx.setResponseTimeoutMillis(TimeoutMode.EXTEND, Duration.ofSeconds(1));
     * assert ctx.responseTimeoutMillis() == oldResponseTimeoutMillis + 1000;
     * ctx.setResponseTimeoutMillis(TimeoutMode.EXTEND, Duration.ofMillis(-500));
     * assert ctx.responseTimeoutMillis() == oldResponseTimeoutMillis + 500;
     * }

     */
    void setResponseTimeout(TimeoutMode mode, Duration responseTimeout);

    /**
     * Schedules the response timeout that is triggered when the {@link Response} is not
     * fully received within the specified amount of time from now.
     * Note that the specified {@code responseTimeout} must be positive.
     * This value is initially set from {@link ClientOptions#RESPONSE_TIMEOUT_MILLIS}.
     * This method is a shortcut for {@code setResponseTimeout(TimeoutMode.SET_FROM_NOW, responseTimeout)}.
     *
     *
For example:
     *
{@code
     * ClientRequestContext ctx = ...;
     * // Schedules timeout after 1 seconds from now.
     * ctx.setResponseTimeout(Duration.ofSeconds(1));
     * }

     *
     * @param responseTimeout the amount of time allowed from now
     *
     */
    default void setResponseTimeout(Duration responseTimeout) {
        setResponseTimeout(TimeoutMode.SET_FROM_NOW, responseTimeout);
    }

    /**
     * Returns a {@link CompletableFuture} which is completed with a {@link Throwable} cancellation cause when
     * the {@link ClientRequestContext} is about to get cancelled. If the response is handled successfully
     * without cancellation, the {@link CompletableFuture} won't complete.
     */
    CompletableFuture<Throwable> whenResponseCancelling();

    /**
     * Returns a {@link CompletableFuture} which is completed with a {@link Throwable} cancellation cause after
     * the {@link ClientRequestContext} has been cancelled. {@link #isCancelled()} will always return
     * {@code true} when the returned {@link CompletableFuture} is completed. If the response is handled
     * successfully without cancellation, the {@link CompletableFuture} won't complete.
     */
    CompletableFuture<Throwable> whenResponseCancelled();

    /**
     * Returns a {@link CompletableFuture} which is completed when the {@link ClientRequestContext} is about to
     * get timed out. If the response is handled successfully or not cancelled by timeout, the
     * {@link CompletableFuture} won't complete.
     *
     * @deprecated Use {@link #whenResponseCancelling()} instead.
     */
    @Deprecated
    CompletableFuture<Void> whenResponseTimingOut();

    /**
     * Returns a {@link CompletableFuture} which is completed after the {@link ClientRequestContext} has been
     * timed out. {@link #isTimedOut()} will always return {@code true} when the returned
     * {@link CompletableFuture} is completed. If the response is handled successfully or not cancelled by
     * timeout, the {@link CompletableFuture} won't complete.
     *
     * @deprecated Use {@link #whenResponseCancelled()} instead.
     */
    @Deprecated
    CompletableFuture<Void> whenResponseTimedOut();

    /**
     * Cancels the response. Shortcut for {@code cancel(ResponseCancellationException.get())}.
     */
    @Override
    default void cancel() {
        cancel(ResponseCancellationException.get());
    }

    /**
     * Times out the response. Shortcut for {@code cancel(ResponseTimeoutException.get())}.
     */
    @Override
    default void timeoutNow() {
        cancel(ResponseTimeoutException.get());
    }

    /**
     * Returns the maximum length of the received {@link Response}.
     * This value is initially set from {@link ClientOptions#MAX_RESPONSE_LENGTH}.
     *
     * @return the maximum length of the response. {@code 0} if unlimited.
     *
     * @see ContentTooLargeException
     */
    long maxResponseLength();

    /**
     * Sets the maximum length of the received {@link Response}.
     * This value is initially set from {@link ClientOptions#MAX_RESPONSE_LENGTH}.
     * Specify {@code 0} to disable the limit of the length of a response.
     *
     * @see ContentTooLargeException
     */
    void setMaxResponseLength(long maxResponseLength);

    /**
     * Returns an {@link HttpHeaders} which will be included when a {@link Client} sends an {@link HttpRequest}.
     */
    HttpHeaders additionalRequestHeaders();

    /**
     * Sets a header with the specified {@code name} and {@code value}. This will remove all previous values
     * associated with the specified {@code name}.
     * The header will be included when a {@link Client} sends an {@link HttpRequest}.
     */
    void setAdditionalRequestHeader(CharSequence name, Object value);

    /**
     * Adds a header with the specified {@code name} and {@code value}. The header will be included when
     * a {@link Client} sends an {@link HttpRequest}.
     */
    void addAdditionalRequestHeader(CharSequence name, Object value);

    /**
     * Mutates the {@link HttpHeaders} which will be included when a {@link Client} sends
     * an {@link HttpRequest}.
     *
     * @param mutator the {@link Consumer} that mutates the additional request headers
     */
    void mutateAdditionalRequestHeaders(Consumer<HttpHeadersBuilder> mutator);

    /**
     * {@inheritDoc}
     *
     *
Note that an {@link HttpRequest} will be aggregated before being written if
     * {@link ExchangeType#UNARY} or {@link ExchangeType#RESPONSE_STREAMING} is set.
     */
    @Override
    @UnstableApi
    ExchangeType exchangeType();
}


text:
package org.elasticsearch.common.blobstore.fs;

import org.apache.lucene.util.IOUtils;
import org.elasticsearch.common.blobstore.BlobMetaData;
import org.elasticsearch.common.blobstore.BlobPath;
import org.elasticsearch.common.blobstore.support.AbstractBlobContainer;
import org.elasticsearch.common.blobstore.support.PlainBlobMetaData;
import org.elasticsearch.common.io.Streams;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashMap;
import java.util.Map;

import static java.util.Collections.unmodifiableMap;

/**
 * A file system based implementation of {@link org.elasticsearch.common.blobstore.BlobContainer}.
 * All blobs in the container are stored on a file system, the location of which is specified by the {@link BlobPath}.
 *
 * Note that the methods in this implementation of {@link org.elasticsearch.common.blobstore.BlobContainer} may
 * additionally throw a {@link java.lang.SecurityException} if the configured {@link java.lang.SecurityManager}
 * does not permit read and/or write access to the underlying files.
 */
public class FsBlobContainer extends AbstractBlobContainer {

    protected final FsBlobStore blobStore;

    protected final Path path;

    public FsBlobContainer(FsBlobStore blobStore, BlobPath blobPath, Path path) {
        super(blobPath);
        this.blobStore = blobStore;
        this.path = path;
    }

    @Override
    public Map<String, BlobMetaData> listBlobs() throws IOException {
        return listBlobsByPrefix(null);
    }

    @Override
    public Map<String, BlobMetaData> listBlobsByPrefix(String blobNamePrefix) throws IOException {
        // If we get duplicate files we should just take the last entry
        Map<String, BlobMetaData> builder = new HashMap<>();

        blobNamePrefix = blobNamePrefix == null ? "" : blobNamePrefix;
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(path, blobNamePrefix + "*")) {
            for (Path file : stream) {
                final BasicFileAttributes attrs = Files.readAttributes(file, BasicFileAttributes.class);
                if (attrs.isRegularFile()) {
                    builder.put(file.getFileName().toString(), new PlainBlobMetaData(file.getFileName().toString(), attrs.size()));
                }
            }
        }
        return unmodifiableMap(builder);
    }

    @Override
    public void deleteBlob(String blobName) throws IOException {
        Path blobPath = path.resolve(blobName);
        Files.deleteIfExists(blobPath);
    }

    @Override
    public boolean blobExists(String blobName) {
        return Files.exists(path.resolve(blobName));
    }

    @Override
    public InputStream readBlob(String name) throws IOException {
        return new BufferedInputStream(Files.newInputStream(path.resolve(name)), blobStore.bufferSizeInBytes());
    }

    @Override
    public void writeBlob(String blobName, InputStream inputStream, long blobSize) throws IOException {
        final Path file = path.resolve(blobName);
        // TODO: why is this not specifying CREATE_NEW? Do we really need to be able to truncate existing files?
        try (OutputStream outputStream = Files.newOutputStream(file)) {
            Streams.copy(inputStream, outputStream, new byte[blobStore.bufferSizeInBytes()]);
        }
        IOUtils.fsync(file, false);
        IOUtils.fsync(path, true);
    }

    @Override
    public void move(String source, String target) throws IOException {
        Path sourcePath = path.resolve(source);
        Path targetPath = path.resolve(target);
        // If the target file exists then Files.move() behaviour is implementation specific
        // the existing file might be replaced or this method fails by throwing an IOException.
        assert !Files.exists(targetPath);
        Files.move(sourcePath, targetPath, StandardCopyOption.ATOMIC_MOVE);
        IOUtils.fsync(path, true);
    }
}


text:
package workshop.microservices.weblog.core;

import static workshop.microservices.weblog.TestData.*;

import java.util.Date;

/**
 * Creates article test data.
 */
public class ArticleBuilder {

    private String articleId;

    private String title;

    private String content;

    private AuthorBuilder author;

    private Date created;

    public ArticleBuilder withArticleId(String articleId) {
        this.articleId = articleId;
        return this;
    }

    public ArticleBuilder withTitle(String title) {
        this.title = title;
        return this;
    }

    public ArticleBuilder andContent(String content) {
        this.content = content;
        return this;
    }

    public ArticleBuilder writtenBy(AuthorBuilder author) {
        this.author = author;
        return this;
    }

    public ArticleBuilder createdOn(Date created) {
        this.created = created;
        return this;
    }

    public Article build() {
        return new Article(articleId, title, content, author.build(), created);
    }

    public static ArticleBuilder defaultArticle() {
        return new ArticleBuilder()
                .withArticleId(ARTICLE_ID)
                .withTitle(TITLE)
                .andContent(CONTENT)
                .writtenBy(AuthorBuilder.defaultAuthor())
                .createdOn(new Date());
    }
}


text:
class AddJoinTableForCorpusTextAndMetadataValue < ActiveRecord::Migration
  def change
    create_table :rglossa_corpus_texts_metadata_values do |t|
      t.belongs_to :rglossa_corpus_text, null: false
      t.belongs_to :rglossa_metadata_value, null: false
    end
  end
end


text:
from pyramid.config import Configurator
from pyramid.response import Response

def hello_world(request):
    return Response('
Hello World!
')

def main(global_config, **settings):
    config = Configurator(settings=settings)
    config.add_route('hello', '/')
    config.add_view(hello_world, route_name='hello')
    return config.make_wsgi_app()


text:
<!doctype html>
<meta http-equiv="X-UA-Compatible" content="IE=Edge">

	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />

PatientFlow

		Add Patient Event

		Add Patient Event


text:
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#ifndef SQLITE_STRATEGIES_H
#define SQLITE_STRATEGIES_H 1

#include <cstdlib>
#include <vector>
#include <algorithm>

#include "common.hh"
#include "queueditem.hh"
#include "sqlite-pst.hh"
#include "sqlite-stats.hh"

class EventuallyPersistentEngine;

typedef enum {
    select_all,
    delete_vbucket
} vb_statement_type;

/**
 * Base class for all Sqlite strategies.
 */
class SqliteStrategy {
public:

    SqliteStrategy(const char * const fn,
                   const char * const finit,
                   const char * const pfinit,
                   size_t shards);

    virtual ~SqliteStrategy();

    sqlite3 *open();
    void close();

    size_t getNumOfDbShards() {
        return shardCount;
    }

    virtual uint16_t getDbShardId(const QueuedItem &qi) {
        return getDbShardIdForKey(qi.getKey());
    }

    virtual const std::vector<Statements *> &allStatements() = 0;

    virtual Statements *getStatements(uint16_t vbid, uint16_t vbver,
                                      const std::string &key) = 0;

    PreparedStatement *getInsVBucketStateST() {
        return ins_vb_stmt;
    }

    PreparedStatement *getClearVBucketStateST() {
        return clear_vb_stmt;
    }

    PreparedStatement *getGetVBucketStateST() {
        return sel_vb_stmt;
    }

    PreparedStatement *getClearStatsST() {
        return clear_stats_stmt;
    }

    PreparedStatement *getInsStatST() {
        return ins_stat_stmt;
    }

    virtual bool hasEfficientVBLoad() { return false; }

    virtual bool hasEfficientVBDeletion() { return false; }

    virtual std::vector<PreparedStatement*> getVBStatements(uint16_t vb, vb_statement_type vbst) {
        (void)vb;
        (void)vbst;
        std::vector<PreparedStatement*> rv;
        return rv;
    }

    virtual void closeVBStatements(std::vector<PreparedStatement*> &psts) {
        (void)psts;
    }

    virtual void destroyTables() = 0;
    virtual void destroyInvalidTables(bool destroyOnlyOne = false) = 0;

    virtual void renameVBTable(uint16_t vbucket, const std::string &newName) {
        (void)vbucket;
        (void)newName;
    }

    virtual void createVBTable(uint16_t vbucket) {
        (void)vbucket;
    }

    virtual void optimizeWrites(std::vector<queued_item> &items) {
        (void)items;
    }

    void execute(const char * const query);

    static void disableSchemaCheck() {
        shouldCheckSchemaVersion = false;
    }

    SQLiteStats         sqliteStats;

protected:

    void doFile(const char * const filename);

    uint16_t getDbShardIdForKey(const std::string &key) {
        assert(shardCount > 0);
        int h=5381;
        int i=0;
        const char *str = key.c_str();

        for(i=0; str[i] != 0x00; i++) {
            h = ((h << 5) + h) ^ str[i];
        }
        return std::abs(h) % (int)shardCount;
    }

    virtual void initDB() {
        doFile(initFile);
    }

    void checkSchemaVersion();
    void initMetaTables();

    virtual void initTables() = 0;
    virtual void initStatements() = 0;
    virtual void initMetaStatements();
    virtual void destroyStatements() {};

    void destroyMetaStatements();

    static bool shouldCheckSchemaVersion;

    sqlite3            *db;
    const char * const  filename;
    const char * const  initFile;
    const char * const  postInitFile;
    size_t              shardCount;

    PreparedStatement *ins_vb_stmt;
    PreparedStatement *clear_vb_stmt;
    PreparedStatement *sel_vb_stmt;

    PreparedStatement *clear_stats_stmt;
    PreparedStatement *ins_stat_stmt;

    uint16_t            schema_version;

private:
    DISALLOW_COPY_AND_ASSIGN(SqliteStrategy);
};

//
// ----------------------------------------------------------------------
// Concrete Strategies
// ----------------------------------------------------------------------
//

/**
 * Strategy for a single table kv store in a single DB.
 */
class SingleTableSqliteStrategy : public SqliteStrategy {
public:

    /**
     * Constructor.
     *
     * @param fn the filename of the DB
     * @param finit an init script to run as soon as the DB opens
     * @param pfinit an init script to run after initializing all schema
     * @param shards the number of shards
     */
    SingleTableSqliteStrategy(const char * const fn,
                              const char * const finit,
                              const char * const pfinit,
                              size_t shards = 1) :
        SqliteStrategy(fn, finit, pfinit, shards), statements() {
        assert(filename);
    }

    virtual ~SingleTableSqliteStrategy() { }

    const std::vector<Statements *> &allStatements() {
        return statements;
    }

    Statements *getStatements(uint16_t vbid, uint16_t vbver,
                              const std::string &key) {
        (void)vbid;
        (void)vbver;
        return statements.at(getDbShardIdForKey(key));
    }

    void destroyStatements();
    virtual void destroyTables();
    virtual void destroyInvalidTables(bool destroyOnlyOne = false);

    void optimizeWrites(std::vector<queued_item> &items) {
        // Sort all the queued items for each db shard by their row ids
        CompareQueuedItemsByRowId cq;
        std::sort(items.begin(), items.end(), cq);
    }

    virtual std::vector<PreparedStatement*> getVBStatements(uint16_t vb, vb_statement_type vbst) {
        (void)vb;
        std::vector<PreparedStatement*> rv;
        std::vector<Statements*>::iterator it;
        for (it = statements.begin(); it != statements.end(); ++it) {
            switch (vbst) {
            case select_all:
                rv.push_back((*it)->all());
                break;
            case delete_vbucket:
                rv.push_back((*it)->del_vb());
                break;
            default:
                break;
            }
        }

        return rv;
    }

    virtual void closeVBStatements(std::vector<PreparedStatement*> &psts) {
        std::for_each(psts.begin(), psts.end(),
                      std::mem_fun(&PreparedStatement::reset));
    }

protected:
    std::vector<Statements *> statements;

    virtual void initTables();
    virtual void initStatements();

private:
    DISALLOW_COPY_AND_ASSIGN(SingleTableSqliteStrategy);
};

//
// ----------------------------------------------------------------------
// Multi DB strategy
// ----------------------------------------------------------------------
//

/**
 * A specialization of SqliteStrategy that allows multiple data
 * shards with a single kv table each.
 */
class MultiDBSingleTableSqliteStrategy : public SingleTableSqliteStrategy {
public:

    /**
     * Constructor.
     *
     * @param fn same as SqliteStrategy
     * @param sp the shard pattern
     * @param finit same as SqliteStrategy
     * @param pfinit same as SqliteStrategy
     * @param n number of DB shards to create
     */
    MultiDBSingleTableSqliteStrategy(const char * const fn,
                                     const char * const sp,
                                     const char * const finit,
                                     const char * const pfinit,
                                     int n):
        SingleTableSqliteStrategy(fn, finit, pfinit, n),
        shardpattern(sp), numTables(n) {
        assert(shardpattern);
    }

    void initDB(void);
    void initTables(void);
    void initStatements(void);
    void destroyTables(void);
    void destroyInvalidTables(bool destroyOnlyOne = false);

private:
    const char * const shardpattern;
    int numTables;
};

//
// ----------------------------------------------------------------------
// Table Per Vbucket
// ----------------------------------------------------------------------
//

/**
 * Strategy for a table per vbucket store in a single DB.
 */
class MultiTableSqliteStrategy : public SqliteStrategy {
public:

    /**
     * Constructor.
     *
     * @param fn the filename of the DB
     * @param finit an init script to run as soon as the DB opens
     * @param pfinit an init script to run after initializing all schema
     * @param nv the maxinum number of vbuckets
     * @param shards the number of data shards
     */
    MultiTableSqliteStrategy(const char * const fn,
                             const char * const finit,
                             const char * const pfinit,
                             int nv,
                             int shards=1)
        : SqliteStrategy(fn, finit, pfinit, shards),
          nvbuckets(nv), statements() {

        assert(filename);
    }

    virtual ~MultiTableSqliteStrategy() { }

    const std::vector<Statements *> &allStatements() {
        return statements;
    }

    virtual Statements *getStatements(uint16_t vbid, uint16_t vbver,
                                      const std::string &key) {
        (void)vbver;
        (void)key;
        assert(static_cast<size_t>(vbid) < statements.size());
        return statements.at(vbid);
    }

    virtual void destroyStatements();
    virtual void destroyTables();
    virtual void destroyInvalidTables(bool destroyOnlyOne = false);

    virtual void renameVBTable(uint16_t vbucket, const std::string &newName);
    virtual void createVBTable(uint16_t vbucket);

    bool hasEfficientVBLoad() { return true; }

    bool hasEfficientVBDeletion() { return true; }

    virtual std::vector<PreparedStatement*> getVBStatements(uint16_t vb, vb_statement_type vbst) {
        std::vector<PreparedStatement*> rv;
        assert(static_cast<size_t>(vb) < statements.size());
        switch (vbst) {
        case select_all:
            rv.push_back(statements.at(vb)->all());
            break;
        case delete_vbucket:
            rv.push_back(statements.at(vb)->del_vb());
            break;
        default:
            break;
        }
        return rv;
    }

    void closeVBStatements(std::vector<PreparedStatement*> &psts) {
        std::for_each(psts.begin(), psts.end(),
                      std::mem_fun(&PreparedStatement::reset));
    }

    void optimizeWrites(std::vector<queued_item> &items) {
        // Sort all the queued items for each db shard by its vbucket
        // ID and then its row ids
        CompareQueuedItemsByVBAndRowId cq;
        std::sort(items.begin(), items.end(), cq);
    }

protected:
    size_t nvbuckets;
    std::vector<Statements *> statements;

    virtual void initTables();
    virtual void initStatements();

private:
    DISALLOW_COPY_AND_ASSIGN(MultiTableSqliteStrategy);
};

//
// ----------------------------------------------------------------------
// Multiple Shards, Table Per Vbucket
// ----------------------------------------------------------------------
//

/**
 * Strategy for a table per vbucket store in multiple shards.
 */
class ShardedMultiTableSqliteStrategy : public MultiTableSqliteStrategy {
public:

    /**
     * Constructor.
     *
     * @param fn the filename of the DB
     * @param sp the shard pattern
     * @param finit an init script to run as soon as the DB opens
     * @param pfinit an init script to run after initializing all schema
     * @param nv the maxinum number of vbuckets
     * @param n the number of data shards
     */
    ShardedMultiTableSqliteStrategy(const char * const fn,
                                    const char * const sp,
                                    const char * const finit,
                                    const char * const pfinit,
                                    int nv,
                                    int n)
        : MultiTableSqliteStrategy(fn, finit, pfinit, nv, n),
          shardpattern(sp),
          statementsPerShard() {

        assert(filename);
    }

    virtual ~ShardedMultiTableSqliteStrategy() { }

    Statements *getStatements(uint16_t vbid, uint16_t vbver,
                              const std::string &key);

    void destroyStatements();
    void destroyTables();
    void destroyInvalidTables(bool destroyOnlyOne = false);

    void renameVBTable(uint16_t vbucket, const std::string &newName);
    void createVBTable(uint16_t vbucket);

    std::vector<PreparedStatement*> getVBStatements(uint16_t vb, vb_statement_type vbst);

protected:
    const char * const        shardpattern;
    // statementsPerShard[vbucket][shard]
    std::vector<std::vector<Statements*> > statementsPerShard;

    void initDB();
    void initTables();
    void initStatements();

private:
    DISALLOW_COPY_AND_ASSIGN(ShardedMultiTableSqliteStrategy);
};

//
// ----------------------------------------------------------------------
// Sharded by VBucket
// ----------------------------------------------------------------------
//

/**
 * Strategy for a table per vbucket where each vbucket exists in only
 * one shard.
 */
class ShardedByVBucketSqliteStrategy : public MultiTableSqliteStrategy {
public:

    /**
     * Constructor.
     *
     * @param fn the filename of the DB
     * @param sp the shard pattern for generating shard files
     * @param finit an init script to run as soon as the DB opens
     * @param pfinit an init script to run after initializing all schema
     * @param nv the maxinum number of vbuckets
     * @param n the number of data shards
     */
    ShardedByVBucketSqliteStrategy(const char * const fn,
                                   const char * const sp,
                                   const char * const finit,
                                   const char * const pfinit,
                                   int nv,
                                   int n)
        : MultiTableSqliteStrategy(fn, finit, pfinit, nv, n),
          shardpattern(sp) {

        assert(filename);
    }

    uint16_t getDbShardId(const QueuedItem &qi) {
        return getShardForVBucket(qi.getVBucketId());
    }

    virtual ~ShardedByVBucketSqliteStrategy() { }

    void destroyTables();
    void destroyInvalidTables(bool destroyOnlyOne = false);

    void renameVBTable(uint16_t vbucket, const std::string &newName);
    void createVBTable(uint16_t vbucket);

protected:
    const char * const shardpattern;

    size_t getShardForVBucket(uint16_t vb) {
        size_t rv = (static_cast<size_t>(vb) % shardCount);
        assert(rv < shardCount);
        return rv;
    }

    void initDB();
    void initTables();
    void initStatements();

private:
    DISALLOW_COPY_AND_ASSIGN(ShardedByVBucketSqliteStrategy);
};

#endif /* SQLITE_STRATEGIES_H */


text:
namespace mesos {

// Forward declaration.
class Resources;

class ResourceLimits;

// An efficient collection of resource quantities. All values are guaranteed
// to be positive and finite.
//
// E.g. [("cpus", 4.5), ("gpus", 0.1), ("ports", 1000)]
//
// Absent resource entries imply there is no (zero) such resources.
//
// Notes on handling negativity and arithmetic operations: values are guaranteed
// to be positive. This is achieved by construction validation and no public
// mutation interfaces. During construction, `Value::Scalar` arguments must be
// non-negative and finite, and entries with zero quantities will be dropped
// silently. Invalid arguments will result in an error where `Try`
// is returned. For arithmetic operations, non-positive values are silently
// dropped--this is consist with `class Resources`.
//
// Note for posterity, the status quo prior to this class
// was to use stripped-down `Resources` objects for storing
// quantities, however this approach:
//
//   (1) did not support quantities of non-scalar resources;
//   (2) was error prone, the caller must ensure that no
//       `Resource` metatdata (e.g. `DiskInfo`) is present;
//   (3) had poor performance, given the `Resources` storage
//       model and arithmetic implementation have to operate
//       on broader invariants.
class ResourceQuantities
{
public:
  // Parse an input string of semicolon separated "name:number" pairs.
  // Duplicate names are allowed in the input and will be merged into one entry.
  // Entries with zero values will be silently dropped.
  //
  // Example: "cpus:10;mem:1024;ports:3"
  //          "cpus:10; mem:1024; ports:3"
  // NOTE: we will trim the whitespace around the pair and in the number.
  // However, whitespace in "c p us:10" are preserved and will be parsed to
  // {"c p us", 10}. This is consistent with `Resources::fromSimpleString()`.
  //
  // Numbers must be non-negative and finite, otherwise an `Error`
  // will be returned.
  static Try<ResourceQuantities> fromString(const std::string& text);

  // Take scalar `Resources` and combine them into `ResourceQuantities`.
  // Only the resource name and its scalar value are used and the rest of the
  // meta-data is ignored. It is caller's responsibility to ensure all
  // `Resource` entries are of scalar type. Otherwise a `CHECK` error will
  // be triggered.
  static ResourceQuantities fromScalarResources(const Resources& resources);

  // Same as above, but takes a single Resource that must be valid
  // and of scalar type.
  static ResourceQuantities fromScalarResource(const Resource& resource);

  // Take `Resources` and combine them into `ResourceQuantities`. This function
  // assumes that the provided resources have already been validated; for
  // example, it assumes that ranges do not overlap and that sets do not contain
  // duplicate items.
  static ResourceQuantities fromResources(const Resources& resources);

  // Returns the summed up `ResourceQuantities` given a
  // `hashmap<Key, ResourceQuantities>`.
  template <typename Key>
  static ResourceQuantities sum(const hashmap<Key, ResourceQuantities>& map)
  {
    ResourceQuantities result;

    foreachvalue (const ResourceQuantities& quantities, map) {
      result += quantities;
    }

    return result;
  }

  ResourceQuantities();

  explicit ResourceQuantities(
    const google::protobuf::Map<std::string, Value::Scalar>& map);

  ResourceQuantities(const ResourceQuantities& that) = default;
  ResourceQuantities(ResourceQuantities&& that) = default;

  ResourceQuantities& operator=(const ResourceQuantities& that) = default;
  ResourceQuantities& operator=(ResourceQuantities&& that) = default;

  typedef boost::container::small_vector_base<
      std::pair<std::string, Value::Scalar> >::const_iterator iterator;
  typedef boost::container::small_vector_base<
      std::pair<std::string, Value::Scalar> >::const_iterator const_iterator;

  // NOTE: Non-`const` `iterator`, `begin()` and `end()` are __intentionally__
  // defined with `const` semantics in order to prevent mutation during
  // iteration. Mutation is allowed with the `[]` operator.
  const_iterator begin();
  const_iterator end();

  const_iterator begin() const { return quantities.begin(); }
  const_iterator end() const { return quantities.end(); }

  size_t size() const { return quantities.size(); };

  bool empty() const { return quantities.empty(); }

  // Returns the quantity scalar value if a quantity with the given name.
  // If the given name is absent, return zero.
  Value::Scalar get(const std::string& name) const;

  bool contains(const ResourceQuantities& quantities) const;

  bool operator==(const ResourceQuantities& quantities) const;
  bool operator!=(const ResourceQuantities& quantities) const;

  ResourceQuantities& operator+=(const ResourceQuantities& quantities);
  ResourceQuantities& operator-=(const ResourceQuantities& quantities);

  ResourceQuantities operator+(const ResourceQuantities& quantities) const;
  ResourceQuantities operator-(const ResourceQuantities& quantities) const;

private:
  friend class ResourceLimits;

  void add(const std::string& name, const Value::Scalar& scalar);
  void add(const std::string& name, double value);

  // List of name quantity pairs sorted by name.
  // Arithmetic and comparison operations benefit from this sorting.
  //
  // Pre-allocate space for first-class resources, plus some margins.
  // This needs to be updated as introduce more first-class resources.
  // [cpus, disk, gpus, mem, ports]
  boost::container::small_vector<std::pair<std::string, Value::Scalar>, 7>
    quantities;
};

std::ostream& operator<<(std::ostream& stream, const ResourceQuantities& q);

// An efficient collection of resource limits. All values are guaranteed
// to be non-negative and finite.
//
// E.g. [("cpus", 4.5), ("gpus", 0.1), ("ports", 1000)]
//
// Difference with `class ResourceQuantities`:
// The main difference resides in the semantics of absent entries and, in turn,
// whether zero values are preserved.
//
//   (1) Absent entry in `ResourceQuantities` implies zero quantity. While in
//   `ResourceLimits`, absence implies no limit (i.e. infinite amount). This
//   affects the semantics of the contains operation.
//
//   (2) Zero value preservation: `ResourceLimits` keeps zero value entries
//   while `ResourceQuantities` silently drops them. This is in accordance with
//   the absence semantic. Zero value and absence are equivalent in
//   `ResourceQuantities`. While in `ResourceLimits`, they are not.
class ResourceLimits
{
public:
  // Parse an input string of semicolon separated "name:number" pairs.
  // Entries with zero values will be preserved (unlike `ResourceQuantities`).
  // Duplicate names are NOT allowed in the input, otherwise an `Error` will
  // be returned.
  //
  // Example: "cpus:10;mem:1024;ports:0"
  //          "cpus:10; mem:1024; ports:0"
  // NOTE: we will trim the whitespace around the pair and in the number.
  // However, whitespace in "c p us:10" are preserved and will be parsed to
  // {"c p us", 10}. This is consistent with `Resources::fromSimpleString()`.
  //
  // Numbers must be non-negative and finite, otherwise an `Error`
  // will be returned.
  static Try<ResourceLimits> fromString(const std::string& text);

  ResourceLimits();

  explicit ResourceLimits(
    const google::protobuf::Map<std::string, Value::Scalar>& map);

  ResourceLimits(const ResourceLimits& that) = default;
  ResourceLimits(ResourceLimits&& that) = default;

  ResourceLimits& operator=(const ResourceLimits& that) = default;
  ResourceLimits& operator=(ResourceLimits&& that) = default;

  typedef boost::container::small_vector_base<
      std::pair<std::string, Value::Scalar> >::const_iterator iterator;
  typedef boost::container::small_vector_base<
      std::pair<std::string, Value::Scalar> >::const_iterator const_iterator;

  // NOTE: Non-`const` `iterator`, `begin()` and `end()` are __intentionally__
  // defined with `const` semantics in order to prevent mutation during
  // iteration. Mutation is allowed with the `[]` operator.
  const_iterator begin();
  const_iterator end();

  const_iterator begin() const { return limits.begin(); }
  const_iterator end() const { return limits.end(); }

  size_t size() const { return limits.size(); };

  bool empty() const { return limits.empty(); }

  // Returns the limit of the resource with the given name.
  // If there is no explicit limit for the resource, return `None()`.
  // Note, `None()` implies that the limit of the resource is infinite.
  Option<Value::Scalar> get(const std::string& name) const;

  // Due to the absence-means-infinite semantic of limits, absent entries,
  // intuitively, are considered to contain entries with finite scalar values.
  // For example:
  //    `[ ]`` will always contain any other `ResourceLimits`.
  //    `[("cpu":1)]` contains `[("mem":1)]` and vice versa.
  //    `[("cpu":1)]` will not contain `[("cpu":2)]`.
  bool contains(const ResourceLimits& right) const;

  bool operator==(const ResourceLimits& limits) const;
  bool operator!=(const ResourceLimits& limits) const;

  bool contains(const ResourceQuantities& quantities) const;

  ResourceLimits& operator-=(const ResourceQuantities& quantities);
  ResourceLimits operator-(const ResourceQuantities& quantities) const;

private:
  // Set the limit of the resource with `name` to `scalar`.
  // Note, the existing limit of the resource will be overwritten.
  void set(const std::string& name, const Value::Scalar& scalar);

  // List of name limit pairs sorted by name.
  // Arithmetic and comparison operations benefit from this sorting.
  //
  // Pre-allocate space for first-class resources, plus some margins.
  // This needs to be updated as introduce more first-class resources.
  // [cpus, disk, gpus, mem, ports]
  boost::container::small_vector<std::pair<std::string, Value::Scalar>, 7>
    limits;
};

std::ostream& operator<<(std::ostream& stream, const ResourceLimits& limits);

} // namespace mesos {

#endif //  __COMMON_RESOURCE_QUANTITIES_HPP__


text:
package quasar.physical.marklogic.qscript

import slamdata.Predef.String
import quasar.fp.ski.κ
import quasar.physical.marklogic.cts.Query
import quasar.physical.marklogic.xquery._

import matryoshka._
import scalaz._

private[qscript] final class UnreachablePlanner[M[_]: MonadPlanErr, FMT, F[_], J](
  name: String
) extends Planner[M, FMT, F, J] {

  def plan[Q](implicit Q: Birecursive.Aux[Q, Query[J, ?]]
  ): AlgebraM[M, F, Search[Q] \/ XQuery] =
    κ(MonadPlanErr[M].raiseError(MarkLogicPlannerError.unreachable(name)))
}


text:
go_tenki is a CLI application of weather forecast.

## How to use
### Get source and install
```
$ go get github.com/ken1flan/go_tenki
$ cd $GOPATH/github.com/ken1flan/go_tenki
$ go install
```

### [Get OpenWeatherMap API Key](http://openweathermap.org/appid)

### Copy and edit .envrc with your API key and location info
```
$ cp dot.envrc .envrc
$ vi .envrc
$ source .envrc
```

### Run
```
$ go_tenki
☀ 2.0℃$
```


text:
package com.blazebit.persistence.spring.data.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import com.blazebit.persistence.view.EntityViewSetting;

/**
 * Annotation to let method parameters be bound to the {@link EntityViewSetting}.
 *
 * @author Giovanni Lovato
 * @since 1.3.0
 */
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OptionalParam {

    /**
     * The name of the parameter.
     */
    String value();
}


text:
#pragma once

#include "../oovisualization_api.h"

#include "VisualizationBase/src/items/StaticStyle.h"
#include "VisualizationBase/src/layouts/SequentialLayout.h"
#include "VisualizationBase/src/items/VListStyle.h"

namespace OOVisualization {

class OOVISUALIZATION_API VKeywordMethodCallStyle : public Super<Visualization::ItemStyle>
{
	public:
		void load(Visualization::StyleLoader& sl);

		const Visualization::SequentialLayoutStyle& layout() const;
		const Visualization::StaticStyle& keyword() const;
		const Visualization::VListStyle& arguments() const;

	private:
		Visualization::SequentialLayoutStyle layout_;
		Visualization::StaticStyle keyword_;
		Visualization::VListStyle arguments_;
};

inline const Visualization::SequentialLayoutStyle& VKeywordMethodCallStyle::layout() const { return layout_; }
inline const Visualization::StaticStyle& VKeywordMethodCallStyle::keyword() const { return keyword_; }
inline const Visualization::VListStyle& VKeywordMethodCallStyle::arguments() const { return arguments_; }

}


text:
package org.apache.hadoop.hdfs;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.RollingUpgradeAction;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.SafeModeAction;
import org.apache.hadoop.hdfs.protocol.RollingUpgradeInfo;
import org.apache.hadoop.hdfs.qjournal.MiniJournalCluster;
import org.apache.hadoop.hdfs.qjournal.MiniQJMHACluster;
import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.StartupOption;
import org.apache.hadoop.hdfs.server.datanode.DataNode;
import org.apache.hadoop.hdfs.server.namenode.FSImage;
import org.apache.hadoop.hdfs.server.namenode.NNStorage;
import org.apache.hadoop.hdfs.server.namenode.SecondaryNameNode;
import org.apache.hadoop.hdfs.tools.DFSAdmin;
import org.apache.hadoop.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;

/**
 * This class tests rolling upgrade.
 */
public class TestRollingUpgrade {
  private static final Log LOG = LogFactory.getLog(TestRollingUpgrade.class);

  public static void runCmd(DFSAdmin dfsadmin, boolean success,
      String... args) throws  Exception {
    if (success) {
      Assert.assertEquals(0, dfsadmin.run(args));
    } else {
      Assert.assertTrue(dfsadmin.run(args) != 0);
    }
  }

  /**
   * Test DFSAdmin Upgrade Command.
   */
  @Test
  public void testDFSAdminRollingUpgradeCommands() throws Exception {
    // start a cluster
    final Configuration conf = new HdfsConfiguration();
    MiniDFSCluster cluster = null;
    try {
      cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0).build();
      cluster.waitActive();

      final Path foo = new Path("/foo");
      final Path bar = new Path("/bar");
      final Path baz = new Path("/baz");

      {
        final DistributedFileSystem dfs = cluster.getFileSystem();
        final DFSAdmin dfsadmin = new DFSAdmin(conf);
        dfs.mkdirs(foo);

        //illegal argument "abc" to rollingUpgrade option
        runCmd(dfsadmin, false, "-rollingUpgrade", "abc");

        //query rolling upgrade
        runCmd(dfsadmin, true, "-rollingUpgrade");

        //start rolling upgrade
        dfs.setSafeMode(SafeModeAction.SAFEMODE_ENTER);
        runCmd(dfsadmin, true, "-rollingUpgrade", "prepare");
        dfs.setSafeMode(SafeModeAction.SAFEMODE_LEAVE);

        //query rolling upgrade
        runCmd(dfsadmin, true, "-rollingUpgrade", "query");

        dfs.mkdirs(bar);

        //finalize rolling upgrade
        runCmd(dfsadmin, true, "-rollingUpgrade", "finalize");

        dfs.mkdirs(baz);

        runCmd(dfsadmin, true, "-rollingUpgrade");

        // All directories created before upgrade, when upgrade in progress and
        // after upgrade finalize exists
        Assert.assertTrue(dfs.exists(foo));
        Assert.assertTrue(dfs.exists(bar));
        Assert.assertTrue(dfs.exists(baz));

        dfs.setSafeMode(SafeModeAction.SAFEMODE_ENTER);
        dfs.saveNamespace();
        dfs.setSafeMode(SafeModeAction.SAFEMODE_LEAVE);
      }

      // Ensure directories exist after restart
      cluster.restartNameNode();
      {
        final DistributedFileSystem dfs = cluster.getFileSystem();
        Assert.assertTrue(dfs.exists(foo));
        Assert.assertTrue(dfs.exists(bar));
        Assert.assertTrue(dfs.exists(baz));
      }
    } finally {
      if(cluster != null) cluster.shutdown();
    }
  }

  private static Configuration setConf(Configuration conf, File dir,
      MiniJournalCluster mjc) {
    conf.set(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY, dir.getAbsolutePath());
    conf.set(DFSConfigKeys.DFS_NAMENODE_EDITS_DIR_KEY,
        mjc.getQuorumJournalURI("myjournal").toString());
    conf.setLong(DFSConfigKeys.DFS_NAMENODE_CHECKPOINT_TXNS_KEY, 0L);
    return conf;
  }

  @Test (timeout = 30000)
  public void testRollingUpgradeWithQJM() throws Exception {
    String nnDirPrefix = MiniDFSCluster.getBaseDirectory() + "/nn/";
    final File nn1Dir = new File(nnDirPrefix + "image1");
    final File nn2Dir = new File(nnDirPrefix + "image2");

    LOG.info("nn1Dir=" + nn1Dir);
    LOG.info("nn2Dir=" + nn2Dir);

    final Configuration conf = new HdfsConfiguration();
    final MiniJournalCluster mjc = new MiniJournalCluster.Builder(conf).build();
    setConf(conf, nn1Dir, mjc);

    {
      // Start the cluster once to generate the dfs dirs
      final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf)
        .numDataNodes(0)
        .manageNameDfsDirs(false)
        .checkExitOnShutdown(false)
        .build();
      // Shutdown the cluster before making a copy of the namenode dir to release
      // all file locks, otherwise, the copy will fail on some platforms.
      cluster.shutdown();
    }

    MiniDFSCluster cluster2 = null;
    try {
      // Start a second NN pointed to the same quorum.
      // We need to copy the image dir from the first NN -- or else
      // the new NN will just be rejected because of Namespace mismatch.
      FileUtil.fullyDelete(nn2Dir);
      FileUtil.copy(nn1Dir, FileSystem.getLocal(conf).getRaw(),
          new Path(nn2Dir.getAbsolutePath()), false, conf);

      // Start the cluster again
      final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf)
        .numDataNodes(0)
        .format(false)
        .manageNameDfsDirs(false)
        .checkExitOnShutdown(false)
        .build();

      final Path foo = new Path("/foo");
      final Path bar = new Path("/bar");
      final Path baz = new Path("/baz");

      final RollingUpgradeInfo info1;
      {
        final DistributedFileSystem dfs = cluster.getFileSystem();
        dfs.mkdirs(foo);

        //start rolling upgrade
        dfs.setSafeMode(SafeModeAction.SAFEMODE_ENTER);
        info1 = dfs.rollingUpgrade(RollingUpgradeAction.PREPARE);
        dfs.setSafeMode(SafeModeAction.SAFEMODE_LEAVE);
        LOG.info("START\n" + info1);

        //query rolling upgrade
        Assert.assertEquals(info1, dfs.rollingUpgrade(RollingUpgradeAction.QUERY));

        dfs.mkdirs(bar);
        cluster.shutdown();
      }

      // cluster2 takes over QJM
      final Configuration conf2 = setConf(new Configuration(), nn2Dir, mjc);
      cluster2 = new MiniDFSCluster.Builder(conf2)
        .numDataNodes(0)
        .format(false)
        .manageNameDfsDirs(false)
        .build();
      final DistributedFileSystem dfs2 = cluster2.getFileSystem();

      // Check that cluster2 sees the edits made on cluster1
      Assert.assertTrue(dfs2.exists(foo));
      Assert.assertTrue(dfs2.exists(bar));
      Assert.assertFalse(dfs2.exists(baz));

      //query rolling upgrade in cluster2
      Assert.assertEquals(info1, dfs2.rollingUpgrade(RollingUpgradeAction.QUERY));

      dfs2.mkdirs(baz);

      LOG.info("RESTART cluster 2");
      cluster2.restartNameNode();
      Assert.assertEquals(info1, dfs2.rollingUpgrade(RollingUpgradeAction.QUERY));
      Assert.assertTrue(dfs2.exists(foo));
      Assert.assertTrue(dfs2.exists(bar));
      Assert.assertTrue(dfs2.exists(baz));

      //restart cluster with -upgrade should fail.
      try {
        cluster2.restartNameNode("-upgrade");
      } catch(IOException e) {
        LOG.info("The exception is expected.", e);
      }

      LOG.info("RESTART cluster 2 again");
      cluster2.restartNameNode();
      Assert.assertEquals(info1, dfs2.rollingUpgrade(RollingUpgradeAction.QUERY));
      Assert.assertTrue(dfs2.exists(foo));
      Assert.assertTrue(dfs2.exists(bar));
      Assert.assertTrue(dfs2.exists(baz));

      //finalize rolling upgrade
      final RollingUpgradeInfo finalize = dfs2.rollingUpgrade(
          RollingUpgradeAction.FINALIZE);
      Assert.assertTrue(finalize.isFinalized());

      LOG.info("RESTART cluster 2 with regular startup option");
      cluster2.getNameNodeInfos()[0].setStartOpt(StartupOption.REGULAR);
      cluster2.restartNameNode();
      Assert.assertTrue(dfs2.exists(foo));
      Assert.assertTrue(dfs2.exists(bar));
      Assert.assertTrue(dfs2.exists(baz));
    } finally {
      if (cluster2 != null) cluster2.shutdown();
    }
  }

  @Test
  public void testRollback() throws IOException {
    // start a cluster
    final Configuration conf = new HdfsConfiguration();
    MiniDFSCluster cluster = null;
    try {
      cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0).build();
      cluster.waitActive();

      final Path foo = new Path("/foo");
      final Path bar = new Path("/bar");
      cluster.getFileSystem().mkdirs(foo);

      startRollingUpgrade(foo, bar, cluster);
      cluster.getFileSystem().rollEdits();
      cluster.getFileSystem().rollEdits();
      rollbackRollingUpgrade(foo, bar, cluster);

      startRollingUpgrade(foo, bar, cluster);
      cluster.getFileSystem().rollEdits();
      cluster.getFileSystem().rollEdits();
      rollbackRollingUpgrade(foo, bar, cluster);

      startRollingUpgrade(foo, bar, cluster);
      cluster.restartNameNode();
      rollbackRollingUpgrade(foo, bar, cluster);

      startRollingUpgrade(foo, bar, cluster);
      cluster.restartNameNode();
      rollbackRollingUpgrade(foo, bar, cluster);

      startRollingUpgrade(foo, bar, cluster);
      rollbackRollingUpgrade(foo, bar, cluster);

      startRollingUpgrade(foo, bar, cluster);
      rollbackRollingUpgrade(foo, bar, cluster);
    } finally {
      if(cluster != null) cluster.shutdown();
    }
  }

  private static void startRollingUpgrade(Path foo, Path bar,
      MiniDFSCluster cluster) throws IOException {
    final DistributedFileSystem dfs = cluster.getFileSystem();

    //start rolling upgrade
    dfs.setSafeMode(SafeModeAction.SAFEMODE_ENTER);
    dfs.rollingUpgrade(RollingUpgradeAction.PREPARE);
    dfs.setSafeMode(SafeModeAction.SAFEMODE_LEAVE);

    dfs.mkdirs(bar);

    Assert.assertTrue(dfs.exists(foo));
    Assert.assertTrue(dfs.exists(bar));
  }

  private static void rollbackRollingUpgrade(Path foo, Path bar,
      MiniDFSCluster cluster) throws IOException {
    cluster.restartNameNode("-rollingUpgrade", "rollback");

    final DistributedFileSystem dfs = cluster.getFileSystem();
    Assert.assertTrue(dfs.exists(foo));
    Assert.assertFalse(dfs.exists(bar));
  }

  @Test
  public void testDFSAdminDatanodeUpgradeControlCommands() throws Exception {
    // start a cluster
    final Configuration conf = new HdfsConfiguration();
    MiniDFSCluster cluster = null;
    try {
      cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build();
      cluster.waitActive();
      final DFSAdmin dfsadmin = new DFSAdmin(conf);
      DataNode dn = cluster.getDataNodes().get(0);

      // check the datanode
      final String dnAddr = dn.getDatanodeId().getIpcAddr(false);
      final String[] args1 = {"-getDatanodeInfo", dnAddr};
      Assert.assertEquals(0, dfsadmin.run(args1));

      // issue shutdown to the datanode.
      final String[] args2 = {"-shutdownDatanode", dnAddr, "upgrade" };
      Assert.assertEquals(0, dfsadmin.run(args2));

      // the datanode should be down.
      Thread.sleep(2000);
      Assert.assertFalse("DataNode should exit", dn.isDatanodeUp());

      // ping should fail.
      Assert.assertEquals(-1, dfsadmin.run(args1));
    } finally {
      if (cluster != null) cluster.shutdown();
    }
  }

  @Test (timeout = 300000)
  public void testFinalize() throws Exception {
    final Configuration conf = new HdfsConfiguration();
    MiniQJMHACluster cluster = null;
    final Path foo = new Path("/foo");
    final Path bar = new Path("/bar");

    try {
      cluster = new MiniQJMHACluster.Builder(conf).build();
      MiniDFSCluster dfsCluster = cluster.getDfsCluster();
      dfsCluster.waitActive();

      // let NN1 tail editlog every 1s
      dfsCluster.getConfiguration(1).setInt(
          DFSConfigKeys.DFS_HA_TAILEDITS_PERIOD_KEY, 1);
      dfsCluster.restartNameNode(1);

      dfsCluster.transitionToActive(0);
      DistributedFileSystem dfs = dfsCluster.getFileSystem(0);
      dfs.mkdirs(foo);

      FSImage fsimage = dfsCluster.getNamesystem(0).getFSImage();

      // start rolling upgrade
      RollingUpgradeInfo info = dfs
          .rollingUpgrade(RollingUpgradeAction.PREPARE);
      Assert.assertTrue(info.isStarted());
      dfs.mkdirs(bar);

      queryForPreparation(dfs);

      // The NN should have a copy of the fsimage in case of rollbacks.
      Assert.assertTrue(fsimage.hasRollbackFSImage());

      info = dfs.rollingUpgrade(RollingUpgradeAction.FINALIZE);
      Assert.assertTrue(info.isFinalized());
      Assert.assertTrue(dfs.exists(foo));

      // Once finalized, there should be no more fsimage for rollbacks.
      Assert.assertFalse(fsimage.hasRollbackFSImage());

      // Should have no problem in restart and replaying edits that include
      // the FINALIZE op.
      dfsCluster.restartNameNode(0);
    } finally {
      if (cluster != null) {
        cluster.shutdown();
      }
    }
  }

  @Test (timeout = 300000)
  public void testQuery() throws Exception {
    final Configuration conf = new Configuration();
    MiniQJMHACluster cluster = null;
    try {
      cluster = new MiniQJMHACluster.Builder(conf).build();
      MiniDFSCluster dfsCluster = cluster.getDfsCluster();
      dfsCluster.waitActive();

      dfsCluster.transitionToActive(0);
      DistributedFileSystem dfs = dfsCluster.getFileSystem(0);

      dfsCluster.shutdownNameNode(1);

      // start rolling upgrade
      RollingUpgradeInfo info = dfs
          .rollingUpgrade(RollingUpgradeAction.PREPARE);
      Assert.assertTrue(info.isStarted());

      info = dfs.rollingUpgrade(RollingUpgradeAction.QUERY);
      Assert.assertFalse(info.createdRollbackImages());

      dfsCluster.restartNameNode(1);

      queryForPreparation(dfs);

      // The NN should have a copy of the fsimage in case of rollbacks.
      Assert.assertTrue(dfsCluster.getNamesystem(0).getFSImage()
          .hasRollbackFSImage());
    } finally {
      if (cluster != null) {
        cluster.shutdown();
      }
    }
  }

  @Test (timeout = 300000)
  public void testQueryAfterRestart() throws IOException, InterruptedException {
    final Configuration conf = new Configuration();
    MiniDFSCluster cluster = null;
    try {
      cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0).build();
      cluster.waitActive();
      DistributedFileSystem dfs = cluster.getFileSystem();

      dfs.setSafeMode(SafeModeAction.SAFEMODE_ENTER);
      // start rolling upgrade
      dfs.rollingUpgrade(RollingUpgradeAction.PREPARE);
      queryForPreparation(dfs);
      dfs.setSafeMode(SafeModeAction.SAFEMODE_ENTER);
      dfs.saveNamespace();
      dfs.setSafeMode(SafeModeAction.SAFEMODE_LEAVE);

      cluster.restartNameNodes();
      dfs.rollingUpgrade(RollingUpgradeAction.QUERY);
    } finally {
      if (cluster != null) {
        cluster.shutdown();
      }
    }
  }

  @Test(timeout = 300000)
  public void testCheckpoint() throws IOException, InterruptedException {
    final Configuration conf = new Configuration();
    conf.setInt(DFSConfigKeys.DFS_HA_TAILEDITS_PERIOD_KEY, 1);
    conf.setInt(DFSConfigKeys.DFS_NAMENODE_CHECKPOINT_PERIOD_KEY, 1);

    MiniQJMHACluster cluster = null;
    final Path foo = new Path("/foo");

    try {
      cluster = new MiniQJMHACluster.Builder(conf).build();
      MiniDFSCluster dfsCluster = cluster.getDfsCluster();
      dfsCluster.waitActive();

      dfsCluster.transitionToActive(0);
      DistributedFileSystem dfs = dfsCluster.getFileSystem(0);

      // start rolling upgrade
      RollingUpgradeInfo info = dfs
          .rollingUpgrade(RollingUpgradeAction.PREPARE);
      Assert.assertTrue(info.isStarted());

      queryForPreparation(dfs);

      dfs.mkdirs(foo);
      long txid = dfs.rollEdits();
      Assert.assertTrue(txid > 0);

      int retries = 0;
      while (++retries < 5) {
        NNStorage storage = dfsCluster.getNamesystem(1).getFSImage()
            .getStorage();
        if (storage.getFsImageName(txid - 1) != null) {
          return;
        }
        Thread.sleep(1000);
      }
      Assert.fail("new checkpoint does not exist");

    } finally {
      if (cluster != null) {
        cluster.shutdown();
      }
    }
  }

  static void queryForPreparation(DistributedFileSystem dfs) throws IOException,
      InterruptedException {
    RollingUpgradeInfo info;
    int retries = 0;
    while (++retries < 10) {
      info = dfs.rollingUpgrade(RollingUpgradeAction.QUERY);
      if (info.createdRollbackImages()) {
        break;
      }
      Thread.sleep(1000);
    }

    if (retries >= 10) {
      Assert.fail("Query return false");
    }
  }

  /**
   * In non-HA setup, after rolling upgrade prepare, the Secondary NN should
   * still be able to do checkpoint
   */
  @Test
  public void testCheckpointWithSNN() throws Exception {
    MiniDFSCluster cluster = null;
    DistributedFileSystem dfs = null;
    SecondaryNameNode snn = null;

    try {
      Configuration conf = new HdfsConfiguration();
      cluster = new MiniDFSCluster.Builder(conf).build();
      cluster.waitActive();

      conf.set(DFSConfigKeys.DFS_NAMENODE_SECONDARY_HTTP_ADDRESS_KEY,
          "0.0.0.0:0");
      snn = new SecondaryNameNode(conf);

      dfs = cluster.getFileSystem();
      dfs.mkdirs(new Path("/test/foo"));

      snn.doCheckpoint();

      //start rolling upgrade
      dfs.setSafeMode(SafeModeAction.SAFEMODE_ENTER);
      dfs.rollingUpgrade(RollingUpgradeAction.PREPARE);
      dfs.setSafeMode(SafeModeAction.SAFEMODE_LEAVE);

      dfs.mkdirs(new Path("/test/bar"));
      // do checkpoint in SNN again
      snn.doCheckpoint();
    } finally {
      IOUtils.cleanup(null, dfs);
      if (snn != null) {
        snn.shutdown();
      }
      if (cluster != null) {
        cluster.shutdown();
      }
    }
  }
}


text:
require "fileutils"
mkdir_p File.join(RAILS_ROOT, "app", "javascripts")
touch   File.join(RAILS_ROOT, "app", "javascripts", "application.js")


text:
gnuplot-pingscript
==================

This is a small script which utilizes the ping command and gnuplot to
generate a graph.

Usage
-----

	./gnuplot-pingscript.sh

Enter the needed values when you are prompted to do so.

Another way to use the script is with arguments:

	./gnuplot-pingscript.sh SERVER INTERVAL PING_COUNT PLOT_Y_START IMAGE_OUTPUT_HEIGHT IMAGE_OUTPUT_WIDTH

If you just want to generate the graph for a specific directory which
has a `ping.txt` file in it:

	./gnuplot-pingscript.sh DIRECTORY PLOT_Y_START IMAGE_OUTPUT_HEIGHT IMAGE_OUTPUT_WIDTH