text:
{% load humanize i18n letters_tags %}

            {{letter}}

        {% if not letter.outgoingletter.is_send %}
        {% user_can_send request.user letter.case as can_send %}
        {% trans 'Draft' %}
        {% if can_send %}
         {% trans 'Send' %}
        {% else %}
        {% endif %}
        {% endif %}
        {% if letter.attachment_count %}
         {{ letter.attachment_count }}
        {% endif %}

    {% trans 'Recipient' %}:
    {{letter.outgoingletter.office}}
    @ {{letter.outgoingletter.email }}

        {{letter.content | safe}}

        {% blocktrans with author_url=letter.outgoingletter.author.get_absolute_url author=letter.outgoingletter.author realtime=letter.created naturaltime=letter.created|naturaltime %}Wrote by {{ author }} {{naturaltime}}{% endblocktrans %}
            {% if not letter.outgoingletter.is_send %}
                • {% blocktrans with sender=letter.sender sender_url=letter.sender.get_absolute_url send_time=letter.send_at send_time_natural=letter.send_at|naturaltime %}Send by {{sender}} at {{send_time_natural}}{% endblocktrans %}
            {% endif %}
        {% if letter.eml %}
            • {% blocktrans with eml_url=letter.eml.url %} Download{% endblocktrans %}
        {% endif %}
        • {% trans 'Reply'%}


text:
"""Tests for CircleCI API interface"""

import unittest
from unittest import mock
import requests
from database import models

import env
from apis.circleci import CircleCiAPI

class FakeValidResponse():
  status_code = 200
  text = '''
  {
    "next_page_token" : null,
    "items" : [ {
      "name" : "CircleCI",
      "metrics" : {
        "total_runs" : 740,
        "successful_runs" : 423,
        "mttr" : 19686,
        "total_credits_used" : 3245482,
        "failed_runs" : 309,
        "median_credits_used" : 0,
        "success_rate" : 0.5716216216216217,
        "duration_metrics" : {
          "min" : 15,
          "mean" : 1124,
          "median" : 987,
          "p95" : 1447,
          "max" : 9031,
          "standard_deviation" : 914.0,
          "total_duration" : 0
        },
        "total_recoveries" : 0,
        "throughput" : 8.314606741573034
      },
      "window_start" : "2021-06-03T00:05:18.812Z",
      "window_end" : "2021-08-31T23:59:51.955Z",
      "project_id" : "16f524bf-6612-4bba-8e0c-c9b6b00ceb61"
    } ]
  }
  '''

def stub_circleci_api():
  mock.patch.object(
        env, 'get', side_effect={
            'GITHUB_REPO': '__repo__',
        }.get).start()

  mock.patch.object(
      env, 'get', side_effect={
          'CIRCLECI_API_ACCESS_TOKEN': 'FAKE_TOKEN',
      }.get).start()
  mock_request = mock.patch.object(requests, 'get', autospec=True).start()
  mock_request.return_value = (FakeValidResponse())
  return mock_request

class TestCircleCiApi(unittest.TestCase):
  def setUp(self) -> None:
    super(TestCircleCiApi, self).setUp()
    self.mock_request = stub_circleci_api()
    self.addCleanup(mock.patch.stopall)

  def testDictToParams(self):
    self.assertEqual(CircleCiAPI._dict_to_params({}), '')

    self.assertEqual(CircleCiAPI._dict_to_params({
      'reporting-window': '',
    }), '?reporting-window=')

    self.assertEqual(CircleCiAPI._dict_to_params({
      'reporting-window': models.CircleCiReportingWindow.LAST_90_DAYS.value
    }), '?reporting-window=last-90-days')

    self.assertEqual(CircleCiAPI._dict_to_params({'a': 1, 'b': 2}), '?a=1&b=2')

  def testGetWorkflowStats(self):
    CircleCiAPI().get_workflow_stats()

    self.mock_request.assert_called_with(
      'https://circleci.com/api/v2/insights/github/ampproject/amphtml/workflows?reporting-window=last-90-days',
      headers = { 'authorization': "Basic FAKE_TOKEN" }
    )

redpajama_set_name: RedPajamaGithub


