text:
require "spec_helper"

RSpec.describe "Revoke Token Flow" do
  before do
    Doorkeeper.configure { orm DOORKEEPER_ORM }
  end

  let(:private_client_application) { FactoryBot.create :application }
  let(:public_client_application) { FactoryBot.create :application, confidential: false }
  let(:resource_owner) { User.create!(name: "John", password: "sekret") }

  context "with authenticated, confidential OAuth 2.0 client/application" do
    let(:access_token) do
      FactoryBot.create(
        :access_token,
        application: private_client_application,
        resource_owner_id: resource_owner.id,
        resource_owner_type: resource_owner.class.name,
        use_refresh_token: true,
      )
    end

    let(:headers) do
      client_id = private_client_application.uid
      client_secret = private_client_application.secret
      credentials = Base64.encode64("#{client_id}:#{client_secret}")
      { "HTTP_AUTHORIZATION" => "Basic #{credentials}" }
    end

    it "revokes the access token provided" do
      post revocation_token_endpoint_url, params: { token: access_token.token }, headers: headers

      expect(response).to be_successful
      expect(access_token.reload).to be_revoked
    end

    it "revokes the refresh token provided" do
      post revocation_token_endpoint_url, params: { token: access_token.refresh_token }, headers: headers

      expect(response).to be_successful
      expect(access_token.reload).to be_revoked
    end

    context "with invalid token to revoke" do
      it "does not revoke any tokens and must respond with success" do
        expect do
          post revocation_token_endpoint_url,
               params: { token: "I_AM_AN_INVALID_TOKEN" },
               headers: headers
        end.not_to(change { Doorkeeper::AccessToken.where(revoked_at: nil).count })

        expect(response).to be_successful
      end
    end

    context "with bad credentials and a valid token" do
      let(:headers) do
        client_id = private_client_application.uid
        credentials = Base64.encode64("#{client_id}:poop")
        { "HTTP_AUTHORIZATION" => "Basic #{credentials}" }
      end

      it "does not revoke any tokens and respond with forbidden" do
        post revocation_token_endpoint_url, params: { token: access_token.token }, headers: headers

        expect(response).to be_forbidden
        expect(response.body).to include("unauthorized_client")
        expect(response.body).to include(I18n.t("doorkeeper.errors.messages.revoke.unauthorized"))
        expect(access_token.reload).not_to be_revoked
      end
    end

    context "with no credentials and a valid token" do
      it "does not revoke any tokens and respond with forbidden" do
        post revocation_token_endpoint_url, params: { token: access_token.token }

        expect(response).to be_forbidden
        expect(response.body).to include("unauthorized_client")
        expect(response.body).to include(I18n.t("doorkeeper.errors.messages.revoke.unauthorized"))
        expect(access_token.reload).not_to be_revoked
      end
    end

    context "with valid token for another client application" do
      let(:other_client_application) { FactoryBot.create :application }
      let(:headers) do
        client_id = other_client_application.uid
        client_secret = other_client_application.secret
        credentials = Base64.encode64("#{client_id}:#{client_secret}")
        { "HTTP_AUTHORIZATION" => "Basic #{credentials}" }
      end

      it "does not revoke the token as it's unauthorized" do
        post revocation_token_endpoint_url, params: { token: access_token.token }, headers: headers

        expect(response).to be_forbidden
        expect(response.body).to include("unauthorized_client")
        expect(response.body).to include(I18n.t("doorkeeper.errors.messages.revoke.unauthorized"))
        expect(access_token.reload).not_to be_revoked
      end
    end
  end

  context "with authenticated public OAuth 2.0 client/application" do
    let(:access_token) do
      FactoryBot.create(
        :access_token,
        application: nil,
        resource_owner_id: resource_owner.id,
        resource_owner_type: resource_owner.class.name,
        use_refresh_token: true,
      )
    end

    it "revokes the access token provided" do
      post revocation_token_endpoint_url,
           params: { client_id: public_client_application.uid, token: access_token.token },
           headers: headers

      expect(response).to be_successful
      expect(access_token.reload).to be_revoked
    end

    it "revokes the refresh token provided" do
      post revocation_token_endpoint_url,
           params: { client_id: public_client_application.uid, token: access_token.refresh_token },
           headers: headers

      expect(response).to be_successful
      expect(access_token.reload).to be_revoked
    end

    it "responses with success even for invalid token" do
      post revocation_token_endpoint_url,
           params: { client_id: public_client_application.uid, token: "dont_exist" },
           headers: headers

      expect(response).to be_successful
    end

    context "with a valid token issued for a confidential client" do
      let(:access_token) do
        FactoryBot.create(
          :access_token,
          application: private_client_application,
          resource_owner_id: resource_owner.id,
          resource_owner_type: resource_owner.class.name,
          use_refresh_token: true,
        )
      end

      it "does not revoke the access token provided" do
        post revocation_token_endpoint_url,
             params: { client_id: public_client_application.uid, token: access_token.token }

        expect(response).to be_forbidden
        expect(response.body).to include("unauthorized_client")
        expect(response.body).to include(I18n.t("doorkeeper.errors.messages.revoke.unauthorized"))
        expect(access_token.reload).not_to be_revoked
      end

      it "does not revoke the refresh token provided" do
        post revocation_token_endpoint_url,
             params: { client_id: public_client_application.uid, token: access_token.refresh_token }

        expect(response).to be_forbidden
        expect(response.body).to include("unauthorized_client")
        expect(response.body).to include(I18n.t("doorkeeper.errors.messages.revoke.unauthorized"))
        expect(access_token.reload).not_to be_revoked
      end
    end
  end

  context "without client authentication, when skip_client_authentication_for_password_grant is false (the default)" do
    before do
      Doorkeeper.configure do
        orm DOORKEEPER_ORM
        skip_client_authentication_for_password_grant false
      end
    end

    let(:access_token) do
      FactoryBot.create(
        :access_token,
        application: nil,
        resource_owner_id: resource_owner.id,
        resource_owner_type: resource_owner.class.name,
        use_refresh_token: true,
      )
    end

    it "does not remove the token and responses with an error" do
      post revocation_token_endpoint_url,
           params: { token: access_token.token },
           headers: headers

      expect(response).not_to be_successful
      expect(access_token.reload).not_to be_revoked
    end
  end

  context "without client authentication, when skip_client_authentication_for_password_grant is true" do
    before do
      Doorkeeper.configure do
        orm DOORKEEPER_ORM
        skip_client_authentication_for_password_grant true
      end
    end

    let(:access_token) do
      FactoryBot.create(
        :access_token,
        application: nil,
        resource_owner_id: resource_owner.id,
        resource_owner_type: resource_owner.class.name,
        use_refresh_token: true,
      )
    end

    it "revokes the access token provided" do
      post revocation_token_endpoint_url,
           params: { client_id: public_client_application.uid, token: access_token.token },
           headers: headers

      expect(response).to be_successful
      expect(access_token.reload).to be_revoked
    end
  end
