text:
import React from 'react';
import PropTypes from 'prop-types';

import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import { get } from 'lodash';

import ExpensesWithData from '../apps/expenses/components/ExpensesWithData';
import OrdersWithData from '../apps/expenses/components/OrdersWithData';
import ExpensesStatsWithData from '../apps/expenses/components/ExpensesStatsWithData';

import Header from '../components/Header';
import Body from '../components/Body';
import Footer from '../components/Footer';
import CollectiveCover from '../components/CollectiveCover';
import ErrorPage from '../components/ErrorPage';
import CollectivePicker from '../components/CollectivePickerWithData';

import withIntl from '../lib/withIntl';
import withLoggedInUser from '../lib/withLoggedInUser';
import { FormattedMessage } from 'react-intl';

class HostDashboard extends React.Component {
  static propTypes = {
    hostCollectiveSlug: PropTypes.string, // for addData
    LoggedInUser: PropTypes.object,
    data: PropTypes.object, // from addData
  };

  constructor(props) {
    super(props);
    this.state = { selectedCollective: null };
  }

  pickCollective(selectedCollective) {
    this.setState({ selectedCollective });
  }

  render() {
    const { LoggedInUser, data } = this.props;

    if (!data.Collective) return <ErrorPage data={data} />;
    if (!data.Collective.isHost) return <ErrorPage message="collective.is.not.host" />;

    const host = data.Collective;
    const selectedCollective = this.state.selectedCollective || host;
    const includeHostedCollectives = selectedCollective.id === host.id;

    return (

          <CollectiveCover
            collective={host}
            href={`/${host.slug}`}
            className="small"
            style={get(host, 'settings.style.hero.cover')}
          />

          {LoggedInUser && (
            <CollectivePicker
              host={host}
              LoggedInUser={LoggedInUser}
              onChange={selectedCollective => this.pickCollective(selectedCollective)}
            />
          )}

                    <FormattedMessage
                      id="collective.expenses.title"
                      values={{ n: this.totalExpenses }}
                      defaultMessage="{n, plural, one {Latest expense} other {Latest expenses}}"
                    />

                <ExpensesWithData
                  collective={selectedCollective}
                  host={host}
                  includeHostedCollectives={includeHostedCollectives}
                  LoggedInUser={LoggedInUser}
                  filters={true}
                  editable={true}
                />

                    <FormattedMessage
                      id="collective.orders.title"
                      values={{ n: this.totalOrders }}
                      defaultMessage="{n, plural, one {Latest order} other {Latest orders}}"
                    />

                <OrdersWithData
                  collective={selectedCollective}
                  includeHostedCollectives={includeHostedCollectives}
                  filters={true}
                  LoggedInUser={LoggedInUser}
                />

            {this.state.selectedCollective && (

                <ExpensesStatsWithData slug={selectedCollective.slug} />

            )}

    );
  }
}

const getDataQuery = gql`
  query Collective($hostCollectiveSlug: String, $orderBy: CollectiveOrderField, $orderDirection: OrderDirection) {
    Collective(slug: $hostCollectiveSlug) {
      id
      slug
      name
      isHost
      currency
      paymentMethods {
        id
        uuid
        service
        name
        createdAt
        balance
        currency
      }
      collectives(orderBy: $orderBy, orderDirection: $orderDirection) {
        total
        collectives {
          id
          slug
          name
          currency
          hostFeePercent
          stats {
            id
            balance
            expenses {
              id
              all
              pending
              paid
              rejected
              approved
            }
          }
        }
      }
    }
  }
`;

const COLLECTIVES_PER_PAGE = 20;

export const addData = graphql(getDataQuery, {
  options(props) {
    return {
      variables: {
        hostCollectiveSlug: props.hostCollectiveSlug,
        offset: 0,
        limit: props.limit || COLLECTIVES_PER_PAGE * 2,
        includeHostedCollectives: true,
        orderBy: 'name',
        orderDirection: 'ASC',
      },
    };
  },
  props: ({ data }) => ({
    data,
    fetchMore: () => {
      return data.fetchMore({
        variables: {
          offset: data.allCollectives.length,
          limit: COLLECTIVES_PER_PAGE,
        },
        updateQuery: (previousResult, { fetchMoreResult }) => {
          if (!fetchMoreResult) {
            return previousResult;
          }
          return Object.assign({}, previousResult, {
            // Append the new posts results to the old one
            allCollectives: [...previousResult.allCollectives, ...fetchMoreResult.allCollectives],
          });
        },
      });
    },
  }),
});

export default withIntl(withLoggedInUser(addData(HostDashboard)));


text:
<?php

$param = Router::$args[0];

if(isset($param) && in_array($param, array('fbtool', 'admin'))){
    if($param == 'fbtool'){
        $as = 'Customer Account';
        $group = 1;
    }else{
        $as = 'System Administrator';
        $group = 0;
    }
    $args['html']['control'] .= '

as

            <input type="hidden" name="group" value="'.$group.'" />
             '.$as.'

'
    ;
} else {
$args['html']['control'] .= <<<html

as

         <input type="radio" name="group" value="1" /> Customer Account

         <input type="radio" name="group" value="0" /> System Administrator

html
;
}

$args['html']['script'] .= <<
script
;

$args['code']['login'] = function($username,$password){
	$group = intval($_POST['group']);
	if($group == 0)
		// login as system user
		return false;
	else {
            // login as merchant
            $sql = "SELECT id, fullname as name, theme, 'fbtool' as `group` FROM tbl_users
                                                    WHERE email='$username' and password='".md5($password)."'";

            if($user = db_query_one($sql))
                    $_SESSION['user'] = $user;

            return true;
	}
};

redpajama_set_name: RedPajamaGithub


text:
define(['jquery', 'bootstrap', 'backend', 'form', 'table'], function ($, undefined, Backend, Form, Table) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'general/attachment/index',
                    add_url: 'general/attachment/add',
                    edit_url: 'general/attachment/edit',
                    del_url: 'general/attachment/del',
                    multi_url: 'general/attachment/multi',
                    table: 'attachment'
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                sortName: 'id',
                columns: [
                    [
                        {field: 'state', checkbox: true, },
                        {field: 'id', title: __('Id')},
                        {field: 'url', title: __('Preview'), formatter: Controller.api.formatter.thumb},
                        {field: 'url', title: __('Url'), formatter: Controller.api.formatter.url},
                        {field: 'imagewidth', title: __('Imagewidth')},
                        {field: 'imageheight', title: __('Imageheight')},
                        {field: 'imagetype', title: __('Imagetype')},
                        {field: 'storage', title: __('Storage')},
                        {field: 'filesize', title: __('Filesize')},
                        {field: 'mimetype', title: __('Mimetype')},
                        {field: 'createtime', title: __('Createtime'), formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ],
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

        },
        select: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'general/attachment/select',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                sortName: 'id',
                columns: [
                    [
                        {field: 'state', checkbox: true, },
                        {field: 'id', title: __('Id')},
                        {field: 'url', title: __('Preview'), formatter: Controller.api.formatter.thumb},
                        {field: 'imagewidth', title: __('Imagewidth')},
                        {field: 'imageheight', title: __('Imageheight')},
                        {field: 'mimetype', title: __('Mimetype'), operate: 'LIKE %...%',
                            process: function (value, arg) {
                                return value.replace(/\*/g, '%');
                            }},
                        {field: 'createtime', title: __('Createtime'), formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), events: {
                                'click .btn-chooseone': function (e, value, row, index) {
                                    var callback = Backend.api.query('callback');
                                    var id = Backend.api.query('element_id');
                                    var multiple = Backend.api.query('multiple');
                                    multiple = multiple == 'true' ? true : false;
                                    if (id && callback) {
                                        parent.window[callback](id, {url: row.url}, multiple);
                                    }
                                },
                            }, formatter: function () {
                                return ' ' + __('Choose') + '';
                            }}
                    ]
                ]
            });

            // 选中多个
            $(document).on("click", ".btn-choose-multi", function () {
                var callback = Backend.api.query('callback');
                var id = Backend.api.query('element_id');
                var urlArr = new Array();
                $.each(table.bootstrapTable("getAllSelections"), function (i, j) {
                    urlArr.push(j.url);
                });
                parent.window[callback](id, {url: urlArr.join(",")}, true);
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            formatter: {
                thumb: function (value, row, index) {
                    if (row.mimetype.indexOf("image") > -1) {
                        var style = row.storage == 'upyun' ? '!/fwfh/120x90' : '';
                        return '';
                    } else {
                        return '' + __('None') + '';
                    }
                },
                url: function (value, row, index) {
                    return '' + value + '';
                },
            }
        }

    };
    return Controller;
});


text:
package com.alibaba.nacos.auth.context;

import com.alibaba.nacos.auth.config.AuthConfigs;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.plugin.auth.api.IdentityContext;
import com.alibaba.nacos.plugin.auth.constant.Constants;
import com.alibaba.nacos.plugin.auth.spi.server.AuthPluginManager;
import com.alibaba.nacos.plugin.auth.spi.server.AuthPluginService;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;

/**
 * Identity context builder for HTTP.
 *
 * @author Nacos
 */
public class HttpIdentityContextBuilder implements IdentityContextBuilder<HttpServletRequest> {

    private static final String X_FORWARDED_FOR = "X-Forwarded-For";

    private static final String X_FORWARDED_FOR_SPLIT_SYMBOL = ",";

    private final AuthConfigs authConfigs;