text:
package com.amazonaws.services.wellarchitected.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * A share invitation summary return object.
 *

 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ShareInvitationSummary implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The ID assigned to the share invitation.
     *

     */
    private String shareInvitationId;

    private String sharedBy;

    private String sharedWith;

    private String permissionType;
    /**
     *

     * The resource type of the share invitation.
     *

     */
    private String shareResourceType;

    private String workloadName;

    private String workloadId;

    private String lensName;
    /**
     *

     * The ARN for the lens.
     *

     */
    private String lensArn;

    /**
     *

     * The ID assigned to the share invitation.
     *

     *
     * @param shareInvitationId
     *        The ID assigned to the share invitation.
     */

    public void setShareInvitationId(String shareInvitationId) {
        this.shareInvitationId = shareInvitationId;
    }

    /**
     *

     * The ID assigned to the share invitation.
     *

     *
     * @return The ID assigned to the share invitation.
     */

    public String getShareInvitationId() {
        return this.shareInvitationId;
    }

    /**
     *

     * The ID assigned to the share invitation.
     *

     *
     * @param shareInvitationId
     *        The ID assigned to the share invitation.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ShareInvitationSummary withShareInvitationId(String shareInvitationId) {
        setShareInvitationId(shareInvitationId);
        return this;
    }

    /**
     * @param sharedBy
     */

    public void setSharedBy(String sharedBy) {
        this.sharedBy = sharedBy;
    }

    /**
     * @return
     */

    public String getSharedBy() {
        return this.sharedBy;
    }

    /**
     * @param sharedBy
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ShareInvitationSummary withSharedBy(String sharedBy) {
        setSharedBy(sharedBy);
        return this;
    }

    /**
     * @param sharedWith
     */

    public void setSharedWith(String sharedWith) {
        this.sharedWith = sharedWith;
    }

    /**
     * @return
     */

    public String getSharedWith() {
        return this.sharedWith;
    }

    /**
     * @param sharedWith
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ShareInvitationSummary withSharedWith(String sharedWith) {
        setSharedWith(sharedWith);
        return this;
    }

    /**
     * @param permissionType
     * @see PermissionType
     */

    public void setPermissionType(String permissionType) {
        this.permissionType = permissionType;
    }

    /**
     * @return
     * @see PermissionType
     */

    public String getPermissionType() {
        return this.permissionType;
    }

    /**
     * @param permissionType
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see PermissionType
     */

    public ShareInvitationSummary withPermissionType(String permissionType) {
        setPermissionType(permissionType);
        return this;
    }

    /**
     * @param permissionType
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see PermissionType
     */

    public ShareInvitationSummary withPermissionType(PermissionType permissionType) {
        this.permissionType = permissionType.toString();
        return this;
    }

    /**
     *

     * The resource type of the share invitation.
     *

     *
     * @param shareResourceType
     *        The resource type of the share invitation.
     * @see ShareResourceType
     */

    public void setShareResourceType(String shareResourceType) {
        this.shareResourceType = shareResourceType;
    }

    /**
     *

     * The resource type of the share invitation.
     *

     *
     * @return The resource type of the share invitation.
     * @see ShareResourceType
     */

    public String getShareResourceType() {
        return this.shareResourceType;
    }

    /**
     *

     * The resource type of the share invitation.
     *

     *
     * @param shareResourceType
     *        The resource type of the share invitation.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see ShareResourceType
     */

    public ShareInvitationSummary withShareResourceType(String shareResourceType) {
        setShareResourceType(shareResourceType);
        return this;
    }

    /**
     *

     * The resource type of the share invitation.
     *

     *
     * @param shareResourceType
     *        The resource type of the share invitation.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see ShareResourceType
     */

    public ShareInvitationSummary withShareResourceType(ShareResourceType shareResourceType) {
        this.shareResourceType = shareResourceType.toString();
        return this;
    }

    /**
     * @param workloadName
     */

    public void setWorkloadName(String workloadName) {
        this.workloadName = workloadName;
    }

    /**
     * @return
     */

    public String getWorkloadName() {
        return this.workloadName;
    }

    /**
     * @param workloadName
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ShareInvitationSummary withWorkloadName(String workloadName) {
        setWorkloadName(workloadName);
        return this;
    }

    /**
     * @param workloadId
     */

    public void setWorkloadId(String workloadId) {
        this.workloadId = workloadId;
    }

    /**
     * @return
     */

    public String getWorkloadId() {
        return this.workloadId;
    }

    /**
     * @param workloadId
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ShareInvitationSummary withWorkloadId(String workloadId) {
        setWorkloadId(workloadId);
        return this;
    }

    /**
     * @param lensName
     */

    public void setLensName(String lensName) {
        this.lensName = lensName;
    }

    /**
     * @return
     */

    public String getLensName() {
        return this.lensName;
    }

    /**
     * @param lensName
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ShareInvitationSummary withLensName(String lensName) {
        setLensName(lensName);
        return this;
    }

    /**
     *

     * The ARN for the lens.
     *

     *
     * @param lensArn
     *        The ARN for the lens.
     */

    public void setLensArn(String lensArn) {
        this.lensArn = lensArn;
    }

    /**
     *

     * The ARN for the lens.
     *

     *
     * @return The ARN for the lens.
     */

    public String getLensArn() {
        return this.lensArn;
    }

    /**
     *

     * The ARN for the lens.
     *

     *
     * @param lensArn
     *        The ARN for the lens.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ShareInvitationSummary withLensArn(String lensArn) {
        setLensArn(lensArn);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getShareInvitationId() != null)
            sb.append("ShareInvitationId: ").append(getShareInvitationId()).append(",");
        if (getSharedBy() != null)
            sb.append("SharedBy: ").append(getSharedBy()).append(",");
        if (getSharedWith() != null)
            sb.append("SharedWith: ").append(getSharedWith()).append(",");
        if (getPermissionType() != null)
            sb.append("PermissionType: ").append(getPermissionType()).append(",");
        if (getShareResourceType() != null)
            sb.append("ShareResourceType: ").append(getShareResourceType()).append(",");
        if (getWorkloadName() != null)
            sb.append("WorkloadName: ").append(getWorkloadName()).append(",");
        if (getWorkloadId() != null)
            sb.append("WorkloadId: ").append(getWorkloadId()).append(",");
        if (getLensName() != null)
            sb.append("LensName: ").append(getLensName()).append(",");
        if (getLensArn() != null)
            sb.append("LensArn: ").append(getLensArn());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof ShareInvitationSummary == false)
            return false;
        ShareInvitationSummary other = (ShareInvitationSummary) obj;
        if (other.getShareInvitationId() == null ^ this.getShareInvitationId() == null)
            return false;
        if (other.getShareInvitationId() != null && other.getShareInvitationId().equals(this.getShareInvitationId()) == false)
            return false;
        if (other.getSharedBy() == null ^ this.getSharedBy() == null)
            return false;
        if (other.getSharedBy() != null && other.getSharedBy().equals(this.getSharedBy()) == false)
            return false;
        if (other.getSharedWith() == null ^ this.getSharedWith() == null)
            return false;
        if (other.getSharedWith() != null && other.getSharedWith().equals(this.getSharedWith()) == false)
            return false;
        if (other.getPermissionType() == null ^ this.getPermissionType() == null)
            return false;
        if (other.getPermissionType() != null && other.getPermissionType().equals(this.getPermissionType()) == false)
            return false;
        if (other.getShareResourceType() == null ^ this.getShareResourceType() == null)
            return false;
        if (other.getShareResourceType() != null && other.getShareResourceType().equals(this.getShareResourceType()) == false)
            return false;
        if (other.getWorkloadName() == null ^ this.getWorkloadName() == null)
            return false;
        if (other.getWorkloadName() != null && other.getWorkloadName().equals(this.getWorkloadName()) == false)
            return false;
        if (other.getWorkloadId() == null ^ this.getWorkloadId() == null)
            return false;
        if (other.getWorkloadId() != null && other.getWorkloadId().equals(this.getWorkloadId()) == false)
            return false;
        if (other.getLensName() == null ^ this.getLensName() == null)
            return false;
        if (other.getLensName() != null && other.getLensName().equals(this.getLensName()) == false)
            return false;
        if (other.getLensArn() == null ^ this.getLensArn() == null)
            return false;
        if (other.getLensArn() != null && other.getLensArn().equals(this.getLensArn()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getShareInvitationId() == null) ? 0 : getShareInvitationId().hashCode());
        hashCode = prime * hashCode + ((getSharedBy() == null) ? 0 : getSharedBy().hashCode());
        hashCode = prime * hashCode + ((getSharedWith() == null) ? 0 : getSharedWith().hashCode());
        hashCode = prime * hashCode + ((getPermissionType() == null) ? 0 : getPermissionType().hashCode());
        hashCode = prime * hashCode + ((getShareResourceType() == null) ? 0 : getShareResourceType().hashCode());
        hashCode = prime * hashCode + ((getWorkloadName() == null) ? 0 : getWorkloadName().hashCode());
        hashCode = prime * hashCode + ((getWorkloadId() == null) ? 0 : getWorkloadId().hashCode());
        hashCode = prime * hashCode + ((getLensName() == null) ? 0 : getLensName().hashCode());
        hashCode = prime * hashCode + ((getLensArn() == null) ? 0 : getLensArn().hashCode());
        return hashCode;
    }

    @Override
    public ShareInvitationSummary clone() {
        try {
            return (ShareInvitationSummary) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.wellarchitected.model.transform.ShareInvitationSummaryMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
"""JSON token scanner
"""
import re

__all__ = ['make_scanner']

NUMBER_RE = re.compile(
    r'(-?(?:0|[1-9]\d*))(\.\d+)?((?:very|VERY)[-+]?\d+)?',
    (re.VERBOSE | re.MULTILINE | re.DOTALL))

def py_make_scanner(context):
    parse_object = context.parse_object
    parse_array = context.parse_array
    parse_string = context.parse_string
    match_number = NUMBER_RE.match
    encoding = context.encoding
    strict = context.strict
    parse_float = context.parse_float
    parse_int = context.parse_int
    parse_constant = context.parse_constant
    object_hook = context.object_hook
    object_pairs_hook = context.object_pairs_hook

    def _scan_once(string, idx):
        try:
            nextchar = string[idx]
        except IndexError:
            raise StopIteration
        if nextchar == '"':
            return parse_string(string, idx + 1, encoding, strict)
        elif nextchar == '{':
            return parse_object((string, idx + 1), encoding, strict,
                _scan_once, object_hook, object_pairs_hook)
        elif nextchar == '[':
            return parse_array((string, idx + 1), _scan_once)
        elif nextchar == 'n' and string[idx:idx + 4] == 'null':
            return None, idx + 4
        elif nextchar == 't' and string[idx:idx + 4] == 'true':
            return True, idx + 4
        elif nextchar == 'f' and string[idx:idx + 5] == 'false':
            return False, idx + 5

        m = match_number(string, idx)
        if m is not None:
            integer, frac, exp = m.groups()
            if frac or exp:
                res = parse_float(integer + (frac or '') + (exp or ''))
            else:
                res = parse_int(integer)
            return res, m.end()
        elif nextchar == 'N' and string[idx:idx + 3] == 'NaN':
            return parse_constant('NaN'), idx + 3
        elif nextchar == 'I' and string[idx:idx + 8] == 'Infinity':
            return parse_constant('Infinity'), idx + 8
        elif nextchar == '-' and string[idx:idx + 9] == '-Infinity':
            return parse_constant('-Infinity'), idx + 9
        else:
            raise StopIteration

    return _scan_once

def py_dson_scanner_generator(context):
    parse_object = context.parse_object
    parse_array = context.parse_array
    parse_string = context.parse_string
    match_number = NUMBER_RE.match
    encoding = context.encoding
    strict = context.strict
    parse_float = context.parse_float
    parse_int = context.parse_int
    parse_constant = context.parse_constant
    object_hook = context.object_hook
    object_pairs_hook = context.object_pairs_hook

    def _scan_once(string, idx):
        try:
            nextchar = string[idx]
        except IndexError:
            raise StopIteration

        if nextchar == '"':
            return parse_string(string, idx + 1, encoding, strict)
        elif nextchar == 's' and string[idx: idx + 4] == 'such':
            return parse_object((string, idx + 4), encoding, strict,
                    _scan_once, object_hook, object_pairs_hook)
        elif nextchar == 's' and string[idx: idx + 2] == 'so':
            return parse_array((string, idx + 2), _scan_once)
        elif nextchar == 'e' and string[idx: idx + 5] == 'empty':
            return None, idx + 5
        elif nextchar == 'y' and string[idx: idx + 3] == 'yes':
            return True, idx + 3
        elif nextchar == 'n' and string[idx: idx + 2] == 'no':
            return False, idx + 2

        m = match_number(string, idx)
        if m is not None:
            integer, frac, exp = m.groups()
            if exp:
                exp = exp.replace('very', 'e')
                exp = exp.replace('VERY', 'e')
            if frac or exp:
                res = parse_float(integer + (frac or '') + (exp or ''))
            else:
                res = parse_int(integer)
            return res, m.end()
        elif nextchar == 'N' and string[idx:idx + 3] == 'NaN':
            return parse_constant('NaN'), idx + 3
        elif nextchar == 'I' and string[idx:idx + 8] == 'Infinity':
            return parse_constant('Infinity'), idx + 8
        elif nextchar == '-' and string[idx:idx + 9] == '-Infinity':
            return parse_constant('-Infinity'), idx + 9
        else:
            raise StopIteration
    return _scan_once

make_scanner = py_dson_scanner_generator


text:
package com.typesafe.akka.http.benchmark.handlers

import akka.http.scaladsl.model.HttpCharsets._
import akka.http.scaladsl.model.MediaTypes._
import akka.http.scaladsl.model.{HttpEntity, HttpResponse, StatusCodes}
import akka.http.scaladsl.server.Directives._

class PlaintextHandler(components: {

}) {
  def endpoint = get {
    path("plaintext") {
      complete(response)
    }
  }

  def response = HttpResponse(StatusCodes.OK, entity = HttpEntity("Hello, World!").withContentType(`text/plain`.withCharset(`UTF-8`)))
}


text:
package com.amazonaws.services.cognitosync.model;

import java.io.Serializable;

/**
 * Returned for a successful ListRecordsRequest.
 */