end


text:
<?php
class Kwf_Acl_Component extends Kwf_Acl
{
    public function __construct()
    {
        parent::__construct();

        $this->addRole(new Kwf_Acl_Role('superuser', trlKwf('Superuser')));
        $this->addRole(new Kwf_Acl_Role('preview', trlKwf('Preview')));
        $this->add(new Kwf_Acl_Resource_EditRole('edit_role_superuser', 'superuser'), 'edit_role');
        $this->add(new Kwf_Acl_Resource_EditRole('edit_role_preview', 'preview'), 'edit_role');

        $this->add(new Zend_Acl_Resource('kwf_debug_class-tree'), 'kwf_debug');
        $this->add(new Zend_Acl_Resource('kwf_component_web'));
        $this->add(new Zend_Acl_Resource('kwf_component_media'));
        $this->add(new Zend_Acl_Resource('kwf_component_index'));
        $this->add(new Zend_Acl_Resource('kwf_component_benchmark'));
        $this->add(new Zend_Acl_Resource('kwf_component_show-component'));
        $this->add(new Kwf_Acl_Resource_MenuUrl('kwf_component_pages',
            array('text'=>trlKwf('Page tree'), 'icon'=>'application_side_tree.png'),
            '/admin/component/pages'));
            $this->add(new Zend_Acl_Resource('kwf_component_page'), 'kwf_component_pages');
            $this->add(new Zend_Acl_Resource('kwf_component_components'),
                                'kwf_component_pages'); // für /component/show
            $this->add(new Zend_Acl_Resource('kwf_component'),
                                'kwf_component_pages'); // für /component/edit
            $this->add(new Zend_Acl_Resource('kwf_component_preview'), 'kwf_component_pages');

        $this->add(new Zend_Acl_Resource('kwf_component_root')); //Komponenten können hier resourcen anhängen

        $this->add(new Zend_Acl_Resource('kwc_structure')); // Create Structure Resource for all classes
        foreach(Kwc_Abstract::getComponentClasses() as $class) {
            $this->add(new Kwf_Acl_Resource_Component_Structure($class), 'kwc_structure');
        }

        $this->allow('admin', 'kwc_structure');
        $this->allow('superuser', 'kwc_structure');

        $this->allow(null, 'kwf_component_web');
        $this->allow(null, 'kwf_component_media');
        $this->allow(null, 'kwf_component_index');
        $this->allow('admin', 'kwf_component');
        $this->allow('superuser', 'kwf_component');
        $this->allow('superuser', 'edit_role_superuser');
        $this->allow('superuser', 'edit_role_preview');

        $this->allow('admin', 'kwf_component_show-component');
        $this->allow('admin', 'kwf_component_pages');
        $this->allow('admin', 'kwf_component_benchmark');
        $this->allow('superuser', 'kwf_component_show-component');
        $this->allow('superuser', 'kwf_component_pages');
        $this->allow('preview', 'kwf_component_preview');

        $this->allow(null, 'kwf_component_root');

        $this->deny('guest', 'kwf_component_index');
        $this->deny('guest', 'kwf_component_pages');

        // Kwf_Component_Acl nicht vergessen für Komponentenrechte!
    }
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * heimdal2.c:
 * This file is automatically generated; please do not edit it.
 */

#include <stdlib.h>

static const char * const text[] = {
	"$Id$",
	"Cannot fetch local realm",
	"Unable to fetch credentials",
	"Bad key supplied",
	"Can't encrypt data",
	"Cannot encode/decode authentication info",
	"Principal attemping change is in wrong realm",
	"Packet is too large",
	"Version number is incorrect",
	"Checksum does not match",
	"Unsealing private data failed",
	"Unsupported operation",
	"Could not find administrating host",
	"Administrating host name is unknown",
	"Could not find service name in services database",
	"Could not create socket",
	"Could not connect to server",
	"Could not fetch local socket address",
	"Could not fetch master key",
	"Could not verify master key",
	"Entry already exists in database",
	"Database store error",
	"Database read error",
	"Insufficient access to perform requested operation",
	"Data is available for return to client",
	"No such entry in the database",
	"Memory exhausted",
	"Could not fetch system hostname",
	"Could not bind port",
	"Length mismatch problem",
	"Illegal use of wildcard",
	"Database is locked or in use--try again later",
	"Insecure password rejected",
	"Cleartext password and DES key did not match",
	"Invalid principal for change srvtab request",
	"Attempt do delete immutable principal",
	"Reserved kadm error (36)",
	"Reserved kadm error (37)",
	"Reserved kadm error (38)",
	"Reserved kadm error (39)",
	"Reserved kadm error (40)",
	"Reserved kadm error (41)",
	"Reserved kadm error (42)",
	"Reserved kadm error (43)",
	"Reserved kadm error (44)",
	"Reserved kadm error (45)",
	"Reserved kadm error (46)",
	"Reserved kadm error (47)",
	"Reserved kadm error (48)",
	"Reserved kadm error (49)",
	"Reserved kadm error (50)",
	"Reserved kadm error (51)",
	"Reserved kadm error (52)",
	"Reserved kadm error (53)",
	"Reserved kadm error (54)",
	"Reserved kadm error (55)",
	"Reserved kadm error (56)",
	"Reserved kadm error (57)",
	"Reserved kadm error (58)",
	"Reserved kadm error (59)",
	"Reserved kadm error (60)",
	"Reserved kadm error (61)",
	"Reserved kadm error (62)",
	"Reserved kadm error (63)",
	"Null passwords are not allowed",
	"Password is too short",
	"Too few character classes in password",
	"Password is in the password dictionary",
    0
};

struct error_table {
    char const * const * msgs;
    long base;
    int n_msgs;
};
struct et_list {
    struct et_list *next;
    const struct error_table * table;
};
extern struct et_list *_et_list;

const struct error_table et_kadm_error_table = { text, -1783126272L, 68 };

static struct et_list link = { 0, 0 };

void initialize_kadm_error_table_r(struct et_list **list);
void initialize_kadm_error_table(void);

void initialize_kadm_error_table(void) {
    initialize_kadm_error_table_r(&_et_list);
}

/* For Heimdal compatibility */
void initialize_kadm_error_table_r(struct et_list **list)
{
    struct et_list *et, **end;

    for (end = list, et = *list; et; end = &et->next, et = et->next)
        if (et->table->msgs == text)
            return;
    et = malloc(sizeof(struct et_list));
    if (et == 0) {
        if (!link.table)
            et = &link;
        else
            return;
    }
    et->table = &et_kadm_error_table;
    et->next = 0;
    *end = et;
}


text:
FROM debian:7.7
MAINTAINER dev@stratos.apache.org

# ------------------
# Setup ssh server
# ------------------
WORKDIR /opt/
RUN apt-get update && apt-get install -y openssh-server git
RUN mkdir -p /var/run/sshd
RUN echo 'root:stratos' | chpasswd
RUN sed -i "s/PermitRootLogin without-password/#PermitRootLogin without-password/" /etc/ssh/sshd_config
EXPOSE 22

# ----------------------
# Install dependencies
# ----------------------
RUN apt-get install -y git python python-pip python-dev gcc zip
RUN pip install paho-mqtt
RUN pip install psutil
RUN pip install pexpect
RUN pip install pycrypto
RUN pip install gitpython
RUN pip install yapsy

# -------------------------
# Install cartridge agent
# -------------------------
WORKDIR /mnt/

ADD packs/apache-stratos-python-cartridge-agent-4.1.0-SNAPSHOT.zip /mnt/apache-stratos-python-cartridge-agent-4.1.0-SNAPSHOT.zip
RUN unzip -q /mnt/apache-stratos-python-cartridge-agent-4.1.0-SNAPSHOT.zip -d /mnt/apache-stratos-python-cartridge-agent-4.1.0-SNAPSHOT/
RUN rm /mnt/apache-stratos-python-cartridge-agent-4.1.0-SNAPSHOT.zip

RUN mkdir -p /mnt/apache-stratos-python-cartridge-agent-4.1.0-SNAPSHOT/payload

RUN chmod +x /mnt/apache-stratos-python-cartridge-agent-4.1.0-SNAPSHOT/extensions/bash/*
RUN mkdir -p /var/log/apache-stratos/
RUN touch /var/log/apache-stratos/cartridge-agent-extensions.log

# -----------------------
# Setup startup scripts
# -----------------------
ADD files/run /usr/local/bin/run
RUN chmod +x /usr/local/bin/run


text:
layout: post
title: "实践JDK内置命令之jstack"
date: 2018-02-25 11:08:00 +0800
categories: Java
tags: java jstack
---

jstack命令用来查看跟JVM线程和栈相关的信息

```shell
$ jstack -help
Usage:
    jstack [-l] <pid>
        (to connect to running process)
    jstack -F [-m] [-l] <pid>
        (to connect to a hung process)
    jstack [-m] [-l] <executable> <core>
        (to connect to a core file)
    jstack [-m] [-l] [server_id@]<remote server IP or hostname>
        (to connect to a remote debug server)

Options:
    -F  to force a thread dump. Use when jstack <pid> does not respond (process is hung)
    -m  to print both java and native frames (mixed mode)
    -l  long listing. Prints additional information about locks.(每个线程栈最后多出一条Locked ownable synchronizers:******信息,告知拥有的同步锁)
    -h or -help to print this help message
```

```shell
$ jstack 19238
"Signal Dispatcher" daemon prio=10 tid=0x00007fd6cc11a800 nid=0x4cc6 runnable [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Finalizer" daemon prio=10 tid=0x00007fd6cc0f2000 nid=0x4cc5 in Object.wait() [0x00007fd6c84f3000]
   java.lang.Thread.State: WAITING (on object monitor)
	at java.lang.Object.wait(Native Method)
	at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:135)
	- locked <0x000000078b68c8c0> (a java.lang.ref.ReferenceQueue$Lock)
	at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:151)
	at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:209)

"Reference Handler" daemon prio=10 tid=0x00007fd6cc0f0000 nid=0x4cc4 in Object.wait() [0x00007fd6c85f4000]
   java.lang.Thread.State: WAITING (on object monitor)
	at java.lang.Object.wait(Native Method)
	at java.lang.Object.wait(Object.java:503)
	at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:133)
	- locked <0x000000078dd624d8> (a java.lang.ref.Reference$Lock)

"VM Thread" prio=10 tid=0x00007fd6cc0eb800 nid=0x4cc3 runnable

"GC task thread#0 (ParallelGC)" prio=10 tid=0x00007fd6cc01e800 nid=0x4cc1 runnable

"GC task thread#1 (ParallelGC)" prio=10 tid=0x00007fd6cc020800 nid=0x4cc2 runnable

"VM Periodic Task Thread" prio=10 tid=0x00007fd6cc12d000 nid=0x4cca waiting on condition

JNI global references: 657
```


text:
<?php

namespace ApiBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @author Roman Belousov <romanandreyvich@gmail.com>
 *
 * @ORM\Entity
 * @ORM\Table(name="family")
 */
class Family
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;
    /**
     * @ORM\Column(type="string")
     * @Assert\NotBlank()
     */
    protected $lastname;
    /**
     * @ORM\OneToMany(targetEntity="User", mappedBy="family", cascade={"persist", "remove"})
     */
    protected $users;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->users = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set lastname
     *
     * @param string $lastname
     *
     * @return Family
     */
    public function setLastname($lastname)
    {
        $this->lastname = $lastname;

        return $this;
    }