    public HttpIdentityContextBuilder(AuthConfigs authConfigs) {
        this.authConfigs = authConfigs;
    }

    /**
     * get identity context from http.
     *
     * @param request user request
     * @return IdentityContext from request context
     */
    @Override
    public IdentityContext build(HttpServletRequest request) {
        IdentityContext result = new IdentityContext();
        getRemoteIp(request, result);
        Optional<AuthPluginService> authPluginService = AuthPluginManager.getInstance()
                .findAuthServiceSpiImpl(authConfigs.getNacosAuthSystemType());
        if (!authPluginService.isPresent()) {
            return result;
        }
        // According to RFC2616, HTTP header and URI is case-insensitive, so use tree map with CASE_INSENSITIVE_ORDER
        // to match the identity key and save the real key in map value.
        Map<String, String> identityNames = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
        for (String each : authPluginService.get().identityNames()) {
            identityNames.put(each, each);
        }
        getIdentityFromHeader(request, result, identityNames);
        getIdentityFromParameter(request, result, identityNames);
        return result;
    }

    private void getIdentityFromHeader(HttpServletRequest request, IdentityContext result,
            Map<String, String> identityNames) {
        Enumeration<String> headerEnu = request.getHeaderNames();
        while (headerEnu.hasMoreElements()) {
            String paraName = headerEnu.nextElement();
            if (identityNames.containsKey(paraName)) {
                result.setParameter(identityNames.get(paraName), request.getHeader(paraName));
            }
        }
    }

    private void getIdentityFromParameter(HttpServletRequest request, IdentityContext result,
            Map<String, String> identityNames) {
        Enumeration<String> paramEnu = request.getParameterNames();
        while (paramEnu.hasMoreElements()) {
            String paraName = paramEnu.nextElement();
            if (identityNames.containsKey(paraName)) {
                result.setParameter(identityNames.get(paraName), request.getParameter(paraName));
            }
        }
    }

    private void getRemoteIp(HttpServletRequest request, IdentityContext result) {
        String remoteIp = StringUtils.EMPTY;
        String xForwardedFor = request.getHeader(X_FORWARDED_FOR);
        if (!StringUtils.isBlank(xForwardedFor)) {
            remoteIp = xForwardedFor.split(X_FORWARDED_FOR_SPLIT_SYMBOL)[0].trim();
        }
        if (StringUtils.isBlank(remoteIp)) {
            String nginxHeader = request.getHeader(Constants.Identity.X_REAL_IP);
            remoteIp = StringUtils.isBlank(nginxHeader) ? request.getRemoteAddr() : nginxHeader;
        }
        result.setParameter(Constants.Identity.REMOTE_IP, remoteIp);
    }
}


text:
package org.sourcepit.common.utils.props;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import java.util.Properties;

public interface PropertiesMap extends Map<String, String>, PropertiesSource
{
   Map<String, String> getDefaultProperties();

   void setBoolean(String key, boolean value);

   void setInt(String key, int value);

   Properties toJavaProperties();

   <K extends Object, V extends Object> void putMap(Map<K, V> map);

   /**
    * @throws IllegalArgumentException if the input stream contains a malformed Unicode escape sequence.
    * @throws IllegalStateException if an error occurred when reading from the input stream.
    */
   void load(InputStream inputStream);

   void load(ClassLoader classLoader, String resourcePath);

   /**
    * @throws IllegalArgumentException if the input stream contains a malformed Unicode escape sequence, or the file
    *            cannot be foud
    * @throws IllegalStateException if an error occurred when reading from the input stream.
    */
   void load(File file);

   void store(File file);

   void store(OutputStream outputStream);
}


text:
package com.intellij.structuralsearch.impl.matcher.predicates;

import com.intellij.psi.*;
import com.intellij.structuralsearch.MalformedPatternException;
import com.intellij.structuralsearch.SSRBundle;
import com.intellij.structuralsearch.StructuralSearchProfile;
import com.intellij.structuralsearch.StructuralSearchUtil;
import com.intellij.structuralsearch.impl.matcher.MatchContext;
import com.intellij.structuralsearch.impl.matcher.MatchResultImpl;
import com.intellij.structuralsearch.impl.matcher.MatchUtils;
import com.intellij.structuralsearch.impl.matcher.handlers.MatchPredicate;
import com.intellij.structuralsearch.plugin.util.SmartPsiPointer;
import org.jetbrains.annotations.NonNls;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * Root of handlers for pattern node matching. Handles simpliest type of the match.
 */
public final class RegExpPredicate extends MatchPredicate {
  private Pattern pattern;
  private final String baseHandlerName;
  private boolean simpleString;
  private final boolean couldBeOptimized;
  private final String regexp;
  private final boolean caseSensitive;
  private boolean multiline;
  private final boolean wholeWords;
  private final boolean target;
  private NodeTextGenerator myNodeTextGenerator;

  public interface NodeTextGenerator {
    String getText(PsiElement element);
  }

  public RegExpPredicate(final String regexp, final boolean caseSensitive, final String _baseHandlerName, boolean _wholeWords, boolean _target) {
    couldBeOptimized = containsRegExp(regexp);
    if (!_wholeWords) {
      simpleString = couldBeOptimized;
    }

    this.regexp = regexp;
    this.caseSensitive = caseSensitive;
    this.wholeWords = _wholeWords;
    baseHandlerName = _baseHandlerName;

    if (!simpleString) {
      compilePattern();
    }
    target = _target;
  }

  private static boolean containsRegExp(final String regexp) {
    for(int i=0;i<regexp.length();++i) {
      if(MatchUtils.SPECIAL_CHARS.indexOf(regexp.charAt(i))!=-1) {
        return false;
      }
    }

    return true;
  }

  private void compilePattern() {
    try {
      @NonNls String realRegexp = regexp;
      if (wholeWords) {
        realRegexp = ".*?\\b(?:" + realRegexp + ")\\b.*?";
      }

      pattern = Pattern.compile(
        realRegexp,
        (caseSensitive ? 0: Pattern.CASE_INSENSITIVE) | (multiline ? Pattern.DOTALL:0)
      );
    } catch(PatternSyntaxException ex) {
      throw new MalformedPatternException(SSRBundle.message("error.incorrect.regexp.constraint", regexp, baseHandlerName));
    }
  }

  public boolean couldBeOptimized() {
    return couldBeOptimized;
  }

  public String getRegExp() {
    return regexp;
  }

  /**
   * Attempts to match given handler node against given node.
   * @param matchedNode for matching
   * @param context of the matching
   * @return true if matching was successfull and false otherwise
   */
  public boolean match(PsiElement node,PsiElement matchedNode, int start, int end, MatchContext context) {
    if (matchedNode==null) return false;
    String text;

    text = myNodeTextGenerator != null ? myNodeTextGenerator.getText(matchedNode) : getMeaningfulText(matchedNode);

    boolean result = doMatch(text, start, end, context, matchedNode);

    if (!result) {

      matchedNode = StructuralSearchUtil.getParentIfIdentifier(matchedNode);

      String alternativeText = context.getPattern().getAlternativeTextToMatch(matchedNode, text);
      if (alternativeText != null) {
        result = doMatch(alternativeText, start, end, context, matchedNode);
      }
    }

    return result;
  }

  public static String getMeaningfulText(PsiElement matchedNode) {
    final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByPsiElement(matchedNode);
    return profile != null ? profile.getMeaningfulText(matchedNode) : matchedNode.getText();
  }

  public boolean match(PsiElement patternNode, PsiElement matchedNode, MatchContext context) {
    return match(patternNode,matchedNode,0,-1,context);
  }

  boolean doMatch(String text, MatchContext context, PsiElement matchedElement) {
    return doMatch(text,0,-1,context, matchedElement);
  }

  boolean doMatch(String text, int from, int end, MatchContext context,PsiElement matchedElement) {
    if (from > 0 || end != -1) {
      text = text.substring(from, end == -1 || end >= text.length() ? text.length():end);
    }

    if (simpleString) {
      return (caseSensitive)?text.equals(regexp):text.equalsIgnoreCase(regexp);
    }

    if(!multiline && text.contains("\n")) setMultiline(true);
    final Matcher matcher = pattern.matcher(text);

    if (matcher.matches()) {
      for (int i=1;i<=matcher.groupCount();++i) {
        context.getResult().addSon(
          new MatchResultImpl(
            baseHandlerName + "_" + i,
            matcher.group(i),
            new SmartPsiPointer(matchedElement),
            matcher.start(i),
            matcher.end(i),
            target
          )
        );
      }
      return true;
    } else {
      return false;
    }
  }

  public void setNodeTextGenerator(final NodeTextGenerator nodeTextGenerator) {
    myNodeTextGenerator = nodeTextGenerator;
  }

  public void setMultiline(boolean b) {
    multiline = b;
    compilePattern();
  }

  public boolean isWholeWords() {
    return wholeWords;
  }
}


text:
<?php

namespace Antares\Form\Controls;

class PasswordType extends AbstractType
{

    /** @var string */
    protected $type = 'password';

}


text:
// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

package jodd.db.connection;

import java.sql.Connection;

/**
 * A generic strategy for obtaining JDBC connections.
 *

 * Implementors might also implement connection pooling.
 *

 * Implementations should provide a public default constructor.
 */
public interface ConnectionProvider extends AutoCloseable {

	/**
	 * Initialize the connection provider. May be called more then once;
	 * does not have any effect if pool is already initialized.
	 */
	void init();