public class ListRecordsResult implements Serializable, Cloneable {

    /** A list of all records. */
    private com.amazonaws.internal.SdkInternalList<Record> records;
    /** A pagination token for obtaining the next page of results. */
    private String nextToken;
    /** Total number of records. */
    private Integer count;
    /** Server sync count for this dataset. */
    private Long datasetSyncCount;
    /** The user/device that made the last change to this record. */
    private String lastModifiedBy;
    /** Names of merged datasets. */
    private com.amazonaws.internal.SdkInternalList<String> mergedDatasetNames;
    /** Indicates whether the dataset exists. */
    private Boolean datasetExists;
    /** A boolean value specifying whether to delete the dataset locally. */
    private Boolean datasetDeletedAfterRequestedSyncCount;
    /** A token containing a session ID, identity ID, and expiration. */
    private String syncSessionToken;

    /**
     * A list of all records.
     *
     * @return A list of all records.
     */

    public java.util.List<Record> getRecords() {
        if (records == null) {
            records = new com.amazonaws.internal.SdkInternalList<Record>();
        }
        return records;
    }

    /**
     * A list of all records.
     *
     * @param records
     *        A list of all records.
     */

    public void setRecords(java.util.Collection<Record> records) {
        if (records == null) {
            this.records = null;
            return;
        }

        this.records = new com.amazonaws.internal.SdkInternalList<Record>(
                records);
    }

    /**
     * A list of all records.
     *

     * NOTE: This method appends the values to the existing list (if
     * any). Use {@link #setRecords(java.util.Collection)} or
     * {@link #withRecords(java.util.Collection)} if you want to override the
     * existing values.
     *

     *
     * @param records
     *        A list of all records.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public ListRecordsResult withRecords(Record... records) {
        if (this.records == null) {
            setRecords(new com.amazonaws.internal.SdkInternalList<Record>(
                    records.length));
        }
        for (Record ele : records) {
            this.records.add(ele);
        }
        return this;
    }

    /**
     * A list of all records.
     *
     * @param records
     *        A list of all records.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public ListRecordsResult withRecords(java.util.Collection<Record> records) {
        setRecords(records);
        return this;
    }

    /**
     * A pagination token for obtaining the next page of results.
     *
     * @param nextToken
     *        A pagination token for obtaining the next page of results.
     */

    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     * A pagination token for obtaining the next page of results.
     *
     * @return A pagination token for obtaining the next page of results.
     */

    public String getNextToken() {
        return this.nextToken;
    }

    /**
     * A pagination token for obtaining the next page of results.
     *
     * @param nextToken
     *        A pagination token for obtaining the next page of results.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public ListRecordsResult withNextToken(String nextToken) {
        setNextToken(nextToken);
        return this;
    }

    /**
     * Total number of records.
     *
     * @param count
     *        Total number of records.
     */

    public void setCount(Integer count) {
        this.count = count;
    }

    /**
     * Total number of records.
     *
     * @return Total number of records.
     */

    public Integer getCount() {
        return this.count;
    }

    /**
     * Total number of records.
     *
     * @param count
     *        Total number of records.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public ListRecordsResult withCount(Integer count) {
        setCount(count);
        return this;
    }

    /**
     * Server sync count for this dataset.
     *
     * @param datasetSyncCount
     *        Server sync count for this dataset.
     */

    public void setDatasetSyncCount(Long datasetSyncCount) {
        this.datasetSyncCount = datasetSyncCount;
    }

    /**
     * Server sync count for this dataset.
     *
     * @return Server sync count for this dataset.
     */

    public Long getDatasetSyncCount() {
        return this.datasetSyncCount;
    }

    /**
     * Server sync count for this dataset.
     *
     * @param datasetSyncCount
     *        Server sync count for this dataset.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public ListRecordsResult withDatasetSyncCount(Long datasetSyncCount) {
        setDatasetSyncCount(datasetSyncCount);
        return this;
    }

    /**
     * The user/device that made the last change to this record.
     *
     * @param lastModifiedBy
     *        The user/device that made the last change to this record.
     */

    public void setLastModifiedBy(String lastModifiedBy) {
        this.lastModifiedBy = lastModifiedBy;
    }

    /**
     * The user/device that made the last change to this record.
     *
     * @return The user/device that made the last change to this record.
     */

    public String getLastModifiedBy() {
        return this.lastModifiedBy;
    }

    /**
     * The user/device that made the last change to this record.
     *
     * @param lastModifiedBy
     *        The user/device that made the last change to this record.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public ListRecordsResult withLastModifiedBy(String lastModifiedBy) {
        setLastModifiedBy(lastModifiedBy);
        return this;
    }

    /**
     * Names of merged datasets.
     *
     * @return Names of merged datasets.
     */

    public java.util.List<String> getMergedDatasetNames() {
        if (mergedDatasetNames == null) {
            mergedDatasetNames = new com.amazonaws.internal.SdkInternalList<String>();
        }
        return mergedDatasetNames;
    }

    /**
     * Names of merged datasets.
     *
     * @param mergedDatasetNames
     *        Names of merged datasets.
     */

    public void setMergedDatasetNames(
            java.util.Collection<String> mergedDatasetNames) {
        if (mergedDatasetNames == null) {
            this.mergedDatasetNames = null;
            return;
        }

        this.mergedDatasetNames = new com.amazonaws.internal.SdkInternalList<String>(
                mergedDatasetNames);
    }

    /**
     * Names of merged datasets.
     *

     * NOTE: This method appends the values to the existing list (if
     * any). Use {@link #setMergedDatasetNames(java.util.Collection)} or
     * {@link #withMergedDatasetNames(java.util.Collection)} if you want to
     * override the existing values.
     *

     *
     * @param mergedDatasetNames
     *        Names of merged datasets.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public ListRecordsResult withMergedDatasetNames(
            String... mergedDatasetNames) {
        if (this.mergedDatasetNames == null) {
            setMergedDatasetNames(new com.amazonaws.internal.SdkInternalList<String>(
                    mergedDatasetNames.length));
        }
        for (String ele : mergedDatasetNames) {
            this.mergedDatasetNames.add(ele);
        }
        return this;
    }

    /**
     * Names of merged datasets.
     *
     * @param mergedDatasetNames
     *        Names of merged datasets.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public ListRecordsResult withMergedDatasetNames(
            java.util.Collection<String> mergedDatasetNames) {
        setMergedDatasetNames(mergedDatasetNames);
        return this;
    }

    /**
     * Indicates whether the dataset exists.
     *
     * @param datasetExists
     *        Indicates whether the dataset exists.
     */

    public void setDatasetExists(Boolean datasetExists) {
        this.datasetExists = datasetExists;
    }

    /**
     * Indicates whether the dataset exists.
     *
     * @return Indicates whether the dataset exists.
     */

    public Boolean getDatasetExists() {
        return this.datasetExists;
    }