    /**
     * Get lastname
     *
     * @return string
     */
    public function getLastname()
    {
        return $this->lastname;
    }

    /**
     * Add user
     *
     * @param User $user
     *
     * @return Family
     */
    public function addUser(User $user)
    {
        $this->users[] = $user;

        return $this;
    }

    /**
     * Remove user
     *
     * @param User $user
     */
    public function removeUser(User $user)
    {
        $this->users->removeElement($user);
    }

    /**
     * Get users
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getUsers()
    {
        return $this->users;
    }
}


text:
package com.datastax.oss.driver.internal.core.metrics;

import com.datastax.oss.driver.api.core.config.DefaultDriverOption;
import com.datastax.oss.driver.api.core.config.DriverExecutionProfile;
import com.datastax.oss.driver.api.core.metadata.Node;
import com.datastax.oss.driver.api.core.metrics.DefaultSessionMetric;
import com.datastax.oss.driver.api.core.session.throttling.RequestThrottler;
import com.datastax.oss.driver.internal.core.context.InternalDriverContext;
import com.datastax.oss.driver.internal.core.cql.CqlPrepareAsyncProcessor;
import com.datastax.oss.driver.internal.core.cql.CqlPrepareSyncProcessor;
import com.datastax.oss.driver.internal.core.pool.ChannelPool;
import com.datastax.oss.driver.internal.core.session.RequestProcessor;
import com.datastax.oss.driver.internal.core.session.throttling.ConcurrencyLimitingRequestThrottler;
import com.datastax.oss.driver.internal.core.session.throttling.RateLimitingRequestThrottler;
import com.datastax.oss.driver.shaded.guava.common.cache.Cache;
import edu.umd.cs.findbugs.annotations.Nullable;
import io.netty.util.Timeout;
import java.time.Duration;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class AbstractMetricUpdater<MetricT> implements MetricUpdater<MetricT> {

  private static final Logger LOG = LoggerFactory.getLogger(AbstractMetricUpdater.class);

  // Not final for testing purposes
  public static Duration MIN_EXPIRE_AFTER = Duration.ofMinutes(5);

  protected final InternalDriverContext context;
  protected final Set<MetricT> enabledMetrics;

  private final AtomicReference<Timeout> metricsExpirationTimeoutRef = new AtomicReference<>();
  private final Duration expireAfter;

  protected AbstractMetricUpdater(InternalDriverContext context, Set<MetricT> enabledMetrics) {
    this.context = context;
    this.enabledMetrics = enabledMetrics;
    DriverExecutionProfile config = context.getConfig().getDefaultProfile();
    Duration expireAfter = config.getDuration(DefaultDriverOption.METRICS_NODE_EXPIRE_AFTER);
    if (expireAfter.compareTo(MIN_EXPIRE_AFTER) < 0) {
      LOG.warn(
          "[{}] Value too low for {}: {}. Forcing to {} instead.",
          context.getSessionName(),
          DefaultDriverOption.METRICS_NODE_EXPIRE_AFTER.getPath(),
          expireAfter,
          MIN_EXPIRE_AFTER);
      expireAfter = MIN_EXPIRE_AFTER;
    }
    this.expireAfter = expireAfter;
  }

  @Override
  public boolean isEnabled(MetricT metric, String profileName) {
    return enabledMetrics.contains(metric);
  }

  public Duration getExpireAfter() {
    return expireAfter;
  }

  protected int connectedNodes() {
    int count = 0;
    for (Node node : context.getMetadataManager().getMetadata().getNodes().values()) {
      if (node.getOpenConnections() > 0) {
        count++;
      }
    }
    return count;
  }

  protected int throttlingQueueSize() {
    RequestThrottler requestThrottler = context.getRequestThrottler();
    if (requestThrottler instanceof ConcurrencyLimitingRequestThrottler) {
      return ((ConcurrencyLimitingRequestThrottler) requestThrottler).getQueueSize();
    }
    if (requestThrottler instanceof RateLimitingRequestThrottler) {
      return ((RateLimitingRequestThrottler) requestThrottler).getQueueSize();
    }
    LOG.warn(
        "[{}] Metric {} does not support {}, it will always return 0",
        context.getSessionName(),
        DefaultSessionMetric.THROTTLING_QUEUE_SIZE.getPath(),
        requestThrottler.getClass().getName());
    return 0;
  }

  protected long preparedStatementCacheSize() {
    Cache<?, ?> cache = getPreparedStatementCache();
    if (cache == null) {
      LOG.warn(
          "[{}] Metric {} is enabled in the config, "
              + "but it looks like no CQL prepare processor is registered. "
              + "The gauge will always return 0",
          context.getSessionName(),
          DefaultSessionMetric.CQL_PREPARED_CACHE_SIZE.getPath());
      return 0L;
    }
    return cache.size();
  }

  @Nullable
  protected Cache<?, ?> getPreparedStatementCache() {
    // By default, both the sync processor and the async ones are registered and they share the same
    // cache. But with a custom processor registry, there could be only one of the two present.
    for (RequestProcessor<?, ?> processor : context.getRequestProcessorRegistry().getProcessors()) {
      if (processor instanceof CqlPrepareAsyncProcessor) {
        return ((CqlPrepareAsyncProcessor) processor).getCache();
      } else if (processor instanceof CqlPrepareSyncProcessor) {
        return ((CqlPrepareSyncProcessor) processor).getCache();
      }
    }
    return null;
  }

  protected int availableStreamIds(Node node) {
    ChannelPool pool = context.getPoolManager().getPools().get(node);
    return (pool == null) ? 0 : pool.getAvailableIds();
  }

  protected int inFlightRequests(Node node) {
    ChannelPool pool = context.getPoolManager().getPools().get(node);
    return (pool == null) ? 0 : pool.getInFlight();
  }

  protected int orphanedStreamIds(Node node) {
    ChannelPool pool = context.getPoolManager().getPools().get(node);
    return (pool == null) ? 0 : pool.getOrphanedIds();
  }

  protected void startMetricsExpirationTimeout() {
    metricsExpirationTimeoutRef.accumulateAndGet(
        newTimeout(),
        (current, update) -> {
          if (current == null) {
            return update;
          } else {
            update.cancel();
            return current;
          }
        });
  }

  protected void cancelMetricsExpirationTimeout() {
    Timeout t = metricsExpirationTimeoutRef.getAndSet(null);
    if (t != null) {
      t.cancel();
    }
  }

  protected Timeout newTimeout() {
    return context
        .getNettyOptions()
        .getTimer()
        .newTimeout(
            t -> {
              if (t.isExpired()) {
                clearMetrics();
              }
            },
            expireAfter.toNanos(),
            TimeUnit.NANOSECONDS);
  }

  protected abstract void clearMetrics();
}


text:
lower
=====

Some simple c program's based on the unix principle:

- lower.c - A programm which reads from the stdin and writes everything in lower case to the stdout.
- upper.c - A programm which reads from the stdin and writes everything in upper case to the stdout.
- addstring.c - A programm which reads from the stdin and appends the string passed as the first argument to every line.


text:
<?php

require_once 'PHPUnit/Framework/TestCase.php';
require_once 'Zend/Oauth/Token/AuthorizedRequest.php';

class Zend_Oauth_Token_AuthorizedRequestTest extends PHPUnit_Framework_TestCase
{

    public function testConstructorSetsInputData()
    {
        $data = array('foo'=>'bar');
        $token = new Zend_Oauth_Token_AuthorizedRequest($data);
        $this->assertEquals($data, $token->getData());
    }

    public function testConstructorParsesAccessTokenFromInputData()
    {
        $data = array(
            'oauth_token'=>'jZaee4GF52O3lUb9'
        );
        $token = new Zend_Oauth_Token_AuthorizedRequest($data);
        $this->assertEquals('jZaee4GF52O3lUb9', $token->getToken());
    }

    public function testPropertyAccessWorks()
    {
        $data = array(
            'oauth_token'=>'jZaee4GF52O3lUb9'
        );
        $token = new Zend_Oauth_Token_AuthorizedRequest($data);
        $this->assertEquals('jZaee4GF52O3lUb9', $token->oauth_token);
    }

    public function testTokenCastsToEncodedQueryString()
    {
        $queryString = 'oauth_token=jZaee4GF52O3lUb9&foo%20=bar~';
        $token = new Zend_Oauth_Token_AuthorizedRequest();
        $token->setToken('jZaee4GF52O3lUb9');
        $token->setParam('foo ', 'bar~');
        $this->assertEquals($queryString, (string) $token);
    }

    public function testToStringReturnsEncodedQueryString()
    {
        $queryString = 'oauth_token=jZaee4GF52O3lUb9';
        $token = new Zend_Oauth_Token_AuthorizedRequest();
        $token->setToken('jZaee4GF52O3lUb9');
        $this->assertEquals($queryString, $token->toString());
    }

    public function testIsValidDetectsBadResponse()
    {
        $data = array(
            'missing_oauth_token'=>'jZaee4GF52O3lUb9'
        );
        $token = new Zend_Oauth_Token_AuthorizedRequest($data);
        $this->assertFalse($token->isValid());
    }

    public function testIsValidDetectsGoodResponse()
    {
        $data = array(
            'oauth_token'=>'jZaee4GF52O3lUb9',
            'foo'=>'bar'
        );
        $token = new Zend_Oauth_Token_AuthorizedRequest($data);
        $this->assertTrue($token->isValid());
    }

}


text:
package com.wyw.youmingame;

import android.app.Application;
import android.content.Context;

/**
 * 项目名称:YouMinGame
 * 类描述:
 * 创建人:伍跃武
 * 创建时间:2017/5/5 11:56
 */
public class YouMinApplication extends Application {
    public static Context mContext;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;

    }
}