	/**
	 * Returns a connection from connection pool.
	 */
	Connection getConnection();

	/**
	 * Dispose of a used {@link #getConnection() connection}.
	 */
	void closeConnection(Connection connection);

	/**
	 * Closes a provider and releases all its resources.
	 */
	void close();

}


text:
namespace aliyun {
struct CmsQueryListMetricRequestType {
  std::string project;
  std::string metric;
  std::string period;
  std::string start_time;
  std::string end_time;
  std::string dimensions;
  std::string page;
  std::string length;
  std::string extend;
  std::string filter;
};
struct CmsQueryListMetricResponseType {
  std::vector<std::string> datapoints;
  std::string code;
  std::string message;
  std::string success;
  std::string trace_id;
  int next_token;
};
} // end namespace
#endif


text:
require 'chef/provider'
require_relative 'resource_shipyard_agent_application'
require_relative 'provider_shipyard_agent_application'

class Chef
  class Provider
    class ShipyardAgentApplication < Provider
      # A Chef provider for a container-based Shipyard agent install
      #
      # @author Jonathan Hartman <j@p4nt5.com>
      class Container < ShipyardAgentApplication
        def action_create
          image.run_action(:pull)
        end

        def action_delete
          image.run_action(:remove)
        end

        def installed?
          !current_image.tag.nil?
        end

        def version
          current_image.tag
        end

        private

        def current_image
          @current_image ||= Chef::Provider::DockerImage.new(
            Chef::Resource::DockerImage.new(
              new_resource.docker_image, run_context
            ), run_context
          ).load_current_resource
        end

        def image
          @image ||= Chef::Resource::DockerImage.new(new_resource.docker_image,
                                                     run_context)
          @image.tag(new_resource.version)
          @image
        end
      end
    end
  end
end


text:
package com.github.kickshare.ext.service.kickstarter.campaign.impl;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;

import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpResponse;

/**
 * @author Jan.Kucera
 * @since 24.4.2017
 */
public class MockMvcClientHttpRequestFactory implements ClientHttpRequestFactory {
    private ClientHttpRequest mockRequest;
    private ClientHttpResponse mockResponse;

    public MockMvcClientHttpRequestFactory(final InputStream stream) {
        this.mockRequest = mock(ClientHttpRequest.class);
        this.mockResponse = mock(ClientHttpResponse.class);
        try {
            when(mockRequest.execute()).thenReturn(mockResponse);
            when(mockResponse.getBody()).thenReturn(stream);
        } catch (IOException ex) {
            throw new IllegalStateException(ex);
        }
    }

    @Override
    public ClientHttpRequest createRequest(final URI uri, final HttpMethod httpMethod) throws IOException {
        return mockRequest;
    }

}


text:
if ( typeof _  != "function" ) {
	console.log('Lodash was not found and is required by the fontstrap jQuery plugins.');
	var no_lodash = true;
}

$('.js-trigger').click(function (event) {
	event.preventDefault();
});

/*
 * Global helpers for jQuery plugins.
 */

var elementMissing = function (sel, methodName) {
	if ( sel.length === 0 ) {
		console.log('Element does not exist. Did not execute ' + methodName + '. Please check the selector.');
		return true;
	} else {
		return false;
	}
};


text:
package alluxio.client.block.stream;

import java.io.IOException;

/**
 * A {@link BlockInStream} which reads from the given byte array. The stream is able to track how
 * much bytes that have been read from the extended BlockInStream.
 */
public class TestBlockInStream extends BlockInStream {
  /** A field tracks how much bytes read. */
  private int mBytesRead;
  private boolean mClosed;

  public TestBlockInStream(byte[] mData, long id, long length, boolean shortCircuit,
      BlockInStreamSource source) {
    super(new Factory(mData, shortCircuit), source, id, length);
    mBytesRead = 0;
  }

  @Override
  public int read(byte[] b, int off, int len) throws IOException {
    int bytesRead = super.read(b, off, len);
    mBytesRead += bytesRead;
    return bytesRead;
  }

  @Override
  public int positionedRead(long pos, byte[] b, int off, int len) throws IOException {
    int bytesRead = super.positionedRead(pos, b, off, len);
    mBytesRead += bytesRead;
    return bytesRead;
  }

  public boolean isClosed() {
    return mClosed;
  }

  @Override
  public void close() throws IOException {
    mClosed = true;
    super.close();
  }

  /**
   * @return how many bytes been read
   */
  public int getBytesRead() {
    return mBytesRead;
  }

  /**
   * Factory class to create {@link TestPacketReader}s.
   */
  public static class Factory implements PacketReader.Factory {
    private final byte[] mData;
    private final boolean mShortCircuit;

    /**
     * Creates an instance of {@link LocalFilePacketReader.Factory}.
     *
     * @param data the data to serve
     */
    public Factory(byte[] data, boolean shortCircuit) {
      mData = data;
      mShortCircuit = shortCircuit;
    }

    @Override
    public PacketReader create(long offset, long len) {
      return new TestPacketReader(mData, offset, len);
    }

    @Override
    public boolean isShortCircuit() {
      return mShortCircuit;
    }

    @Override
    public void close() {}
  }
}


text:
#region Copyright (c) 2013 James Snape
// <copyright file="ClassWriter.cs" company="James Snape">
//  Copyright 2013 James Snape
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// </copyright>
#endregion

namespace Deeply.Tools.SsisMetadataToClass
{
    using System;
    using System.Collections.Generic;
    using System.IO;

    /// <summary>
    /// Class writer definition.
    /// </summary>
    public class ClassWriter
    {
        /// <summary>
        /// Output options.
        /// </summary>
        private readonly Options options;

        /// <summary>
        /// Output writer.
        /// </summary>
        private readonly TextWriter output;

        /// <summary>
        /// Header format text.
        /// </summary>
        private readonly string headerFormat;

        /// <summary>
        /// Current indent width.
        /// </summary>
        private readonly int indentWidth;

        /// <summary>
        /// Current indent level.
        /// </summary>
        private int indent;

        /// <summary>
        /// Initializes a new instance of the <see cref="ClassWriter"/> class.
        /// </summary>
        /// <param name="options">Output options.</param>
        /// <param name="output">Output writer to send class to.</param>
        /// <param name="headerFormat">Header format text.</param>
        public ClassWriter(Options options, TextWriter output, string headerFormat)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            this.options = options;

            if (output == null)
            {
                throw new ArgumentNullException("output");
            }

            this.output = output;

            if (headerFormat == null)
            {
                throw new ArgumentNullException("headerFormat");
            }

            this.headerFormat = headerFormat;

            this.indentWidth = options.IndentWidth;
        }

        /// <summary>
        /// Gets the current indent string.
        /// </summary>
        private string Indent
        {
            get { return string.Empty.PadRight(this.indent * this.indentWidth); }
        }

        /// <summary>
        /// Helper function to setup the class and write the output.
        /// </summary>
        /// <param name="options">Output options.</param>
        /// <param name="metadata">Sequence of metadata to write.</param>
        /// <param name="output">Output writer to send class to.</param>
        public static void Write(Options options, IEnumerable<SsisMetadata> metadata, TextWriter output)
        {
            string headerFormat = Properties.Settings.Default.HeaderTemplate;

            var writer = new ClassWriter(options, output, headerFormat);
            writer.Write(metadata);
        }

        /// <summary>
        /// Writes the current sequence to the specified output.
        /// </summary>
        /// <param name="metadata">Sequence of metadata to write.</param>
        public void Write(IEnumerable<SsisMetadata> metadata)
        {
            if (metadata == null)
            {
                throw new ArgumentNullException("metadata");
            }

            this.WriteHeader(this.options.ClassName);

            this.WriteBeginNamespace(this.options.NamespaceName);
            ++this.indent;

            this.WriteUsing();
            this.WriteBeginClass(this.options.ClassName);
            ++this.indent;

            this.WriteMetadata(metadata);

            --this.indent;
            this.WriteEndClass();

            --this.indent;
            this.WriteEndNamespace();
        }

        /// <summary>
        /// Writes the metadata as class properties.
        /// </summary>
        /// <param name="metadata">Metadata to write.</param>
        private void WriteMetadata(IEnumerable<SsisMetadata> metadata)
        {
            bool newlineNeeded = false;

            foreach (var item in metadata)
            {
                if (newlineNeeded)
                {
                    this.output.WriteLine();
                }

                this.WriteProperty(item);

                newlineNeeded = true;
            }
        }

        /// <summary>
        /// Writes a single property.
        /// </summary>
        /// <param name="item">Property metadata</param>
        private void WriteProperty(SsisMetadata item)
        {
            this.output.WriteLine("{0}/// <summary>", this.Indent);
            this.output.WriteLine("{0}/// Gets or sets the {1}", this.Indent, item.Name);
            this.output.WriteLine("{0}/// </summary>", this.Indent);
            this.output.WriteLine("{0}public {1} {2} {{ get; set; }}", this.Indent, item.ClrType, item.Name);
        }

        /// <summary>
        /// Writes the file header.
        /// </summary>
        /// <param name="className">Name of the class to be written.</param>
        private void WriteHeader(string className)
        {
            this.output.WriteLine(this.headerFormat, className);
        }

        /// <summary>
        /// Writes a begin namespace.
        /// </summary>
        /// <param name="namespaceName">The class namespace.</param>
        private void WriteBeginNamespace(string namespaceName)
        {
            this.output.WriteLine("namespace {0}", namespaceName);
            this.output.WriteLine("{");
        }