    /**
     * Indicates whether the dataset exists.
     *
     * @param datasetExists
     *        Indicates whether the dataset exists.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public ListRecordsResult withDatasetExists(Boolean datasetExists) {
        setDatasetExists(datasetExists);
        return this;
    }

    /**
     * Indicates whether the dataset exists.
     *
     * @return Indicates whether the dataset exists.
     */

    public Boolean isDatasetExists() {
        return this.datasetExists;
    }

    /**
     * A boolean value specifying whether to delete the dataset locally.
     *
     * @param datasetDeletedAfterRequestedSyncCount
     *        A boolean value specifying whether to delete the dataset locally.
     */

    public void setDatasetDeletedAfterRequestedSyncCount(
            Boolean datasetDeletedAfterRequestedSyncCount) {
        this.datasetDeletedAfterRequestedSyncCount = datasetDeletedAfterRequestedSyncCount;
    }

    /**
     * A boolean value specifying whether to delete the dataset locally.
     *
     * @return A boolean value specifying whether to delete the dataset locally.
     */

    public Boolean getDatasetDeletedAfterRequestedSyncCount() {
        return this.datasetDeletedAfterRequestedSyncCount;
    }

    /**
     * A boolean value specifying whether to delete the dataset locally.
     *
     * @param datasetDeletedAfterRequestedSyncCount
     *        A boolean value specifying whether to delete the dataset locally.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public ListRecordsResult withDatasetDeletedAfterRequestedSyncCount(
            Boolean datasetDeletedAfterRequestedSyncCount) {
        setDatasetDeletedAfterRequestedSyncCount(datasetDeletedAfterRequestedSyncCount);
        return this;
    }

    /**
     * A boolean value specifying whether to delete the dataset locally.
     *
     * @return A boolean value specifying whether to delete the dataset locally.
     */

    public Boolean isDatasetDeletedAfterRequestedSyncCount() {
        return this.datasetDeletedAfterRequestedSyncCount;
    }

    /**
     * A token containing a session ID, identity ID, and expiration.
     *
     * @param syncSessionToken
     *        A token containing a session ID, identity ID, and expiration.
     */

    public void setSyncSessionToken(String syncSessionToken) {
        this.syncSessionToken = syncSessionToken;
    }

    /**
     * A token containing a session ID, identity ID, and expiration.
     *
     * @return A token containing a session ID, identity ID, and expiration.
     */

    public String getSyncSessionToken() {
        return this.syncSessionToken;
    }