text:
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Cats.Models;
using Cats.Web.Administration.Models.ViewModels;
using Cats.Services.Administration;
using Cats.Web.Adminstration.Models.ViewModels;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;

namespace  Cats.Web.Adminstration.Controllers
{
     [Authorize]
    public partial class HubOwnerController : Controller
    {

        private readonly IHubOwnerService _hubOwnerService;

        public HubOwnerController(IHubOwnerService hubOwnerServiceParam)
        {
            this._hubOwnerService = hubOwnerServiceParam;
        }

        public virtual ActionResult Index()
        {
            return View();
        }

        public ActionResult Read([DataSourceRequest] DataSourceRequest reques)
        {

            return Json(GetHubOwner().ToDataSourceResult(reques));
        }

        private IEnumerable<HubOwnerViewModel> GetHubOwner()
        {
            var result = _hubOwnerService.GetAllHubOwner();
            var viewModelList = new List<HubOwnerViewModel>();
            foreach (var hubOwner in result)
            {
                var ownerViewModel = new HubOwnerViewModel();
                ownerViewModel.Name = hubOwner.Name;
                ownerViewModel.LongName = hubOwner.LongName;
                ownerViewModel.HubOwnerID = hubOwner.HubOwnerID;
                viewModelList.Add(ownerViewModel);
            }

            return viewModelList;
        }