        /// <summary>
        /// Writes the end namespace.
        /// </summary>
        private void WriteEndNamespace()
        {
            this.output.WriteLine("}");
        }

        /// <summary>
        /// Writes the using statements.
        /// </summary>
        private void WriteUsing()
        {
            this.output.WriteLine("{0}using System;", this.Indent);
            this.output.WriteLine();
        }

        /// <summary>
        /// Writes a begin class definition.
        /// </summary>
        /// <param name="className">Name of the class to be written.</param>
        private void WriteBeginClass(string className)
        {
            this.output.WriteLine("{0}/// <summary>", this.Indent);
            this.output.WriteLine("{0}/// <see cref=\"{1}\"/> class definition.", this.Indent, className);
            this.output.WriteLine("{0}/// </summary>", this.Indent);
            this.output.WriteLine("{0}public partial class {1}", this.Indent, className);
            this.output.WriteLine("{0}{{", this.Indent);
        }

        /// <summary>
        /// Writes the end of class.
        /// </summary>
        private void WriteEndClass()
        {
            this.output.WriteLine(this.Indent + "}");
        }
    }
}


text:
package de.geofroggerfx.model;

/**
 * This enum represents the different cache types
 *
 * @author abi
 */
public enum Type {

  TRADITIONAL_CACHE("Traditional Cache"),
  MULTI_CACHE("Multi-cache"),
  UNKNOWN_CACHE("Unknown Cache"),
  EARTH_CACHE("Earthcache"),
  LETTERBOX("Letterbox Hybrid"),
  EVENT("Event Cache"),
  WHERIGO("Wherigo Cache"),
  WEBCAM_CACHE("Webcam Cache"),
  VIRTUAL_CACHE("Virtual Cache"),
  CITO_EVENT("Cache In Trash Out Event"),
  MEGA_EVENT("Mega-Event Cache"),
  MYSTERY_CACHE("Mystery Cache");

  private String groundspeakString;

  private Type(String groundspeakString) {
    this.groundspeakString = groundspeakString;
  }

  public String toGroundspeakString() {
    return groundspeakString;
  }

  public static Type groundspeakStringToType(String groundspeakString) {
    for (Type t: Type.values()) {
      if (t.toGroundspeakString().equals(groundspeakString)) {
        return t;
      }
    }
    throw new IllegalArgumentException("unknown type:"+groundspeakString);
  }

}