    /**
     * A token containing a session ID, identity ID, and expiration.
     *
     * @param syncSessionToken
     *        A token containing a session ID, identity ID, and expiration.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public ListRecordsResult withSyncSessionToken(String syncSessionToken) {
        setSyncSessionToken(syncSessionToken);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getRecords() != null)
            sb.append("Records: " + getRecords() + ",");
        if (getNextToken() != null)
            sb.append("NextToken: " + getNextToken() + ",");
        if (getCount() != null)
            sb.append("Count: " + getCount() + ",");
        if (getDatasetSyncCount() != null)
            sb.append("DatasetSyncCount: " + getDatasetSyncCount() + ",");
        if (getLastModifiedBy() != null)
            sb.append("LastModifiedBy: " + getLastModifiedBy() + ",");
        if (getMergedDatasetNames() != null)
            sb.append("MergedDatasetNames: " + getMergedDatasetNames() + ",");
        if (getDatasetExists() != null)
            sb.append("DatasetExists: " + getDatasetExists() + ",");
        if (getDatasetDeletedAfterRequestedSyncCount() != null)
            sb.append("DatasetDeletedAfterRequestedSyncCount: "
                    + getDatasetDeletedAfterRequestedSyncCount() + ",");
        if (getSyncSessionToken() != null)
            sb.append("SyncSessionToken: " + getSyncSessionToken());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof ListRecordsResult == false)
            return false;
        ListRecordsResult other = (ListRecordsResult) obj;
        if (other.getRecords() == null ^ this.getRecords() == null)
            return false;
        if (other.getRecords() != null
                && other.getRecords().equals(this.getRecords()) == false)
            return false;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null
                && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        if (other.getCount() == null ^ this.getCount() == null)
            return false;
        if (other.getCount() != null
                && other.getCount().equals(this.getCount()) == false)
            return false;
        if (other.getDatasetSyncCount() == null
                ^ this.getDatasetSyncCount() == null)
            return false;
        if (other.getDatasetSyncCount() != null
                && other.getDatasetSyncCount().equals(
                        this.getDatasetSyncCount()) == false)
            return false;
        if (other.getLastModifiedBy() == null
                ^ this.getLastModifiedBy() == null)
            return false;
        if (other.getLastModifiedBy() != null
                && other.getLastModifiedBy().equals(this.getLastModifiedBy()) == false)
            return false;
        if (other.getMergedDatasetNames() == null
                ^ this.getMergedDatasetNames() == null)
            return false;
        if (other.getMergedDatasetNames() != null
                && other.getMergedDatasetNames().equals(
                        this.getMergedDatasetNames()) == false)
            return false;
        if (other.getDatasetExists() == null ^ this.getDatasetExists() == null)
            return false;
        if (other.getDatasetExists() != null
                && other.getDatasetExists().equals(this.getDatasetExists()) == false)
            return false;
        if (other.getDatasetDeletedAfterRequestedSyncCount() == null
                ^ this.getDatasetDeletedAfterRequestedSyncCount() == null)
            return false;
        if (other.getDatasetDeletedAfterRequestedSyncCount() != null
                && other.getDatasetDeletedAfterRequestedSyncCount().equals(
                        this.getDatasetDeletedAfterRequestedSyncCount()) == false)
            return false;
        if (other.getSyncSessionToken() == null
                ^ this.getSyncSessionToken() == null)
            return false;
        if (other.getSyncSessionToken() != null
                && other.getSyncSessionToken().equals(
                        this.getSyncSessionToken()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode
                + ((getRecords() == null) ? 0 : getRecords().hashCode());
        hashCode = prime * hashCode
                + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        hashCode = prime * hashCode
                + ((getCount() == null) ? 0 : getCount().hashCode());
        hashCode = prime
                * hashCode
                + ((getDatasetSyncCount() == null) ? 0 : getDatasetSyncCount()
                        .hashCode());
        hashCode = prime
                * hashCode
                + ((getLastModifiedBy() == null) ? 0 : getLastModifiedBy()
                        .hashCode());
        hashCode = prime
                * hashCode
                + ((getMergedDatasetNames() == null) ? 0
                        : getMergedDatasetNames().hashCode());
        hashCode = prime
                * hashCode
                + ((getDatasetExists() == null) ? 0 : getDatasetExists()
                        .hashCode());
        hashCode = prime
                * hashCode
                + ((getDatasetDeletedAfterRequestedSyncCount() == null) ? 0
                        : getDatasetDeletedAfterRequestedSyncCount().hashCode());
        hashCode = prime
                * hashCode
                + ((getSyncSessionToken() == null) ? 0 : getSyncSessionToken()
                        .hashCode());
        return hashCode;
    }

    @Override
    public ListRecordsResult clone() {
        try {
            return (ListRecordsResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException(
                    "Got a CloneNotSupportedException from Object.clone() "
                            + "even though we're Cloneable!", e);
        }
    }
}


text:
// Copyright 2020 Google LLC
//
// 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
//
//      https://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.

// For vsyslog
#define _BSD_SOURCE
#define _DEFAULT_SOURCE

#include "login.h"

#include <assert.h>
#include <errno.h>
#include <glome.h>
#include <limits.h>
#include <netdb.h>
#include <openssl/crypto.h>
#include <signal.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <syslog.h>
#include <time.h>
#include <unistd.h>

#include "base64.h"
#include "crypto.h"
#include "ui.h"

#define PROMPT "> "

#define DMI_UUID_PATH "/sys/class/dmi/id/product_uuid"
#define DMI_UUID_SIZE 36

#define UNUSED(var) (void)(var)

static int get_hostname(char* buf, size_t buflen) {
  if (gethostname(buf, buflen) != 0) {
    return -1;
  }
  buf[buflen - 1] = '\0';

  // Regular hostname is likely fully qualified, so stop here and return it.
  if (strchr(buf, '.') != NULL) {
    return 0;
  }

  // Retry using getaddrinfo to get an FQDN.
  struct addrinfo* res = NULL;
  struct addrinfo hints;
  memset(&hints, 0, sizeof(struct addrinfo));
  hints.ai_socktype = SOCK_DGRAM;
  hints.ai_flags = AI_CANONNAME;
  int ret;
  if ((ret = getaddrinfo(buf, NULL, &hints, &res)) != 0) {
    return -1;
  }
  strncpy(buf, res->ai_canonname, buflen - 1);
  buf[buflen - 1] = '\0';
  freeaddrinfo(res);
  return 0;
}

int failure(int code, const char** error_tag, const char* message) {
  if (error_tag != NULL && *error_tag == NULL) {
    *error_tag = message;
  }
  return code;
}

int get_machine_id(char* buf, size_t buflen, const char** error_tag) {
  if (get_hostname(buf, buflen) == 0) {
    return 0;
  }
  if (DMI_UUID_SIZE + 1 > buflen) {
    return failure(EXITCODE_PANIC, error_tag, "dmi-uuid-size");
  }
  FILE* fd;
  fd = fopen(DMI_UUID_PATH, "r");
  if (fd != NULL) {
    errorf("Unable to obtain hostname. Using DMI UUID instead.\n");
    if (fread(buf, DMI_UUID_SIZE, 1, fd) == 1) {
      buf[DMI_UUID_SIZE] = '\0';
      fclose(fd);
      return 0;
    }
    errorf("ERROR reading DMI product UUID (eof=%d, err=%d)\n", feof(fd),
           ferror(fd));
    fclose(fd);
  } else {
    perror("ERROR opening DMI product UUID file");
  }
  return -1;
}

void timeout_handler(int sig) {
  UNUSED(sig);
  errorf("Timed out while waiting for user input.\n");
  exit(EXITCODE_TIMEOUT);
}

int shell_action(const char* user, char** action, size_t* action_len,
                 const char** error_tag) {
  size_t buf_len = strlen("shell/") + strlen(user) + 1;
  char* buf = calloc(buf_len, 1);
  if (buf == NULL) {
    return failure(EXITCODE_PANIC, error_tag, "message-calloc-error");
  }
  int ret = snprintf(buf, buf_len, "shell/%s", user);
  if (ret < 0) {
    free(buf);
    return failure(EXITCODE_PANIC, error_tag, "message-sprintf-error");
  }
  if ((size_t)ret >= buf_len) {
    free(buf);
    return failure(EXITCODE_PANIC, error_tag, "message-sprintf-trunc");
  }

  *action = buf;
  *action_len = buf_len;
  return 0;
}

char* escape_host(const char* host) {
  size_t host_len = strlen(host);
  char *ret = malloc(host_len * 3 + 1), *ret_end = ret;
  if (ret == NULL) {
    return NULL;
  }
  // Only /, ?, and # would be problematic given our URL encoding
  for (size_t i = 0; i < host_len; ++i) {
    if (host[i] == '/' || host[i] == '?' || host[i] == '#') {
      sprintf(ret_end, "%%%02X", host[i]);
      ret_end += 3;
    } else {
      ret_end[0] = host[i];
      ret_end += 1;
    }
  }
  ret_end[0] = '\0';
  return ret;
}

int request_url(const uint8_t service_key[GLOME_MAX_PUBLIC_KEY_LENGTH],
                int service_key_id, const uint8_t public_key[PUBLIC_KEY_LENGTH],
                const char* host_id, const char* action,
                const uint8_t prefix_tag[GLOME_MAX_TAG_LENGTH],
                size_t prefix_tag_len, char** url, int* url_len,
                const char** error_tag) {
  if (prefix_tag_len > GLOME_MAX_TAG_LENGTH) {
    return failure(EXITCODE_PANIC, error_tag, "prefix-tag-too-large");
  }
  // glome-handshake := base64url(
  //  <prefix-type>
  //  <prefix7>
  //  <eph-key>
  //  [<prefixN>]
  //)
  uint8_t handshake[PUBLIC_KEY_LENGTH + 1 + GLOME_MAX_TAG_LENGTH] = {0};
  size_t handshake_len = PUBLIC_KEY_LENGTH + 1 + prefix_tag_len;

  if (service_key_id == 0) {
    // If no key ID was specified, send the first key byte as the ID.
    handshake[0] = service_key[0] & 0x7f;
  } else {
    handshake[0] = service_key_id & 0x7f;
  }

  memcpy(handshake + 1, public_key, PUBLIC_KEY_LENGTH);
  if (prefix_tag_len > 0) {
    memcpy(handshake + PUBLIC_KEY_LENGTH + 1, prefix_tag, prefix_tag_len);
  }

  char handshake_encoded[ENCODED_BUFSIZE(sizeof handshake)] = {0};
  if (!base64url_encode(handshake, handshake_len, (uint8_t*)handshake_encoded,
                        sizeof handshake_encoded)) {
    return failure(EXITCODE_PANIC, error_tag, "handshake-encode");
  }

  char* host_id_escaped = escape_host(host_id);
  if (host_id_escaped == NULL) {
    return failure(EXITCODE_PANIC, error_tag, "host-id-malloc-error");
  }

  int len = strlen("/v1/") + strlen(handshake_encoded) + 1 +
            strlen(host_id_escaped) + 1 + strlen(action) + 2;
  char* buf = malloc(len);
  if (buf == NULL) {
    free(host_id_escaped);
    return failure(EXITCODE_PANIC, error_tag, "url-malloc-error");
  }
  int ret = snprintf(buf, len, "/v1/%s/%s/%s/", handshake_encoded,
                     host_id_escaped, action);
  free(host_id_escaped);
  host_id_escaped = NULL;
  if (ret < 0) {
    free(buf);
    return failure(EXITCODE_PANIC, error_tag, "url-sprintf-error");
  }
  if (ret >= len) {
    free(buf);
    return failure(EXITCODE_PANIC, error_tag, "url-sprintf-trunc");
  }

  *url = buf;
  *url_len = len;
  return 0;
}

#ifndef PAM_GLOME
void login_error(glome_login_config_t* config, pam_handle_t* pamh,
                 const char* format, ...) {
  UNUSED(config);
  UNUSED(pamh);
  va_list args;
  va_start(args, format);
  vfprintf(stderr, format, args);
  va_end(args);
  fflush(NULL);
}

void login_syslog(glome_login_config_t* config, pam_handle_t* pamh,
                  int priority, const char* format, ...) {
  UNUSED(pamh);
  if (config->options & SYSLOG) {
    va_list args;
    va_start(args, format);
    vsyslog(priority, format, args);
    va_end(args);
  }
}

// read_stdin reads characters from stdin into buf. It returns:
// -1, if it encounters an error while reading
// -2, if it encounters invalid characters in the input
// (buflen-1) if it read buflen-1 characters
// <(buflen-1), if a newline was read before the buffer was full
// If the return value is >=0, the buf is NULL-terminated.
// Additionally, stdin is always advanced up to a newline (or EOF)
// to prevent excess input from being read by a future shell process.
static int read_stdin(char* buf, int buflen) {
  // Return error if we got no characters.
  if (fgets(buf, buflen, stdin) == NULL) {
    perror("ERROR when reading from stdin");
    return -1;
  }

  bool newline = false;
  int len = strlen(buf);
  if (buf[len - 1] == '\n') {
    newline = true;
    buf[len - 1] = '\0';
    len--;
  }

  // Return error if we got a non-printable character.
  for (int i = 0; i < len; i++) {
    if (buf[i] < 0x20 || buf[i] > 0x7e) {
      errorf("ERROR invalid characters read from stdin\n");
      return -2;
    }
  }

  // Read stdin until a newline to avoid passing junk to shell.
  if (!newline) {
    for (int c = 0; c != EOF && c != '\n'; c = fgetc(stdin)) {
    }
  }

  return len;  // Number of characters in the buffer without the NULL byte.
}

static void print_hex(const uint8_t* buf, size_t len) {
  for (size_t i = 0; i < len; i++) {
    errorf("%02x", buf[i]);
  }
  errorf("\n");
}

int login_prompt(glome_login_config_t* config, pam_handle_t* pamh,
                 const char** error_tag, const char* message, char* input,
                 size_t input_size) {
  UNUSED(pamh);
  UNUSED(error_tag);

  puts(message);
  fputs(PROMPT, stdout);
  fflush(NULL);

  if (config->input_timeout_sec) {
    struct sigaction action = {.sa_handler = &timeout_handler};
    if (sigaction(SIGALRM, &action, NULL) < 0) {
      perror("error while setting up the handler");
      // Continue nonetheless as the handler is not critical.
    }
    // Set an alarm to prevent waiting for the code indefinitely.
    alarm(config->input_timeout_sec);
  }

  int bytes_read = read_stdin(input, input_size);

  // Cancel any pending alarms.
  alarm(0);

  if (bytes_read < 0) {
    return EXITCODE_IO_ERROR;
  }
  if (config->options & VERBOSE) {
    errorf("debug: stdin: ");
    print_hex((uint8_t*)input, bytes_read);
  }
  return 0;
}
#endif

int login_authenticate(glome_login_config_t* config, pam_handle_t* pamh,
                       const char* prompt_format, const char** error_tag) {
  if (is_zeroed(config->service_key, sizeof config->service_key)) {
    return failure(EXITCODE_PANIC, error_tag, "no-service-key");
  }

  uint8_t public_key[PUBLIC_KEY_LENGTH] = {0};
  if (derive_or_generate_key(config->secret_key, public_key)) {
    return failure(EXITCODE_PANIC, error_tag, "derive-or-generate-key");
  }

  char* host_id = NULL;
  if (config->host_id != NULL) {
    host_id = strdup(config->host_id);
  } else {
    host_id = calloc(HOST_NAME_MAX + 1, 1);
    if (get_machine_id(host_id, HOST_NAME_MAX + 1, error_tag) < 0) {
      return failure(EXITCODE_PANIC, error_tag, "get-machine-id");
    }
  }

  char* action = NULL;
  size_t action_len = 0;

  if (shell_action(config->username, &action, &action_len, error_tag)) {
    free(host_id);
    return EXITCODE_PANIC;
  }

  if (config->options & VERBOSE) {
    login_syslog(config, pamh, LOG_DEBUG, "host ID: %s, action: %s", host_id,
                 action);
  }

  uint8_t authcode[GLOME_MAX_TAG_LENGTH];
  if (get_authcode(host_id, action, config->service_key, config->secret_key,
                   authcode)) {
    free(host_id);
    free(action);
    return failure(EXITCODE_PANIC, error_tag, "get-authcode");
  }

  char* url = NULL;
  int url_len = 0;
  if (request_url(config->service_key, config->service_key_id, public_key,
                  host_id, action, /*prefix_tag=*/NULL,
                  /*prefix_tag_len=*/0, &url, &url_len, error_tag)) {
    free(host_id);
    free(action);
    return EXITCODE_PANIC;
  }

  free(host_id);
  host_id = NULL;
  free(action);
  action = NULL;

  const char* prefix = "";
  if (config->url_prefix != NULL) {
    prefix = config->url_prefix;
  }
  size_t message_len =
      strlen(prompt_format) + strlen(prefix) - 2 + strlen(url) - 2 + 1;
  char* message = malloc(message_len);
  if (message == NULL) {
    return failure(EXITCODE_PANIC, error_tag, "malloc-message");
  }
  int written = snprintf(message, message_len, prompt_format, prefix, url);
  if (written < 0 || (size_t)written >= message_len) {
    free(message);
    return failure(EXITCODE_PANIC, error_tag, "broken-template");
  }
  free(url);
  url = NULL;

  char input[ENCODED_BUFSIZE(GLOME_MAX_TAG_LENGTH)];
  int rc = login_prompt(config, pamh, error_tag, message, input, sizeof(input));
  free(message);
  if (rc != 0) {
    return rc;
  }

  int bytes_read = strlen(input);
  if (config->options & INSECURE) {
    login_syslog(config, pamh, LOG_DEBUG, "user input: %s", input);
  }

  // Calculate the correct authcode.
  char authcode_encoded[ENCODED_BUFSIZE(sizeof authcode)] = {0};
  if (base64url_encode(authcode, sizeof authcode, (uint8_t*)authcode_encoded,
                       sizeof authcode_encoded) == 0) {
    return failure(EXITCODE_PANIC, error_tag, "authcode-encode");
  }
  if (config->options & INSECURE) {
    login_syslog(config, pamh, LOG_DEBUG, "expect input: %s", authcode_encoded);
  }

  if (bytes_read < MIN_ENCODED_AUTHCODE_LEN) {
    login_syslog(config, pamh, LOG_INFO, "authcode too short: %d bytes (%s)",
                 bytes_read, config->username);
    login_error(config, pamh,
                "Input too short: expected at least %d characters, got %d.\n",
                MIN_ENCODED_AUTHCODE_LEN, bytes_read);
    return failure(EXITCODE_INVALID_INPUT_SIZE, error_tag, "authcode-length");
  }
  if ((size_t)bytes_read > strlen(authcode_encoded)) {
    login_syslog(config, pamh, LOG_INFO, "authcode too long: %d bytes (%s)",
                 bytes_read, config->username);
    login_error(config, pamh,
                "Input too long: expected at most %zu characters, got %d.\n",
                strlen(authcode_encoded), bytes_read);
    return failure(EXITCODE_INVALID_INPUT_SIZE, error_tag, "authcode-length");
  }

  // Since we use (relatively) short auth codes, sleep before confirming the
  // result to prevent bruteforcing.
  if (config->auth_delay_sec) {
    struct timespec delay;
    delay.tv_sec = (time_t)config->auth_delay_sec;
    delay.tv_nsec = 0;
    if (nanosleep(&delay, NULL) != 0) {
      login_error(config, pamh, "interrupted sleep: %s", strerror(errno));
      return failure(EXITCODE_INTERRUPTED, error_tag, "sleep-interrupted");
    }
  }

  if (CRYPTO_memcmp(input, authcode_encoded, bytes_read) != 0) {
    login_syslog(config, pamh, LOG_WARNING, "authcode rejected (%s)",
                 config->username);
    login_error(config, pamh, "Invalid authorization code.\n");
    return failure(EXITCODE_INVALID_AUTHCODE, error_tag, "authcode-invalid");
  }

  return 0;
}