        private HubOwner BindHubOwner(HubOwnerViewModel hubOwnerViewModel)
        {
            if (hubOwnerViewModel == null) return null;
            var hubOwner = new HubOwner()
                               {
                                   Name = hubOwnerViewModel.Name,
                                   LongName = hubOwnerViewModel.LongName,
                                   HubOwnerID = hubOwnerViewModel.HubOwnerID,

                               };
            return hubOwner;
        }

            [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult HubOwnerCreate([DataSourceRequest] DataSourceRequest request, HubOwnerViewModel hubOwner)
        {
            if (hubOwner != null && ModelState.IsValid)
            {

                _hubOwnerService.AddHubOwner(BindHubOwner(hubOwner));
            }

            return Json(new[] { hubOwner }.ToDataSourceResult(request, ModelState));
        }

            [AcceptVerbs(HttpVerbs.Post)]
            public ActionResult HubOwnerUpdate([DataSourceRequest] DataSourceRequest request, HubOwnerViewModel hubOwner)
            {
                if (hubOwner != null && ModelState.IsValid)
                {
                    var result = _hubOwnerService.FindById(hubOwner.HubOwnerID);
                    if (result!=null)
                    {
                        result.Name = hubOwner.Name;
                        result.LongName = hubOwner.LongName;
                        _hubOwnerService.EditHubOwner(result);
                    }
                }
                return Json(new[] { hubOwner }.ToDataSourceResult(request, ModelState));
            }

            [AcceptVerbs(HttpVerbs.Post)]
            public ActionResult HubOwnerDestroy([DataSourceRequest] DataSourceRequest request, HubOwnerViewModel hubOwner)
            {
                if (hubOwner != null && ModelState.IsValid)
                {
                    var result = _hubOwnerService.FindById(hubOwner.HubOwnerID);
                    if (result != null)
                    {
                        _hubOwnerService.DeleteHubOwner(result);
                    }
                }
                return Json(ModelState.ToDataSourceResult());
            }

        //
        // GET: /HubOwners/Delete/5

        public virtual ActionResult Delete(int id)
        {
            HubOwner HubOwner = _hubOwnerService.FindById(id);
            _hubOwnerService.DeleteHubOwner(HubOwner);
            return RedirectToAction("Index");
        }

    }
}


text:
#ifndef ADIOS2_ENGINE_PLUGIN_PLUGINENGINE_H_
#define ADIOS2_ENGINE_PLUGIN_PLUGINENGINE_H_

#include "PluginEngineInterface.h"

#include <memory> // for unique_ptr
#include <string> // for string

#include "adios2/common/ADIOSMacros.h"
#include "adios2/common/ADIOSTypes.h"
#include "adios2/core/Engine.h"
#include "adios2/core/IO.h"
#include "adios2/core/Variable.h"
#include "adios2/helper/adiosComm.h"

namespace adios2
{
namespace plugin
{

/** A front-end wrapper for an engine implemented outside of libadios2 */
class PluginEngine : public core::Engine
{
public:
    PluginEngine(core::IO &io, const std::string &name, const Mode mode,
                 helper::Comm comm);
    virtual ~PluginEngine();