text:
class PostsController < ApplicationController
  include TopicsHelper
  load_and_authorize_resource only: [:index, :show]

  before_filter :ensure_topic_exists
  before_filter :pad_post, only: :create
  helper_method :messageboard, :topic
  layout 'application'

  def index
    authorize! :read, topic

    @post = Post.new(
      topic: topic,
      messageboard: messageboard,
      filter: current_user.try(:post_filter)
    )

    @posts = topic
      .posts
      .includes(user: :roles)
      .page(page)

    @read_status = UserTopicRead.find_or_create_by_user_and_topic(current_user, topic, page)

    if not_inside_topic_and_in_an_old_page?
      redirect_to_later_page
    else
      UserTopicRead.update_read_status!(current_user, topic, page)
    end
  end

  def create
    p = topic.posts.create(params[:post])
    redirect_to :back
  end

  def edit
    authorize! :edit, post
  end

  def update
    authorize! :update, post
    post.update_attributes(params[:post])
    redirect_to messageboard_topic_posts_path(messageboard, topic)
  end

  private

  def post
    post = topic.posts.find(params[:post_id])
    @post ||= post
  end

  def not_inside_topic_and_in_an_old_page?
    !internal_to_topic? && page == 1 && @read_status.page > 1
  end

  def page
    params[:page].nil? ? 1 : params[:page].to_i
  end

  def extra_data
    %Q{data-latest-read=#{@read_status.post_id || 0}} if @read_status
  end

  def internal_to_topic?
    referer = request.referer || ''
    referer.include?("#{topic.id}?page=") || (!topic.slug.nil? && referer.include?("#{topic.slug}?page="))
  end

  def redirect_to_later_page
    redirect_to messageboard_topic_posts_path(messageboard, topic, page: @read_status.page)
  end

  def pad_post
    params[:post][:ip] = request.remote_ip
    params[:post][:user] = current_user
    params[:post][:messageboard] = messageboard
  end

  def ensure_topic_exists
    if topic.blank?
      redirect_to default_home,
        flash: { error: 'This topic does not exist.' }
    end
  end
end


text:
class ApplicationController < ActionController::Base
  helper Openseadragon::OpenseadragonHelper
  # Adds a few additional behaviors into the application controller
  include Blacklight::Controller
# Adds Sufia behaviors into the application controller
  include Sufia::Controller

  include Hydra::Controller::ControllerBehavior
  layout 'sufia-one-column'

  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
end


text:
<?php

namespace Recurly;

class AddonList extends Pager
{
  public static function get($planCode, $client = null)
  {
    $list = new AddonList();
    $list->_loadFrom(Client::PATH_PLANS . '/' . rawurlencode($planCode) . Client::PATH_ADDONS, $client);
    return $list;
  }

  protected function getNodeName() {
    return 'add_ons';
  }
}


text:
module BottomUpMergeSort where

import Control.Monad.Writer
import Data.Foldable (foldlM)

type Less a = a -> a -> Bool

data Sortable a = Sortable { _less :: Less a
                           , _size :: Int
                           , _segments :: [[a]] }

instance Show a =>  Show (Sortable a) where
    show (Sortable _ s segs) = "Sortable { _size = " ++ show s
                               ++ ", _segments = " ++ show segs

type ComputationLog a = Writer [String] a

merge :: Less a -> [a] -> [a] -> [a]
merge less = mrg
    where
      mrg [] ys = ys
      mrg xs [] = xs
      mrg (x:xs) (y:ys) = if less x y
                          then x : mrg xs (y:ys)
                          else y : mrg (x:xs) ys

new :: Less a -> ComputationLog (Sortable a)
new less = return $ Sortable { _less = less
                             , _size = 0
                             , _segments = [] }

add :: (Show a) => a -> Sortable a -> ComputationLog (Sortable a)
add x (Sortable l size segs) = do
  let res = Sortable l (size + 1) (addSeg [x] segs size)
  tell $ ["Adding " ++ show x]
  tell $ [show res]
  return res
    where
      addSeg seg segs' size' =
          if size' `mod` 2 == 0
          then seg : segs'
          else addSeg (merge l seg (head segs')) (tail segs') (size' `div` 2)

sort :: Sortable a -> [a]
sort (Sortable l _ segs) = mergeAll [] segs
    where
      mergeAll xs [] = xs
      mergeAll xs (seg:segs') = mergeAll (merge l xs seg) segs'

fromList :: (Ord a, Show a)
         => [a] -> ComputationLog (Sortable a)
fromList xs = (new (<)) >>= \initial -> foldlM (flip add) initial xs

runFromList :: (Ord a, Show a)
            => [a] -> IO ()
runFromList xs = do
  let (sortable, compLog) = runWriter $ fromList xs
  putStrLn "Sortable:"
  print sortable
  putStrLn "Log:"
  forM_ compLog $ \l -> do
    putStrLn l


text:
layout: post
author: batlopez
title: "Nat's Milestones"
---
- [ ] set-up screen with 3 face shapes
- [ ] when user clicks on 1 face, clear off others and center selected
- [ ] place eyes after face is selected in appropriate location
- [ ] When user presses the 'up' arrow, the size of eyes will increase; when user presses the 'down' arrow, size will decrease
- [ ] randomize color of eyes after user clicks enter
- [ ] place mouth after user clicks enter
- [ ] When user presses the 'up' arrow, the mouth will smile; when user presses the 'down' arrow, mouth will frown
- [ ] when user clicks enter, randomly change color of screen between 4 different colors


text:
import { combineReducers } from 'redux';
import scheduleStatus from './scheduleStatus';
import getModuleStatusReducer from '../../lib/getModuleStatusReducer';

export function getMeetingInfoReducer(types) {
  return (state = null, { type, meeting = null }) => {
    switch (type) {
      case types.updateMeeting: return meeting;
      case types.clearMeeting: return null;
      default: return state;
    }
  };
}

export function getMeetingSchedulingStatusReducer(types) {
  return (state = scheduleStatus.idle, { type }) => {
    switch (type) {
      case types.initScheduling:
        return scheduleStatus.scheduling;
      case types.scheduled:
        return scheduleStatus.scheduled;
      case types.resetScheduling:
        return scheduleStatus.idle;
      default: return state;
    }
  };
}

export function getMeetingStorageReducer(types) {
  return (state = {}, { type, meeting = null }) => {
    switch (type) {
      case types.scheduled:
        return meeting ? {
          startHostVideo: meeting.startHostVideo,
          startParticipantsVideo: meeting.startParticipantsVideo,
          allowJoinBeforeHost: meeting.allowJoinBeforeHost,
          audioOptions: meeting.audioOptions,
          _saved: meeting._saved,
        } : {};
      default: return state;
    }
  };
}

export default types => combineReducers({
  status: getModuleStatusReducer(types),
  meeting: getMeetingInfoReducer(types),
  schedulingStatus: getMeetingSchedulingStatusReducer(types)
});


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">
<link href="./navmenu.css" rel="stylesheet">

Home

Portfolio

About

Blog

Contact

<input type="checkbox" id="nav-trigger" class="nav-trigger" />

	No traffic limits or throttling. Files are served via StackPath's super fast global CDN.

Use a specific tag or commit hash in the URL (not a branch). Files are cached permanently based on the URL. Query strings are ignored.

The catch: this is a free service, so there are no uptime or support guarantees.

Use this URL for development

https://rawgit.com/google/material-design-icons/master/navigation/svg/production/ic_menu_36px.svg

New changes you push to GitHub will be reflected within minutes.

Excessive traffic will be throttled and blacklisted.

If excessive traffic continues, RawGit will display a prominent error message on your website to try to get your attention.


text:
{% extends "navbar.html" %}
{% block head %}
<title>Home | wedge</title>
{% endblock %}
{% block content %}

	{% if session.username %}

Welcome, {{ session.username }}!

Welcome to wedge, the Wikipedia game.

{{ session.username }}'s stats at a glance:

Your number of edits (that wedge knows of): {{ len(get_edits(session.uid)) }}

Total number of edits (by wedge users): {{ len(get_edits()) }}

Your total score: {{ round(get_total_score(session.uid), 1) }}

Your average score for a single edit: {{ round(get_avg_score(session.uid), 1) }}

	{% else %}

What is wedge?

wedge makes Wikipedia editing more fun. It analyzes your edits and rates
				   them by how constructive they are, and awards you points correspondingly.
				   Track your progress by getting instant feedback on your edits, and rack up
				   achievements as your points increase. So join today, and become an active
				   and helpful contributor to Wikipedia while competing with other wedge
				   users to be the most constructive!

	{% endif %}

Top 10 Leaderboard

					Username
					Score

			{% for i in lb %}

					{{ i[0] }}
					{{ round(i[1], 1) }}

			{% endfor %}

{% endblock %}


text:
package com.huawei.ism.openapi.remotedevice;

import com.huawei.ism.openapi.common.batchquery.QueryBase;

public class RemoteDeviceQuery extends QueryBase<RemoteDeviceMO>
{
    /**
     * 批量查询条件
     * @param mo 批量查询条件
     * @param index 起始索引
     * @param count 查询数量
     */
    public RemoteDeviceQuery(RemoteDeviceMO mo, long index, long count)
    {
        super(mo, index, count);
    }

    /**
     * 设置批量查询条件
     * @param mo 批量查询条件
     */
    public void setQueryRemoteDeviceMO(RemoteDeviceMO mo)
    {
        setConcretQueryMO(mo);
    }

    public RemoteDeviceMO getRemoteDeviceMO()
    {
        return getConcretMO();
    }
}


text:
@interface CMFGalleryCell : UICollectionViewCell

@property (nonatomic, strong) NSString *imageName;

-(void)updateCell;

@end


text:
package TripleT;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;

/**
 * The first level of the game.
 * @author Owen Jow
 */
public class Level1 extends LevelPanel {
    private static final int KIRBY_INITIAL_Y = 330;

    /**
     * A no-argument constructor for Level1.
     * Constructs a Kirby to act as the controllable character for the level.
     */
    public Level1() {
        // Foreground data (incl. construction of foreground Rectangle objects)
        foreground = new Foreground(Images.get("demoForeground"), 260, 1006, new Rectangle[] {
            new Rectangle(0, 355, 1006, 82), /* the ground (to begin with) */
            new Rectangle(282, 339, 28, 20), /* first bump in the road */
            new Rectangle(537, 339, 96, 20), /* second bump in the road */
            new Rectangle(697, 339, 309, 20), /* the long elevated part at the end */
            new Rectangle(793, 273, 31, 86), /* the tall part of the hedge-like block at the end */
            new Rectangle(823, 305, 17, 53) /* the short part of the hedge-like block at the end */
        });
        fgImage = foreground.img;

        isLeft = true; // this level is a LEFT level

        kirby = new Kirby(0, KIRBY_INITIAL_Y);
        backgroundImg = Images.get("demoBackground");
    }

    @Override
    protected void reset() {
        super.reset();
        kirby = new Kirby(0, KIRBY_INITIAL_Y);
        foreground.reset();
    }

    @Override
    public void initializeDoors() {
        // There's only one in this level
        doors.add(new Door(967, GameState.level2, "level2", isLeft));
    }

    @Override
    protected void drawForeground(Graphics2D g2) {
        g2.drawImage(fgImage, (int) foreground.leftOffset,
                foreground.origTop + (int) foreground.topOffset, null);
        kirby.drawImage(g2);
    }
}


text:
import { DiplomaPage } from './app.po';

describe('diploma App', () => {
  let page: DiplomaPage;

  beforeEach(() => {
    page = new DiplomaPage();
  });

  it('should display message saying app works', () => {
    page.navigateTo();
    expect(page.getParagraphText()).toEqual('app works!');
  });
});


text:
import namespaces from 'config/namespaces';
import booleanAttributes from 'config/booleanAttributes';

// the property name equivalents for element attributes, where they differ
// from the lowercased attribute name
var propertyNames = {
	'accept-charset': 'acceptCharset',
	accesskey: 'accessKey',
	bgcolor: 'bgColor',
	'class': 'className',
	codebase: 'codeBase',
	colspan: 'colSpan',
	contenteditable: 'contentEditable',
	datetime: 'dateTime',
	dirname: 'dirName',
	'for': 'htmlFor',
	'http-equiv': 'httpEquiv',
	ismap: 'isMap',
	maxlength: 'maxLength',
	novalidate: 'noValidate',
	pubdate: 'pubDate',
	readonly: 'readOnly',
	rowspan: 'rowSpan',
	tabindex: 'tabIndex',
	usemap: 'useMap'
};

export default function ( attribute, options ) {
	var propertyName;

	if ( attribute.pNode && !attribute.namespace && ( !options.pNode.namespaceURI || options.pNode.namespaceURI === namespaces.html ) ) {
		propertyName = propertyNames[ attribute.name ] || attribute.name;

		if ( options.pNode[ propertyName ] !== undefined ) {
			attribute.propertyName = propertyName;
		}

		// is attribute a boolean attribute or 'value'? If so we're better off doing e.g.
		// node.selected = true rather than node.setAttribute( 'selected', '' )
		if ( booleanAttributes.test( propertyName ) || propertyName === 'value' ) {
			attribute.useProperty = true;
		}
	}
}


text:
package chemkin_wrappers;

import util.Paths;

/**
 * Decorator for {@link AbstractChemkinRoutine} that calls the routine "CKReactorPlugFlow" of Chemkin.
 *
 * Corresponds to PFR model.
 * @author Nick
 *
 */
public class PFRDecorator extends ChemkinRoutineDecorator {

	public PFRDecorator(AbstractChemkinRoutine routine){
		super.routine = routine;
	}

	@Override
	public String[] getKeyword() {

		routine.keywords = new String [5];
		routine.keywords[0] = Paths.getBinDirLocation()+"CKReactorPlugFlow";
		routine.keywords[1] = "-i";
		routine.keywords[2] = getReactorDir()+getReactorSetup();
		routine.keywords[3] = "-o";
		routine.keywords[4] = getReactorDir()+getReactorOut();

		return routine.keywords;
	}

	@Override
	public void executeCKRoutine() {
		this.getKeyword();
		routine.executeCKRoutine();

	}

}


text:
package com.exalttech.trex.remote.models.common;

import com.exalttech.trex.remote.models.params.Params;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import javax.annotation.Generated;

/**
 * RPC request model
 *
 * @author GeorgeKh
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
@JsonPropertyOrder({
    "id",
    "jsonrpc",
    "method",
    "params"
})
public class RPCRequest {

    @JsonProperty("id")
    private String id;
    @JsonProperty("jsonrpc")
    private String jsonrpc = "2.0";
    @JsonProperty("method")
    private String method;
    @JsonProperty("params")
    private Params params;

    /**
     *
     * @return The id
     */
    @JsonProperty("id")
    public String getId() {
        return id;
    }

    /**
     *
     * @param id The id
     */
    @JsonProperty("id")
    public void setId(String id) {
        this.id = id;
    }

    /**
     *
     * @return The jsonrpc
     */
    @JsonProperty("jsonrpc")
    public String getJsonrpc() {
        return jsonrpc;
    }

    /**
     *
     * @param jsonrpc The jsonrpc
     */
    @JsonProperty("jsonrpc")
    public void setJsonrpc(String jsonrpc) {
        this.jsonrpc = jsonrpc;
    }

    /**
     *
     * @return The method
     */
    @JsonProperty("method")
    public String getMethod() {
        return method;
    }

    /**
     *
     * @param method The method
     */
    @JsonProperty("method")
    public void setMethod(String method) {
        this.method = method;
    }

    /**
     *
     * @return The params
     */
    @JsonProperty("params")
    public Params getParams() {
        return params;
    }

    /**
     *
     * @param params The params
     */
    @JsonProperty("params")
    public void setParams(Params params) {
        this.params = params;
    }

    @Override
    public String toString() {
        return "RPCRequest{" + "id=" + id + ", jsonrpc=" + jsonrpc + ", method=" + method + ", params=" + params + '}';
    }

}


text:
package server

import (
	"context"
	"crypto"
	"database/sql"
	"fmt"
	"io"
	"math"
	"net"
	"net/http"
	"net/http/pprof"
	"sort"
	"strings"
	"time"

	"github.com/gofrs/uuid"
	jwt "github.com/golang-jwt/jwt/v4"
	"github.com/gorilla/handlers"
	"github.com/gorilla/mux"
	grpcgw "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
	"github.com/heroiclabs/nakama/v3/console"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/encoding/protojson"
)

// Lists API methods and the minimum role required to access them
var restrictedMethods = map[string]console.UserRole{
	// Account
	"/nakama.console.Console/BanAccount":         console.UserRole_USER_ROLE_MAINTAINER,
	"/nakama.console.Console/UnbanAccount":       console.UserRole_USER_ROLE_MAINTAINER,
	"/nakama.console.Console/DeleteAccount":      console.UserRole_USER_ROLE_MAINTAINER,
	"/nakama.console.Console/DeleteAccounts":     console.UserRole_USER_ROLE_DEVELOPER,
	"/nakama.console.Console/DeleteFriend":       console.UserRole_USER_ROLE_MAINTAINER,
	"/nakama.console.Console/DeleteGroupUser":    console.UserRole_USER_ROLE_MAINTAINER,
	"/nakama.console.Console/DeleteWalletLedger": console.UserRole_USER_ROLE_MAINTAINER,
	"/nakama.console.Console/ExportAccount":      console.UserRole_USER_ROLE_MAINTAINER,
	"/nakama.console.Console/GetAccount":         console.UserRole_USER_ROLE_READONLY,
	"/nakama.console.Console/GetFriends":         console.UserRole_USER_ROLE_READONLY,
	"/nakama.console.Console/GetGroups":          console.UserRole_USER_ROLE_READONLY,
	"/nakama.console.Console/GetWalletLedger":    console.UserRole_USER_ROLE_READONLY,
	"/nakama.console.Console/ListAccounts":       console.UserRole_USER_ROLE_READONLY,
	"/nakama.console.Console/UpdateAccount":      console.UserRole_USER_ROLE_MAINTAINER,

	// API Explorer
	"/nakama.console.Console/CallRpcEndpoint":  console.UserRole_USER_ROLE_DEVELOPER,
	"/nakama.console.Console/CallApiEndpoint":  console.UserRole_USER_ROLE_DEVELOPER,
	"/nakama.console.Console/ListApiEndpoints": console.UserRole_USER_ROLE_DEVELOPER,

	// Config
	"/nakama.console.Console/GetConfig":     console.UserRole_USER_ROLE_DEVELOPER,
	"/nakama.console.Console/DeleteAllData": console.UserRole_USER_ROLE_DEVELOPER,

	// Group
	"/nakama.console.Console/ListGroups":         console.UserRole_USER_ROLE_READONLY,
	"/nakama.console.Console/DeleteGroup":        console.UserRole_USER_ROLE_MAINTAINER,
	"/nakama.console.Console/GetGroup":           console.UserRole_USER_ROLE_READONLY,
	"/nakama.console.Console/ExportGroup":        console.UserRole_USER_ROLE_MAINTAINER,
	"/nakama.console.Console/UpdateGroup":        console.UserRole_USER_ROLE_MAINTAINER,
	"/nakama.console.Console/GetMembers":         console.UserRole_USER_ROLE_READONLY,
	"/nakama.console.Console/DemoteGroupMember":  console.UserRole_USER_ROLE_MAINTAINER,
	"/nakama.console.Console/PromoteGroupMember": console.UserRole_USER_ROLE_MAINTAINER,

	// Leaderboard
	"/nakama.console.Console/ListLeaderboards":        console.UserRole_USER_ROLE_READONLY,
	"/nakama.console.Console/GetLeaderboard":          console.UserRole_USER_ROLE_READONLY,
	"/nakama.console.Console/ListLeaderboardRecords":  console.UserRole_USER_ROLE_READONLY,
	"/nakama.console.Console/DeleteLeaderboard":       console.UserRole_USER_ROLE_DEVELOPER,
	"/nakama.console.Console/DeleteLeaderboardRecord": console.UserRole_USER_ROLE_MAINTAINER,

	// Match
	"/nakama.console.Console/ListMatches":   console.UserRole_USER_ROLE_READONLY,
	"/nakama.console.Console/GetMatchState": console.UserRole_USER_ROLE_READONLY,

	// Channel messages
	"/nakama.console.Console/ListChannelMessages":   console.UserRole_USER_ROLE_READONLY,
	"/nakama.console.Console/DeleteChannelMessages": console.UserRole_USER_ROLE_MAINTAINER,

	// Purchase
	"/nakama.console.Console/ListPurchases": console.UserRole_USER_ROLE_READONLY,

	// Runtime
	"/nakama.console.Console/GetRuntime": console.UserRole_USER_ROLE_DEVELOPER,

	// Status
	"/nakama.console.Console/GetStatus": console.UserRole_USER_ROLE_READONLY,

	// Storage
	"/nakama.console.Console/DeleteStorage":          console.UserRole_USER_ROLE_DEVELOPER,
	"/nakama.console.Console/DeleteStorageObject":    console.UserRole_USER_ROLE_MAINTAINER,
	"/nakama.console.Console/GetStorage":             console.UserRole_USER_ROLE_READONLY,
	"/nakama.console.Console/ListStorageCollections": console.UserRole_USER_ROLE_READONLY,
	"/nakama.console.Console/ListStorage":            console.UserRole_USER_ROLE_READONLY,
	"/nakama.console.Console/WriteStorageObject":     console.UserRole_USER_ROLE_MAINTAINER,

	// Unlink
	"/nakama.console.Console/UnlinkApple":               console.UserRole_USER_ROLE_MAINTAINER,
	"/nakama.console.Console/UnlinkCustom":              console.UserRole_USER_ROLE_MAINTAINER,
	"/nakama.console.Console/UnlinkDevice":              console.UserRole_USER_ROLE_MAINTAINER,
	"/nakama.console.Console/UnlinkEmail":               console.UserRole_USER_ROLE_MAINTAINER,
	"/nakama.console.Console/UnlinkFacebook":            console.UserRole_USER_ROLE_MAINTAINER,
	"/nakama.console.Console/UnlinkFacebookInstantGame": console.UserRole_USER_ROLE_MAINTAINER,
	"/nakama.console.Console/UnlinkGameCenter":          console.UserRole_USER_ROLE_MAINTAINER,
	"/nakama.console.Console/UnlinkGoogle":              console.UserRole_USER_ROLE_MAINTAINER,
	"/nakama.console.Console/UnlinkSteam":               console.UserRole_USER_ROLE_MAINTAINER,

	// User
	"/nakama.console.Console/AddUser":    console.UserRole_USER_ROLE_ADMIN,
	"/nakama.console.Console/DeleteUser": console.UserRole_USER_ROLE_ADMIN,
	"/nakama.console.Console/ListUsers":  console.UserRole_USER_ROLE_ADMIN,
}

type ctxConsoleUsernameKey struct{}
type ctxConsoleEmailKey struct{}
type ctxConsoleRoleKey struct{}

type ConsoleServer struct {
	console.UnimplementedConsoleServer
	logger               *zap.Logger
	db                   *sql.DB
	config               Config
	tracker              Tracker
	router               MessageRouter
	streamManager        StreamManager
	metrics              Metrics
	sessionCache         SessionCache
	consoleSessionCache  SessionCache
	loginAttemptCache    LoginAttemptCache
	statusRegistry       *StatusRegistry
	matchRegistry        MatchRegistry
	statusHandler        StatusHandler
	runtimeInfo          *RuntimeInfo
	configWarnings       map[string]string
	serverVersion        string
	ctxCancelFn          context.CancelFunc
	grpcServer           *grpc.Server
	grpcGatewayServer    *http.Server
	leaderboardCache     LeaderboardCache
	leaderboardRankCache LeaderboardRankCache
	leaderboardScheduler LeaderboardScheduler
	api                  *ApiServer
	rpcMethodCache       *rpcReflectCache
	cookie               string
	httpClient           *http.Client
}

func StartConsoleServer(logger *zap.Logger, startupLogger *zap.Logger, db *sql.DB, config Config, tracker Tracker, router MessageRouter, streamManager StreamManager, metrics Metrics, sessionCache SessionCache, consoleSessionCache SessionCache, loginAttemptCache LoginAttemptCache, statusRegistry *StatusRegistry, statusHandler StatusHandler, runtimeInfo *RuntimeInfo, matchRegistry MatchRegistry, configWarnings map[string]string, serverVersion string, leaderboardCache LeaderboardCache, leaderboardRankCache LeaderboardRankCache, leaderboardScheduler LeaderboardScheduler, api *ApiServer, cookie string) *ConsoleServer {
	var gatewayContextTimeoutMs string
	if config.GetConsole().IdleTimeoutMs > 500 {
		// Ensure the GRPC Gateway timeout is just under the idle timeout (if possible) to ensure it has priority.
		gatewayContextTimeoutMs = fmt.Sprintf("%vm", config.GetConsole().IdleTimeoutMs-500)
	} else {
		gatewayContextTimeoutMs = fmt.Sprintf("%vm", config.GetConsole().IdleTimeoutMs)
	}

	serverOpts := []grpc.ServerOption{
		//grpc.StatsHandler(&ocgrpc.ServerHandler{IsPublicEndpoint: true}),
		grpc.MaxRecvMsgSize(int(config.GetConsole().MaxMessageSizeBytes)),
		grpc.UnaryInterceptor(consoleInterceptorFunc(logger, config, consoleSessionCache)),
	}
	grpcServer := grpc.NewServer(serverOpts...)

	ctx, ctxCancelFn := context.WithCancel(context.Background())

	s := &ConsoleServer{
		logger:               logger,
		db:                   db,
		config:               config,
		tracker:              tracker,
		router:               router,
		streamManager:        streamManager,
		metrics:              metrics,
		sessionCache:         sessionCache,
		consoleSessionCache:  consoleSessionCache,
		loginAttemptCache:    loginAttemptCache,
		statusRegistry:       statusRegistry,
		matchRegistry:        matchRegistry,
		statusHandler:        statusHandler,
		configWarnings:       configWarnings,
		serverVersion:        serverVersion,
		ctxCancelFn:          ctxCancelFn,
		grpcServer:           grpcServer,
		runtimeInfo:          runtimeInfo,
		leaderboardCache:     leaderboardCache,
		leaderboardRankCache: leaderboardRankCache,
		leaderboardScheduler: leaderboardScheduler,
		api:                  api,
		cookie:               cookie,
		httpClient:           &http.Client{Timeout: 5 * time.Second},
	}

	if err := s.initRpcMethodCache(); err != nil {
		startupLogger.Fatal("Console server failed to initialize rpc method reflection cache", zap.Error(err))
	}

	console.RegisterConsoleServer(grpcServer, s)
	startupLogger.Info("Starting Console server for gRPC requests", zap.Int("port", config.GetConsole().Port-3))
	go func() {
		listener, err := net.Listen("tcp", fmt.Sprintf("%v:%d", config.GetConsole().Address, config.GetConsole().Port-3))
		if err != nil {
			startupLogger.Fatal("Console server listener failed to start", zap.Error(err))
		}

		if err := grpcServer.Serve(listener); err != nil {
			startupLogger.Fatal("Console server listener failed", zap.Error(err))
		}
	}()

	grpcGateway := grpcgw.NewServeMux(
		grpcgw.WithUnescapingMode(grpcgw.UnescapingModeAllExceptReserved),
		grpcgw.WithMarshalerOption(grpcgw.MIMEWildcard, &grpcgw.HTTPBodyMarshaler{
			Marshaler: &grpcgw.JSONPb{
				MarshalOptions: protojson.MarshalOptions{
					UseProtoNames:   true,
					UseEnumNumbers:  true,
					EmitUnpopulated: true,
				},
				UnmarshalOptions: protojson.UnmarshalOptions{
					DiscardUnknown: true,
				},
			},
		}),
	)

	dialAddr := fmt.Sprintf("127.0.0.1:%d", config.GetConsole().Port-3)
	if config.GetConsole().Address != "" {
		dialAddr = fmt.Sprintf("%v:%d", config.GetConsole().Address, config.GetConsole().Port-3)
	}
	dialOpts := []grpc.DialOption{
		grpc.WithDefaultCallOptions(
			grpc.MaxCallSendMsgSize(int(config.GetConsole().MaxMessageSizeBytes)),
			grpc.MaxCallRecvMsgSize(math.MaxInt32),
		),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
	}
	if err := console.RegisterConsoleHandlerFromEndpoint(ctx, grpcGateway, dialAddr, dialOpts); err != nil {
		startupLogger.Fatal("Console server gateway registration failed", zap.Error(err))
	}

	grpcGatewayRouter := mux.NewRouter()
	grpcGatewayRouter.HandleFunc("/v2/console/storage/import", s.importStorage)

	// Register public subscription callback endpoints
	if config.GetIAP().Apple.NotificationsEndpointId != "" {
		endpoint := fmt.Sprintf("/v2/console/apple/subscriptions/%s", config.GetIAP().Apple.NotificationsEndpointId)
		grpcGatewayRouter.HandleFunc(endpoint, appleNotificationHandler(logger, db))
		logger.Info("Registered endpoint for Apple subscription notifications callback", zap.String("endpoint", endpoint))
	}

	if config.GetIAP().Google.NotificationsEndpointId != "" {
		endpoint := fmt.Sprintf("/v2/console/google/subscriptions/%s", config.GetIAP().Google.NotificationsEndpointId)
		grpcGatewayRouter.HandleFunc(endpoint, googleNotificationHandler(logger, db, config.GetIAP().Google))
		logger.Info("Registered endpoint for Google subscription notifications callback", zap.String("endpoint", endpoint))
	}

	// TODO: Register Huawei callbacks

	// pprof routes
	grpcGatewayRouter.Handle("/debug/pprof/", adminBasicAuth(config.GetConsole())(http.HandlerFunc(pprof.Index)))
	grpcGatewayRouter.Handle("/debug/pprof/cmdline", adminBasicAuth(config.GetConsole())(http.HandlerFunc(pprof.Cmdline)))
	grpcGatewayRouter.Handle("/debug/pprof/profile", adminBasicAuth(config.GetConsole())(http.HandlerFunc(pprof.Profile)))
	grpcGatewayRouter.Handle("/debug/pprof/symbol", adminBasicAuth(config.GetConsole())(http.HandlerFunc(pprof.Symbol)))
	grpcGatewayRouter.Handle("/debug/pprof/trace", adminBasicAuth(config.GetConsole())(http.HandlerFunc(pprof.Trace)))
	grpcGatewayRouter.Handle("/debug/pprof/{profile}", adminBasicAuth(config.GetConsole())(http.HandlerFunc(pprof.Index)))

	// Enable max size check on requests coming arriving the gateway.
	// Enable compression on responses sent by the gateway.
	handlerWithCompressResponse := handlers.CompressHandler(grpcGateway)
	maxMessageSizeBytes := config.GetConsole().MaxMessageSizeBytes
	handlerWithMaxBody := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Check max body size before decompressing incoming request body.
		r.Body = http.MaxBytesReader(w, r.Body, maxMessageSizeBytes)
		handlerWithCompressResponse.ServeHTTP(w, r)
	})
	grpcGatewayRouter.NewRoute().PathPrefix("/v2").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Ensure some headers have required values.
		// Override any value set by the client if needed.
		r.Header.Set("Grpc-Timeout", gatewayContextTimeoutMs)

		// Allow GRPC Gateway to handle the request.
		handlerWithMaxBody.ServeHTTP(w, r)
	})
	registerDashboardHandlers(logger, grpcGatewayRouter)

	// Enable CORS on all requests.
	CORSHeaders := handlers.AllowedHeaders([]string{"Authorization", "Content-Type", "User-Agent"})
	CORSOrigins := handlers.AllowedOrigins([]string{"*"})
	CORSMethods := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "DELETE", "PATCH"})
	handlerWithCORS := handlers.CORS(CORSHeaders, CORSOrigins, CORSMethods)(grpcGatewayRouter)

	// Set up and start GRPC Gateway server.
	s.grpcGatewayServer = &http.Server{
		Addr:         fmt.Sprintf("%v:%d", config.GetConsole().Address, config.GetConsole().Port),
		ReadTimeout:  time.Millisecond * time.Duration(int64(config.GetConsole().ReadTimeoutMs)),
		WriteTimeout: time.Millisecond * time.Duration(int64(config.GetConsole().WriteTimeoutMs)),
		IdleTimeout:  time.Millisecond * time.Duration(int64(config.GetConsole().IdleTimeoutMs)),
		Handler:      handlerWithCORS,
	}

	startupLogger.Info("Starting Console server gateway for HTTP requests", zap.Int("port", config.GetConsole().Port))
	go func() {
		if err := s.grpcGatewayServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			startupLogger.Fatal("Console server gateway listener failed", zap.Error(err))
		}
	}()

	// Run a background process to periodically refresh storage collection names.
	go func() {
		// Refresh function to update cache and return a delay until the next refresh should run.
		refreshFn := func() *time.Timer {
			startAt := time.Now()

			// Load all distinct collections from database.
			collections := make([]string, 0, 10)

			query := `
WITH RECURSIVE t AS (
   (SELECT collection FROM storage ORDER BY collection LIMIT 1)  -- Parentheses required, do not remove.
   UNION ALL
   SELECT (SELECT collection FROM storage WHERE collection > t.collection ORDER BY collection LIMIT 1)
   FROM t
   WHERE t.collection IS NOT NULL
   )
SELECT collection FROM t WHERE collection IS NOT NULL`
			rows, err := s.db.QueryContext(ctx, query)
			if err != nil {
				s.logger.Error("Error querying storage collections.", zap.Error(err))
				return time.NewTimer(time.Minute)
			}
			for rows.Next() {
				var dbCollection string
				if err := rows.Scan(&dbCollection); err != nil {
					_ = rows.Close()
					s.logger.Error("Error scanning storage collections.", zap.Error(err))
					return time.NewTimer(time.Minute)
				}
				collections = append(collections, dbCollection)
			}
			_ = rows.Close()

			sort.Strings(collections)
			collectionSetCache.Store(collections)

			elapsed := time.Now().Sub(startAt)
			elapsed *= 20
			if elapsed < time.Minute {
				elapsed = time.Minute
			}
			return time.NewTimer(elapsed)
		}

		// Run one refresh as soon as the server starts.
		timer := refreshFn()

		// Then refresh on the chosen timer.
		for {
			select {
			case <-ctx.Done():
				if timer != nil {
					timer.Stop()
				}
				return
			case <-timer.C:
				timer = refreshFn()
			}
		}
	}()

	return s
}