int login_run(glome_login_config_t* config, const char** error_tag) {
  assert(config != NULL);
  if (config->options & VERBOSE) {
    errorf(
        "debug: options: 0x%x\n"
        "debug: username: %s\n"
        "debug: login: %s\n"
        "debug: auth delay: %d seconds\n",
        config->options, config->username, config->login_path,
        config->auth_delay_sec);
  }
  if (config->options & SYSLOG) {
    openlog("glome-login", LOG_PID | LOG_CONS, LOG_AUTH);
  }

  int r = login_authenticate(
      config, NULL, "Obtain the one-time authorization code from:\n%s%s",
      error_tag);
  if (r != 0) {
    return r;
  }

  if (config->options & SYSLOG) {
    syslog(LOG_WARNING, "authcode accepted (%s)", config->username);
  }
  puts("Authorization code: OK");
  fflush(NULL);

  execl(config->login_path, config->login_path, "-f", config->username,
        (char*)NULL);
  perror("ERROR while executing login");
  return failure(EXITCODE_PANIC, error_tag, "login-exec");
}


text:
{{#server}}
## Required software

- [Node.js](https://nodejs.org/en/) >=10.15.0

## Configuration

The following environment variables can be used to configure the server:

- `NODE_ENV` : the environment mode, either `production` or `development` (default)
- `PORT` : the port on which the server runs (default 3000)
- `LOG_LEVEL` : the log level for `out.log`
{{/server}}

## Run targets

{{#clientOrServer}}
- `npm start` : start the server
- `npm stop` : stop the server
{{/clientOrServer}}
- `npm run build` : build project
- `npm run build-prod` : build the project for production
{{#client}}
- `npm run bundle-profile` : visualise the bundle dependencies
{{/client}}
- `npm run clean` : clean the project
- `npm run watch` : watch mode (debug mode enabled, autorebuild, autoreload)
- `npm test` : run tests
- `npm run lint` : lint the project
- `npm run ci` : run linting & tests (like Travis CI)

{{#clientOrServer}}
## Running via Docker

Build the container.  Here, `{{name}}` is used as the container name.

```
cd {{name}}
docker build -t {{name}} .
```

Run the container:

```
docker run -it -p 12345:3000 -u "node" -e "NODE_ENV=production" --name "{{name}}" {{name}}
```

Notes:

- The `-it` switches are necessary to make `node` respond to `ctrl+c` etc. in `docker`.
- The `-p` switch indicates that port 3000 on the container is mapped to port 12345 on the host.  Without this switch, the server is inaccessible.
- The `-u` switch is used so that a non-root user is used inside the container.
- The `-e` switch is used to set environment variables.  Alternatively use `--env-file` to use a file with the environment variables.
- References:
  - [Dockerizing a Node.js web app](https://nodejs.org/en/docs/guides/nodejs-docker-webapp/)
  - [Documentation of docker-node](https://github.com/nodejs/docker-node)
  - [Docker CLI docs](https://docs.docker.com/engine/reference/commandline/cli/)
{{/clientOrServer}}

## Testing

All files `/test` will be run by [Mocha](https://mochajs.org/).  You can `npm test` to run all tests, or you can run `npm test -- -g specific-test-name` to run specific tests.

[Chai](http://chaijs.com/) is included to make the tests easier to read and write.

## Publishing a release

1. Make sure the tests are passing: `npm test`
1. Make sure the linting is passing: `npm run lint`
1. Bump the version number with `npm version`, in accordance with [semver](http://semver.org/).  The `version` command in `npm` updates both `package.json` and git tags, but note that it uses a `v` prefix on the tags (e.g. `v1.2.3`).
  1. For a bug fix / patch release, run `npm version patch`.
  1. For a new feature release, run `npm version minor`.
  1. For a breaking API change, run `npm version major.`
  1. For a specific version number (e.g. 1.2.3), run `npm version 1.2.3`.
1. Push the release: `git push origin --tags`
{{#lib}}1. Publish to npm: `npm publish .`{{/lib}}


text:
package org.jboss.netty.handler.codec.marshalling;

import org.jboss.marshalling.MarshallerFactory;
import org.jboss.marshalling.Marshalling;
import org.jboss.marshalling.MarshallingConfiguration;

public class RiverCompatibleMarshallingEncoderTest extends AbstractCompatibleMarshallingEncoderTest {

    @Override
    protected MarshallerFactory createMarshallerFactory() {
        return Marshalling.getProvidedMarshallerFactory("river");
    }

    @Override
    protected MarshallingConfiguration createMarshallingConfig() {
        // Create a configuration
        final MarshallingConfiguration configuration = new MarshallingConfiguration();
        configuration.setVersion(3);
        return configuration;
    }

}


text:
/*
 * MouseClickMessage.cpp
 *
 *  Created on: 22 Aug 2014
 *      Author: deano
 */

#include "MouseClickMessage.h"

MouseClickMessage::MouseClickMessage(const std::string& messageId,
                                     MouseButton button,
                                     int positionX,
                                     int positionY,
                                     bool pressed) :
    Message(messageId)
{
  this->button_ = button;
  this->positionX_ = positionX;
  this->positionY_ = positionY;
  this->pressed_ = pressed;
}

MouseClickMessage::~MouseClickMessage()
{

}

MouseButton MouseClickMessage::getButton() const
{
  return this->button_;
}

int MouseClickMessage::getPositionX() const
{
  return this->positionX_;
}

int MouseClickMessage::getPositionY() const
{
  return this->positionY_;
}

bool MouseClickMessage::isPressed() const
{
  return this->pressed_;
}


text:
FactoryGirl.define do
  factory :bargin do
    name "MyString"
    offer "MyString"
    type ""
    description "MyText"
    url "MyString"
    product_id "MyString"
  end
end


text:
import datetime
import os
from . import bootstrap

PROJECT_NAME = input("Project name: ")
AUTHOR = input("Author name: ")
EMAIL = input("Email: ")
YEAR = datetime.date.today().year
SHORT_DESCRIPTION = input("Short description: ")

if not os.path.exists(PROJECT_NAME):
    bootstrap.make_proj(PROJECT_NAME, AUTHOR, YEAR, EMAIL, SHORT_DESCRIPTION)
else:
    raise SystemError("A directory for" + PROJECT_NAME + "already exists.")


text:
def plural(n):
    if n == 1:
        return False
    else:
        return True


text:
class CreateResponses < ActiveRecord::Migration
  def change
      create_table :responses do |t|
      t.integer :survey_id
      t.integer :question_id
      t.integer :choice_id
      t.integer :vote_count, :default => 0

      t.timestamp
    end
  end
end


text:
package org.runetranscriber.core;

/**
 * Defines methods required by a full transcriber from language letters to font letters.
 *
 * @param <R> Rune type parameter.
 * @param <F> Font letter type parameter.
 */
public interface FullTranscriber<R extends Rune, F extends FontLetter> extends
        Transcriber<LanguageLetterList, String, FontLetterList<F>, F>
{
    /**
     * @return the description
     */
    public String getDescription();

    /**
     * @return the displayName
     */
    public String getDisplayName();

    /**
     * @return the fontLetters
     */
    public FontLetterList<F> getFontLetters();

    /**
     * @return the fontTranscriber
     */
    public FontTranscriber<R, F> getFontTranscriber();

    /**
     * @return the languageLetters
     */
    public LanguageLetterList getLanguageLetters();

    /**
     * @return the phonemes
     */
    public PhonemeList getPhonemes();

    /**
     * @return the phoneticTranscriber
     */
    public PhoneticTranscriber getPhoneticTranscriber();

    /**
     * @return the runes
     */
    public RuneList<R> getRunes();

    /**
     * @return the runeTranscriber
     */
    public RuneTranscriber<R> getRuneTranscriber();
}


text:
(function() {
    'use strict';

    angular
        .module('cpvApp')
        .controller('AuditsController', AuditsController);

    AuditsController.$inject = ['$filter', 'AuditsService', 'ParseLinks'];

    function AuditsController ($filter, AuditsService, ParseLinks) {
        var vm = this;

        vm.audits = null;
        vm.fromDate = null;
        vm.links = null;
        vm.loadPage = loadPage;
        vm.onChangeDate = onChangeDate;
        vm.page = 1;
        vm.previousMonth = previousMonth;
        vm.toDate = null;
        vm.today = today;
        vm.totalItems = null;

        vm.today();
        vm.previousMonth();
        vm.onChangeDate();

        function onChangeDate () {
            var dateFormat = 'yyyy-MM-dd';
            var fromDate = $filter('date')(vm.fromDate, dateFormat);
            var toDate = $filter('date')(vm.toDate, dateFormat);

            AuditsService.query({page: vm.page -1, size: 20, fromDate: fromDate, toDate: toDate}, function(result, headers){
                vm.audits = result;
                vm.links = ParseLinks.parse(headers('link'));
                vm.totalItems = headers('X-Total-Count');
            });
        }

        // Date picker configuration
        function today () {
            // Today + 1 day - needed if the current day must be included
            var today = new Date();
            vm.toDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1);
        }

        function previousMonth () {
            var fromDate = new Date();
            if (fromDate.getMonth() === 0) {
                fromDate = new Date(fromDate.getFullYear() - 1, 11, fromDate.getDate());
            } else {
                fromDate = new Date(fromDate.getFullYear(), fromDate.getMonth() - 1, fromDate.getDate());
            }

            vm.fromDate = fromDate;
        }

        function loadPage (page) {
            vm.page = page;
            vm.onChangeDate();
        }
    }
})();


text:
BIN_DIR=`dirname "$0"`
cd $BIN_DIR/../..

BASE_DIR=`pwd`

echo "Base Dir: " $BASE_DIR

rm -rf $BASE_DIR/package
rm -rf $BASE_DIR/OpenDNSMonitor
mkdir $BASE_DIR/package

cp README.md $BASE_DIR/package
cp runit.sh $BASE_DIR/package

###################
# Build and Package CLI for OSX
###################
echo "Building for OSX"
export GOOS="darwin"

mkdir $BASE_DIR/package/$GOOS
go build
mv OpenDNS_Monitor $BASE_DIR/package/$GOOS

###################
# Build and Package CLI for Linux
###################

echo "Building for Linux"
export GOOS="linux"

mkdir $BASE_DIR/package/$GOOS
go build
mv OpenDNS_Monitor $BASE_DIR/package/$GOOS

##################
# Build and Package CLI for Windowss
###################

echo "Building for Windows"
export GOOS="windows"

mkdir $BASE_DIR/package/$GOOS
go build
mv OpenDNS_Monitor.exe $BASE_DIR/package/$GOOS

###################
# Done!!!
###################
mv package OpenDNSMonitor
echo "Done..."
echo ""
echo "See $BASE_DIR/OpenDNSMonitor for binary files"
open $BASE_DIR/OpenDNSMonitor


text:
from django.dispatch import Signal

upcoming_invoice_updated = Signal(providing_args=['customer'])
invoice_updated = Signal(providing_args=['invoice'])

# Webhooks
recurring_payment_failed = Signal(providing_args=[
    'customer',
    'attempt',
    'invoice',
    'payment',
    'livemode',
])

invoice_ready = Signal(providing_args=[
    'customer',
    'invoice'
])

recurring_payment_succeeded = Signal(providing_args=[
    'customer',
    'invoice',
    'payment',
    'livemode',
])

subscription_trial_ending = Signal(providing_args=[
    'customer',
    'subscription',
])

subscription_final_payment_attempt_failed = Signal(providing_args=[
    'customer',
    'subscription',
])

ping = Signal()

class StripeWebhook(object):
    pass


text:
The source code of my [personal website](https://jr-cologne.de/).

## Requirements

- [Node.js](https://nodejs.org/en/)
- [Gulp 4](https://gulpjs.com/)
- [Ruby](https://www.ruby-lang.org/en/)
- [Jekyll](https://jekyllrb.com/)

## Contributing

Feel free to contribute to this project! Any kinds of contributions are highly appreciated!

## License

This project is licensed under the [MIT License](https://github.com/jr-cologne/jr-cologne.de/blob/master/LICENSE).

Please note that the German copyright (*Urheberrecht*) applies for the content of the website. Only the code itself here on GitHub is licensed under the MIT license!


text:
---
layout: page
title: ops-supervisor
category: blog
description:
date: 2018-09-27
---
# Preface
Supervisor 是一个超级简单的监控-重启命令
1. monitor 监控程序, 当其它程序发生错误时,自动重启
2. control a number of processes on UNIX-like operating systems.

# conf
	```
	$ cat /etc/supervisord.conf
	[include]
	files = supervisord.d/*.conf supervisord.d/*/*.conf

	$ cat /etc/supervisord.d/fetch_weibo.conf
	[program:fetch_weibo]
	command=/usr/local/bin/php fetch_weibo.php
	user=hilo
	directory=/home/hilo
	autostart=true
	startsecs=10
	autorestart=true
	startretries=100

	redirect_stderr         = true
	stdout_logfile_maxbytes = 50MB
	stdout_logfile_backups  = 10
	stdout_logfile          = /srv/awesome/log/app.log
	```

# 启动supervisor

	$ supervisord -c supervisord.conf
	$ systemctl start supervisord

	$ supervisord -c supervisord.conf reload
	$ systemctl reload supervisord

# 使用supervisorctl管理程序

	1)开启/停止某个程序
	 supervisorctl [start | stop | restart] [program名称]      //在supervisord.conf中定义的
	 supervisorctl start fetch_weibo

	2)查看进程状态
	supervisorctl status

# service 系统服务
/etc/init.d/supervisord

	#!/bin/sh
	# Source init functions
	. /etc/rc.d/init.d/functions

	prog="supervisord"

	prog_bin="/usr/local/bin/supervisord"
	PIDFILE="/tmp/supervisord.pid"

	start()
	{
	        echo -n $"Starting $prog: "

	# Source init functions
	. /etc/rc.d/init.d/functions

	prog="supervisord"

	prog_bin="/usr/local/bin/supervisord"
	PIDFILE="/tmp/supervisord.pid"
	start() {
	        echo -n $"Starting $prog: "
	        daemon $prog_bin --pidfile $PIDFILE
	        [ -f $PIDFILE ] && success $"$prog startup" || failure $"$prog startup"
	        echo
	}

	stop() {
	        echo -n $"Shutting down $prog: "
	        [ -f $PIDFILE ] && killproc $prog || success $"$prog shutdown"
	        echo
	}

	case "$1" in
	  start)
	    start
	  ;;
	  stop)
	    stop
	  ;;
	  status)
	        status $prog
	  ;;
	  restart)
	    stop
	    start
	  ;;
	  *)
	    echo "Usage: $0 {start|stop|restart|status}"
	  ;;

	esac

添加为系统服务

	mv supervisord.sh  /etc/init.d/supervisord
	chkconfig --add  supervisord
	chkconfig --level 345 supervisord on

start & stop:

	service supervisord [start | stop]


text:
"""
 SlipStream Client
 =====
 Copyright (C) 2014 SixSq Sarl (sixsq.com)
 =====
 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.
"""
from __future__ import print_function

import sys

from slipstream.command.VMCommandBase import VMCommandBase
from slipstream.util import truncate_middle
from slipstream.Client import Client
from slipstream.ConfigHolder import ConfigHolder
from slipstream.NodeDecorator import NodeDecorator

class MainProgram(VMCommandBase):
    '''A command-line program to set the abort state for a run.'''

    def __init__(self, argv=None):
        self.reason = None
        self.cancel = False
        super(MainProgram, self).__init__(argv)

    def parse(self):
        usage = '''usage: %prog [options] [--] [<reason>]

<reason>         Reason for abort.

Notice:
                 If the reason might start with a dash (-), please add the
                 two dashes (--) before the reason to prevent possible issues.'''

        self.parser.usage = usage

        self.parser.add_option('--cancel', dest='cancel',
                               help='cancel the abort status',
                               default=False, action='store_true')

        self.add_run_opts_and_parse()

        self._checkArgs()

        self.reason = (len(self.args) and self.args[0]) or '(unspecified)'

    def _checkArgs(self):
        if len(self.args) > 1:
            self.usageExitTooManyArguments()

    def doWork(self):
        ch = ConfigHolder(self.options)
        client = Client(ch)

        if self.options.cancel:
            client.cancel_abort()
        else:
            value = truncate_middle(Client.VALUE_LENGTH_LIMIT, self.reason,
                                    '\n(truncated)\n')
            client.setRuntimeParameter(NodeDecorator.ABORT_KEY, value)

if __name__ == "__main__":
    try:
        MainProgram()
    except KeyboardInterrupt:
        print('\n\nExecution interrupted by the user... goodbye!')
        sys.exit(-1)


text:
<?php

namespace Album\Model;

use Zend\Db\TableGateway\TableGateway;

class AlbumTable {

    protected $tableGateway;

    public function __construct(TableGateway $tableGateway) {
        $this->tableGateway = $tableGateway;
    }

    /* Return a RS */

    public function fetchAll() {
        return $this->tableGateway->select();
    }

    public function getAlbum($id) {
        $id = (int) $id;
        $rowSet = $this->tableGateway->select(array('id' => $id));
        $row = $rowSet->current();
        if (!$row)
            throw new \Exception("Cloud not find row $id");
        return $row;
    }

    /* Mesclado Editar e salvar (insert) */
    public function saveAlbum(Album $album) {
        $data = array(
            'artist' => $album->artist,
            'title'  => $album->title,
        );

        $id = (int) $album->id;
        if ($id == 0){
            $this->tableGateway->insert($data);
        }  else {
            if($this->getAlbum($id)){
                $this->tableGateway->update($data, array('id' => $id));
            }else{
                throw new \Exception ('Album ');
            }
        }
    }

    public function deleteAlbum($id){

        $this->tableGateway->delete(array('id' => (int) $id));

    }

}


text:
from .helpers import HelperClass

with description(HelperClass):
    pass


text:
def create_master_turnstile_file(filenames, output_file):
    '''
    Write a function that takes the files in the list filenames, which all have the
    columns 'C/A, UNIT, SCP, DATEn, TIMEn, DESCn, ENTRIESn, EXITSn', and consolidates
    them into one file located at output_file.  There should be ONE row with the column
    headers, located at the top of the file. The input files do not have column header
    rows of their own.

    For example, if file_1 has:
    line 1 ...
    line 2 ...

    and another file, file_2 has:
    line 3 ...
    line 4 ...
    line 5 ...

    We need to combine file_1 and file_2 into a master_file like below:
     'C/A, UNIT, SCP, DATEn, TIMEn, DESCn, ENTRIESn, EXITSn'
    line 1 ...
    line 2 ...
    line 3 ...
    line 4 ...
    line 5 ...
    '''
    with open(output_file, 'w') as master_file:
        master_file.write('C/A,UNIT,SCP,DATEn,TIMEn,DESCn,ENTRIESn,EXITSn\n')
        for filename in filenames:
            f_in = open(filename, 'r')
            for line in f_in:
                master_file.write(line)


text:
SearchNodeOp::SearchNodeOp(Operator op, SearchNode *left, SearchNode *right)
	: op(op), left(left), right(right)
{}

SearchNodeOp::~SearchNodeOp()
{
	delete left;
	delete right;
}

void SearchNodeOp::accept(SearchVisitor &v) const
{
	v.visit(*this);
}


text:
package com.example.hackro.pdfjet;

import org.junit.Test;

import static org.junit.Assert.*;

/**
 * To work on unit tests, switch the Test Artifact in the Build Variants view.
 */
public class ExampleUnitTest {
    @Test
    public void addition_isCorrect() throws Exception {
        assertEquals(4, 2 + 2);
    }
}