    StepStatus BeginStep(StepMode mode,
                         const float timeoutSeconds = 0.f) override;
    void PerformPuts() override;
    void PerformGets() override;
    void EndStep() override;

protected:
#define declare(T)                                                             \
    void DoPutSync(core::Variable<T> &, const T *) override;                   \
    void DoPutDeferred(core::Variable<T> &, const T *) override;               \
    void DoGetSync(core::Variable<T> &, T *) override;                         \
    void DoGetDeferred(core::Variable<T> &, T *) override;

    ADIOS2_FOREACH_STDTYPE_1ARG(declare)
#undef declare

    void DoClose(const int transportIndex = -1) override;

    // probably should go to plugin if this is to be used for non-trivial
    // engines
    void DestructorClose(bool Verbose) noexcept final{};

private:
    struct Impl;
    std::unique_ptr<Impl> m_Impl;
};

} // end namespace plugin
} // end namespace adios2

#endif /* ADIOS2_ENGINE_PLUGIN_PLUGINENGINE_H_ */


text:
module Coveralls
  module SimpleCov
    class Formatter

      def display_result(result)
        # Log which files would be submitted.
        if result.files.length > 0
          Coveralls::Output.puts "[Coveralls] Some handy coverage stats:"
        else
          Coveralls::Output.puts "[Coveralls] There are no covered files.", :color => "yellow"
        end
        result.files.each do |f|
          Coveralls::Output.print "  * "
          Coveralls::Output.print short_filename(f.filename).to_s, :color => "cyan"
          Coveralls::Output.print " => ", :color => "white"
          cov = "#{f.covered_percent.round}%"
          if f.covered_percent > 90
            Coveralls::Output.print cov, :color => "green"
          elsif f.covered_percent > 80
            Coveralls::Output.print cov, :color => "yellow"
          else
            Coveralls::Output.print cov, :color => "red"
          end
          Coveralls::Output.puts ""
        end
        true
      end