func registerDashboardHandlers(logger *zap.Logger, router *mux.Router) {
	indexFn := func(w http.ResponseWriter, r *http.Request) {
		indexFile, err := console.UIFS.Open("index.html")
		if err != nil {
			logger.Error("Failed to open index file.", zap.Error(err))
			w.WriteHeader(http.StatusNotFound)
			return
		}

		indexBytes, err := io.ReadAll(indexFile)
		if err != nil {
			logger.Error("Failed to read index file.", zap.Error(err))
			w.WriteHeader(http.StatusNotFound)
			return
		}

		w.Header().Add("Cache-Control", "no-cache")
		w.Header().Set("X-Frame-Options", "deny")
		w.Write(indexBytes)
		return
	}

	router.Path("/").HandlerFunc(indexFn)
	router.PathPrefix("/").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// get the absolute path to prevent directory traversal
		path := r.URL.Path
		logger = logger.With(zap.String("path", path))

		// check whether a file exists at the given path
		if _, err := console.UIFS.Open(path); err == nil {
			// otherwise, use http.FileServer to serve the static dir
			r.URL.Path = path // override the path with the prefixed path
			console.UI.ServeHTTP(w, r)
			return
		} else {
			indexFn(w, r)
		}
	})
}

func (s *ConsoleServer) Stop() {
	s.ctxCancelFn()
	// 1. Stop GRPC Gateway server first as it sits above GRPC server.
	if err := s.grpcGatewayServer.Shutdown(context.Background()); err != nil {
		s.logger.Error("Console server gateway listener shutdown failed", zap.Error(err))
	}
	// 2. Stop GRPC server.
	s.grpcServer.GracefulStop()
}