      def format(result)

        unless Coveralls.should_run?
          if Coveralls.noisy?
            display_result result
          end
          return
        end

        # Gather the source files.
        source_files = []
        result.files.each do |file|
          properties = {}

          # Get Source
          properties[:source] = File.open(file.filename, "rb:utf-8").read

          # Get the root-relative filename
          properties[:name] = short_filename(file.filename)

          # Get the coverage
          properties[:coverage] = file.coverage

          # Get the group
          # puts "result groups: #{result.groups}"
          # result.groups.each do |group_name, grouped_files|
          #   puts "Checking #{grouped_files.map(&:filename)} for #{file.filename}"
          #   if grouped_files.map(&:filename).include?(file.filename)
          #     properties[:group] = group_name
          #     break
          #   end
          # end

          source_files << properties
        end

        # Log which files are being submitted.
        # puts "Submitting #{source_files.length} file#{source_files.length == 1 ? '' : 's'}:"
        # source_files.each do |f|
        #   puts "  => #{f[:name]}"
        # end

        # Post to hardcover.
        if ENV['JENKINS_URL']
          service_job_id = "#{ENV['JOB_NAME']}/#{ENV['BUILD_NUMBER']}"
          API.post_json "jobs", {:source_files => source_files,
                                 :service_job_id => service_job_id,
                                 :service_name => "jenkins-ci",
                                 :repo_token => ENV["HARDCOVER_REPO_TOKEN"]}
          Coveralls::Output.puts output_message result
        else
          Coveralls::Output.puts "[Hardcover] Other services than Jenkins are not yet supported."
        end

        true

      rescue Exception => e
        display_error e
      end

      def display_error(e)
        Coveralls::Output.puts "Coveralls encountered an exception:", :color => "red"
        Coveralls::Output.puts e.class.to_s, :color => "red"
        Coveralls::Output.puts e.message, :color => "red"
        e.backtrace.each do |line|
          Coveralls::Output.puts line, :color => "red"
        end if e.backtrace
        if e.respond_to?(:response) && e.response
          Coveralls::Output.puts e.response.to_s, :color => "red"
        end
        false
      end

      def output_message(result)
        "Coverage is at #{result.covered_percent.round(2) rescue result.covered_percent.round}%.\nCoverage report sent to Coveralls."
      end