func consoleInterceptorFunc(logger *zap.Logger, config Config, sessionCache SessionCache) func(context.Context, interface{}, *grpc.UnaryServerInfo, grpc.UnaryHandler) (interface{}, error) {
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
		if info.FullMethod == "/nakama.console.Console/Authenticate" {
			// Skip authentication check for Login endpoint.
			return handler(ctx, req)
		}
		if info.FullMethod == "/nakama.console.Console/AuthenticateLogout" {
			return handler(ctx, req)
		}

		md, ok := metadata.FromIncomingContext(ctx)
		if !ok {
			logger.Error("Cannot extract metadata from incoming context")
			return nil, status.Error(codes.FailedPrecondition, "Cannot extract metadata from incoming context")
		}
		auth, ok := md["authorization"]
		if !ok {
			auth, ok = md["grpcgateway-authorization"]
		}
		if !ok {
			return nil, status.Error(codes.Unauthenticated, "Console authentication required.")
		}
		if len(auth) != 1 {
			return nil, status.Error(codes.Unauthenticated, "Console authentication required.")
		}

		if ctx, ok = checkAuth(ctx, config, auth[0], sessionCache); !ok {
			return nil, status.Error(codes.Unauthenticated, "Console authentication invalid.")
		}
		role := ctx.Value(ctxConsoleRoleKey{}).(console.UserRole)

		// if restriction was defined, and user role is less than or equal to (in number, lower = higher privilege) the restriction (excluding 0 - UNKNOWN), allow access; otherwise block access for all but admins
		if restrictedRole, restrictionFound := restrictedMethods[info.FullMethod]; (restrictionFound && role <= restrictedRole && role != console.UserRole_USER_ROLE_UNKNOWN) || role == console.UserRole_USER_ROLE_ADMIN {
			return handler(ctx, req)
		}

		return nil, status.Error(codes.PermissionDenied, "You don't have the necessary permissions to complete the operation.")
	}
}