      def short_filename(filename)
        filename = filename.gsub(::SimpleCov.root, '.').gsub(/^\.\//, '') if ::SimpleCov.root
        filename
      end

    end
  end
end


text:
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif

#ifdef HAVE_TIME_H
#include <time.h>
#endif

#include <errno.h>

#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

#include <stdio.h>

#include <string.h>

#ifdef HAVE_ZLIB_H
#include <zlib.h>
#endif /* HAVE_ZLIB_H */

#ifdef HAVE_BZLIB_H
#include <bzlib.h>
#endif /* HAVE_BZLIB_H */

#include <openssl/sha.h>

#include "memory.h"
#include "error.h"
#include "log.h"
#include "file.h"

struct _GuardianFile
{
    char *path;
    FILE *stream;

    /* Cached values to determine log rotation */
    struct timespec st_mtim;
    ino_t st_ino;
    off_t st_pos;
    off_t st_size;
};

/** Allow DATA_BUFFER_SIZE to be overridden with compile-flags */
#ifndef DATA_BUFFER_SIZE
#define DATA_BUFFER_SIZE 1024
#endif

GuardianFile *
guardian_file_new(const char *path)
{
    GuardianFile *file = (GuardianFile *)guardian_new(1, sizeof(GuardianFile));

    file->path = guardian_new(1, strlen(path)+1);
    strncpy(file->path, path, strlen(path));

    file->stream = NULL;

    return file;
}

int
guardian_file_verify (
        GuardianFile *file,
        size_t st_size,
        const unsigned char *hash)
{
    SHA_CTX sha_ctx;

    int fd;
    struct stat buffer;
    int error_sv;

    char data_buffer[DATA_BUFFER_SIZE];
    char *str_ptr = &data_buffer[0];
    char *end_ptr = &data_buffer[DATA_BUFFER_SIZE-1];
    char *ptr;

    unsigned char file_hash[20];
    size_t _size;
    int i = 0;

    FILE *stream = NULL;

    /**
     * Use a separate stream,
     * file->stream is reserved for read operations.
     */
    stream = fopen(file->path, "r");

    if (stream == NULL)
    {
        error_sv = errno;
        guardian_log_warning (
            "Can not open file: %s:'%s'",
            file->path,
            strerror (error_sv));
        return -1;
    }

    /* Read file statistics */
    fd = fileno (stream);
    fstat (fd, &buffer);

    /* If the file is smaller then expected,
     * it can't be the file we are looking for.
     */
    if (buffer.st_size < st_size)
    {
        fclose(stream);
        return 2;
    }

    SHA1_Init (&sha_ctx);

    while (i < st_size)
    {
        if (i+DATA_BUFFER_SIZE < st_size)
        {
            _size = fread (data_buffer, 1, DATA_BUFFER_SIZE, stream);
        }
        else
        {
            _size = fread (data_buffer, 1, st_size - i, stream);
        }

        SHA1_Update (&sha_ctx, data_buffer, _size);
        i += _size;
    }

    SHA1_Final ((unsigned char *)file_hash, &sha_ctx);

    fclose(stream);

    if(memcmp(file_hash, hash, 20))
    {
        return 3;
    }

    return 0;
}

int
guardian_file_get_hash (
        GuardianFile *file,
        size_t *st_size,
        unsigned char **hash)
{
    SHA_CTX sha_ctx;

    int fd;
    struct stat buffer;
    int error_sv;

    char data_buffer[DATA_BUFFER_SIZE];

    int i = 0;
    size_t _size;

    FILE *stream = NULL;

    /**
     * Use a separate stream,
     * file->stream is reserved for read operations.
     */
    stream = fopen(file->path, "r");

    if (stream == NULL)
    {
        error_sv = errno;
        guardian_log_warning (
            "Can not open file: %s:'%s'",
            file->path,
            strerror (error_sv));
        return -1;
    }

    /* Read file statistics */
    fd = fileno (stream);
    fstat (fd, &buffer);

    *st_size = buffer.st_size;

    SHA1_Init (&sha_ctx);

    while (i < buffer.st_size)
    {
        if (i+DATA_BUFFER_SIZE < buffer.st_size)
        {
            _size = fread (data_buffer, 1, DATA_BUFFER_SIZE, stream);
        }
        else
        {
            _size = fread (data_buffer, 1, buffer.st_size - i, stream);
        }

        SHA1_Update (&sha_ctx, data_buffer, _size);
        i += _size;
    }

    SHA1_Final ((unsigned char *)(*hash), &sha_ctx);

    fclose(stream);

    return 0;
}

int
guardian_file_read (
        GuardianFile *file,
        size_t size,
        void   *buffer,
        GuardianError **error) {

    int fd;
    struct stat st_buffer;
    size_t s = 0;
    int error_sv;

    /* If there is no stream, open one file for reading.
     */
    if (file->stream == NULL) {
        file->stream = fopen(file->path, "r");

        /* Check if a stream could be opened.
         */
        if (file->stream == NULL) {
            /* If a pointer is provided to store
             * an error object, put it there.
             * Otherwise, log the error directly
             * from the library.
             */
            if (error) {
                *error = guardian_error_new (
                    "Can not open file: %s:'%s'",
                    file->path,
                    strerror (error_sv));
            } else {
                guardian_log_error (
                    "Can not open file: %s:'%s'",
                    file->path,
                    strerror (error_sv));
            }
            return -1;
        }

        /* Stat the file, this is needed to determine
         * log-file rotation. But it can also be used
         * for other things.
         */
        fd = fileno (file->stream);
        fstat (fd, &st_buffer);

        file->st_ino  = st_buffer.st_ino;   /* Inode */
        file->st_size = st_buffer.st_size;  /* Size  */
        file->st_mtim = st_buffer.st_mtim;  /* Modification-time */
        file->st_pos  = 0;
    }

    /* Read from the file */
    s = fread (buffer, 1, size, file->stream);
    if (s < size) {

        /* If the EOF flag is set, check if the file is rotated
         * or if we are simply waiting for data.
         */
        if (feof(file->stream)) {
            clearerr(file->stream);

            fd = open(file->path, O_RDONLY);
            fstat (fd, &st_buffer);
            close(fd);

            /* If the file is rotated, close the stream
             * and open a new one on the rotated file.
             */
            if (st_buffer.st_ino != file->st_ino) {
                /* TODO:
                 * Find a better way to log this.
                 */
                guardian_log_info (
                        "File INODE changed, "
                        "log-rotation expected. Opening new stream.");

                fclose(file->stream);

                file->stream = fopen(file->path, "r");
                if (file->stream == NULL) {
                    error_sv = errno;

                    if (error) {
                        *error = guardian_error_new (
                            "Can not open file: %s:'%s'",
                            file->path,
                            strerror (error_sv));
                    }
                    guardian_log_error (
                        "Can not open file: %s:'%s'",
                        file->path,
                        strerror (error_sv));

                    return -1;
                }

                fd = fileno (file->stream);
                fstat (fd, &st_buffer);

                file->st_ino  = st_buffer.st_ino;
                file->st_size = st_buffer.st_size;
                file->st_mtim = st_buffer.st_mtim;
                file->st_pos  = 0;
            }
        }
        if (ferror(file->stream)) {
            guardian_log_warning("An error occurred while reading file.");
        }
    }

    return s;
}