func checkAuth(ctx context.Context, config Config, auth string, sessionCache SessionCache) (context.Context, bool) {
	const basicPrefix = "Basic "
	const bearerPrefix = "Bearer "

	if strings.HasPrefix(auth, basicPrefix) {
		// Basic authentication.
		username, password, ok := parseBasicAuth(auth)
		if !ok {
			return ctx, false
		}

		if username != config.GetConsole().Username || password != config.GetConsole().Password {
			// Username and/or password do not match.
			return ctx, false
		}

		ctx = context.WithValue(context.WithValue(context.WithValue(ctx, ctxConsoleRoleKey{}, console.UserRole_USER_ROLE_ADMIN), ctxConsoleUsernameKey{}, username), ctxConsoleEmailKey{}, "")
		// Basic authentication successful.
		return ctx, true
	} else if strings.HasPrefix(auth, bearerPrefix) {
		// Bearer token authentication.
		tokenStr := auth[len(bearerPrefix):]
		token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
			if s, ok := token.Method.(*jwt.SigningMethodHMAC); !ok || s.Hash != crypto.SHA256 {
				return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
			}
			return []byte(config.GetConsole().SigningKey), nil
		})
		if err != nil {
			// Token verification failed.
			return ctx, false
		}
		id, uname, email, role, exp, ok := parseConsoleToken([]byte(config.GetConsole().SigningKey), tokenStr)
		if !ok || !token.Valid {
			// The token or its claims are invalid.
			return ctx, false
		}
		if !ok {
			// Expiry time claim is invalid.
			return ctx, false
		}
		if exp <= time.Now().UTC().Unix() {
			// Token expired.
			return ctx, false
		}
		userId, err := uuid.FromString(id)
		if err != nil {
			// Malformed id
			return ctx, false
		}
		if !sessionCache.IsValidSession(userId, exp, tokenStr) {
			return ctx, false
		}

		ctx = context.WithValue(context.WithValue(context.WithValue(ctx, ctxConsoleRoleKey{}, role), ctxConsoleUsernameKey{}, uname), ctxConsoleEmailKey{}, email)

		return ctx, true
	}

	return ctx, false
}

func adminBasicAuth(config *ConsoleConfig) func(h http.Handler) http.Handler {
	return func(h http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			auth := r.Header.Get("authorization")
			if auth == "" {
				w.WriteHeader(401)
				return
			}

			username, password, ok := parseBasicAuth(auth)
			if !ok {
				w.WriteHeader(401)
				return
			}

			if username != config.Username || password != config.Password {
				w.WriteHeader(403)
				return
			}

			h.ServeHTTP(w, r)
		})
	}
}


text:
{% extends "education/admin/admin_dashboard.html" %}
{% load stats_extras %}

{% block title %}
    Dashboard -- {{ block.super }}
{% endblock %}

{% block masthead %}

Absenteeism Details

{% endblock %}

{% block content %}

                    From Date	<input type="text" id="id_from_date"  />
                    To Date	<input type="text" id="id_to_date" />
                    <select id='indicatorList'>
                        <option value="all" selected="True">--</option>
                        <option value="P3Boys">P3 Boys</option>
                        <option value="P3Girls">P3 Girls</option>
                        <option value="P3Pupils">P3 Pupils</option>
                        <option value="P6Boys">P6 Boys</option>
                        <option value="P6Girls">P6 Girls</option>
                        <option value="P6Pupils">P6 Pupils</option>
                        <option value="MaleTeachers">Male Teachers</option>
                        <option value="FemaleTeachers">Female Teachers</option>
                        <option value="Teachers">Teachers</option>
                        <option value="MaleHeadTeachers">Male Head Teachers</option>
                        <option value="FemaleHeadTeachers">Female Head Teachers</option>
                        <option value="HeadTeachers">Head Teachers</option>

                    </select>
                    <input type="submit" value="Search" id="btnSearch"/>
                     <input type="submit" value="Current Month" id="btnCurrentMonth"/>
                     <input type="submit" value="Current Term" id="btnCurrentTerm"/>

{% endblock %}


text:
<canvas></canvas>
<button ng-if=!running ng-click=start()>开启</button>
<button ng-else ng-click=stop()>关闭</button>


text:
package paulfife.javameetup.cassandra.model;

/**
 * POJO for a User
 */
public class User {
    private String userId;
    private String fullName;
    private int birthMonth;
    private int birthDay;
    private int birthYear;

    public User() {
    }

    public User(String userId, String fullName, int birthYear, int birthMonth, int birthDay) {
        this.userId = userId;
        this.fullName = fullName;
        this.birthYear = birthYear;
        this.birthMonth = birthMonth;
        this.birthDay = birthDay;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public int getBirthMonth() {
        return birthMonth;
    }

    public void setBirthMonth(int birthMonth) {
        this.birthMonth = birthMonth;
    }

    public int getBirthDay() {
        return birthDay;
    }

    public void setBirthDay(int birthDay) {
        this.birthDay = birthDay;
    }

    public int getBirthYear() {
        return birthYear;
    }

    public void setBirthYear(int birthYear) {
        this.birthYear = birthYear;
    }
}


text:
SEQAN_BEGIN_TESTSUITE(test_GCluster)
{
	// Call tests.
	SEQAN_CALL_TEST(test_GAssignCluster_dummy);
	SEQAN_CALL_TEST(test_GCluster_systemTest_emptyFiles_LAMode);
	SEQAN_CALL_TEST(test_GCluster_systemTest_emptyFiles_CQMode);
	SEQAN_CALL_TEST(test_GCluster_systemTest_toyFiles_LAMode);
	SEQAN_CALL_TEST(test_GCluster_systemTest_toyFiles_CQMode);
	SEQAN_CALL_TEST(test_GCluster_systemTest_rfamFiles_LAMode);
	SEQAN_CALL_TEST(test_GCluster_systemTest_rfamFiles_GAMode);
	SEQAN_CALL_TEST(test_GCluster_systemTest_rfamFiles_CQMode);
	SEQAN_CALL_TEST(test_GCluster_systemTest_pfamFiles_LAMode);
	SEQAN_CALL_TEST(test_GCluster_systemTest_pfamFiles_GAMode);
	SEQAN_CALL_TEST(test_GCluster_systemTest_pfamFiles_CQMode);
}
SEQAN_END_TESTSUITE