text:
<stix:STIX_Package
	xmlns:cyboxCommon="http://cybox.mitre.org/common-2"
	xmlns:cybox="http://cybox.mitre.org/cybox-2"
	xmlns:cyboxVocabs="http://cybox.mitre.org/default_vocabularies-2"
	xmlns:example="http://example.com"
	xmlns:incident="http://stix.mitre.org/Incident-1"
	xmlns:ttp="http://stix.mitre.org/TTP-1"
	xmlns:ta="http://stix.mitre.org/ThreatActor-1"
	xmlns:stixCommon="http://stix.mitre.org/common-1"
	xmlns:stixVocabs="http://stix.mitre.org/default_vocabularies-1"
	xmlns:stix-ciqidentity="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1"
	xmlns:stix="http://stix.mitre.org/stix-1"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:xal="urn:oasis:names:tc:ciq:xal:3"
	xmlns:xnl="urn:oasis:names:tc:ciq:xnl:3"
	xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3"
	xsi:schemaLocation="
	http://cybox.mitre.org/common-2 http://cybox.mitre.org/XMLSchema/common/2.1/cybox_common.xsd
	http://cybox.mitre.org/cybox-2 http://cybox.mitre.org/XMLSchema/core/2.1/cybox_core.xsd
	http://cybox.mitre.org/default_vocabularies-2 http://cybox.mitre.org/XMLSchema/default_vocabularies/2.1/cybox_default_vocabularies.xsd
	http://stix.mitre.org/Incident-1 http://stix.mitre.org/XMLSchema/incident/1.1.1/incident.xsd
	http://stix.mitre.org/TTP-1 http://stix.mitre.org/XMLSchema/ttp/1.1.1/ttp.xsd
	http://stix.mitre.org/ThreatActor-1 http://stix.mitre.org/XMLSchema/threat_actor/1.1.1/threat_actor.xsd
	http://stix.mitre.org/common-1 http://stix.mitre.org/XMLSchema/common/1.1.1/stix_common.xsd
	http://stix.mitre.org/default_vocabularies-1 http://stix.mitre.org/XMLSchema/default_vocabularies/1.1.1/stix_default_vocabularies.xsd
	http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1 http://stix.mitre.org/XMLSchema/extensions/identity/ciq_3.0/1.1.1/ciq_3.0_identity.xsd
	http://stix.mitre.org/stix-1 http://stix.mitre.org/XMLSchema/core/1.1.1/stix_core.xsd
	urn:oasis:names:tc:ciq:xal:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xAL.xsd
	urn:oasis:names:tc:ciq:xnl:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xNL.xsd
	urn:oasis:names:tc:ciq:xpil:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xPIL.xsd" id="example:Package-850caaef-a05f-4a38-ae0f-9dc04bab1c8a" version="1.1.1" timestamp="2014-07-28T12:43:00+00:00">
    <stix:TTPs>
        <stix:TTP id="example:ttp-6a990cfc-9927-4c78-aca6-19eb2289fb45" timestamp="2014-12-22T16:32:01.894000+00:00" xsi:type='ttp:TTPType'>
            <ttp:Behavior>
                <ttp:Attack_Patterns>
                    <ttp:Attack_Pattern capec_id="CAPEC-112">
                        <ttp:Title>Brute Force</ttp:Title>
                    </ttp:Attack_Pattern>
                </ttp:Attack_Patterns>
            </ttp:Behavior>
        </stix:TTP>
    </stix:TTPs>
    <stix:Incidents>
        <stix:Incident id="example:incident-d987cfde-73fe-451e-8d29-33cfda746d6d" timestamp="2014-07-28T12:43:00+00:00" xsi:type='incident:IncidentType'>
            <incident:Title>hotmail account hack to impair access to other e-mail accounts, takedown a facebook page and to get godaddy creds to delete site contents & de-register a domain name</incident:Title>
            <incident:External_ID source="VERIS">9FC3D60B-A20A-419D-A3CA-EEB8527B497D</incident:External_ID>
            <incident:Time>
                <incident:First_Malicious_Action precision="day">2012-02-07T00:00:00</incident:First_Malicious_Action>
                <incident:Initial_Compromise precision="day">2012-02-08T00:00:00</incident:Initial_Compromise>
                <incident:Incident_Discovery precision="hour">2012-02-08T01:00:00</incident:Incident_Discovery>
            </incident:Time>
            <incident:Reporter>
                <stixCommon:Identity xsi:type='stix-ciqidentity:CIQIdentity3.0InstanceType'>
                    <ExtSch:Specification xmlns:ExtSch="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1">
  <xpil:PartyName xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xnl:NameLine xmlns:xnl="urn:oasis:names:tc:ciq:xnl:3">hrbrmstr</xnl:NameLine>
  </xpil:PartyName>
</ExtSch:Specification>
                </stixCommon:Identity>
            </incident:Reporter>
            <incident:Victim xsi:type='stix-ciqidentity:CIQIdentity3.0InstanceType'>
                <ExtSch:Specification xmlns:ExtSch="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1">
  <xpil:PartyName xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xnl:NameLine xmlns:xnl="urn:oasis:names:tc:ciq:xnl:3">Jose Munoz</xnl:NameLine>
  </xpil:PartyName>
  <xpil:Addresses xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xpil:Address>
      <xal:Country xmlns:xal="urn:oasis:names:tc:ciq:xal:3">
        <xal:NameElement>US</xal:NameElement>
      </xal:Country>
      <xal:AdministrativeArea xmlns:xal="urn:oasis:names:tc:ciq:xal:3">
        <xal:NameElement>NY</xal:NameElement>
      </xal:AdministrativeArea>
    </xpil:Address>
  </xpil:Addresses>
</ExtSch:Specification>
            </incident:Victim>
            <incident:Affected_Assets>
                <incident:Affected_Asset>
                    <incident:Type>Mail</incident:Type>
                    <incident:Nature_Of_Security_Effect>
                        <incident:Property_Affected>
                            <incident:Property xsi:type="stixVocabs:LossPropertyVocab-1.0">Confidentiality</incident:Property>
                            <incident:Description_Of_Effect>Credentials: 6</incident:Description_Of_Effect>
                        </incident:Property_Affected>
                        <incident:Property_Affected>
                            <incident:Property xsi:type="stixVocabs:LossPropertyVocab-1.0">Integrity</incident:Property>
                            <incident:Description_Of_Effect>Fraudulent transaction,Defacement</incident:Description_Of_Effect>
                        </incident:Property_Affected>
                        <incident:Property_Affected>
                            <incident:Property xsi:type="stixVocabs:LossPropertyVocab-1.0">Availability</incident:Property>
                            <incident:Type_Of_Availability_Loss xsi:type="stixVocabs:AvailabilityLossTypeVocab-1.1.1">Loss</incident:Type_Of_Availability_Loss>
                        </incident:Property_Affected>
                    </incident:Nature_Of_Security_Effect>
                </incident:Affected_Asset>
                <incident:Affected_Asset>
                    <incident:Type>Web application</incident:Type>
                    <incident:Nature_Of_Security_Effect>
                        <incident:Property_Affected>
                            <incident:Property xsi:type="stixVocabs:LossPropertyVocab-1.0">Confidentiality</incident:Property>
                            <incident:Description_Of_Effect>Credentials: 6</incident:Description_Of_Effect>
                        </incident:Property_Affected>
                        <incident:Property_Affected>
                            <incident:Property xsi:type="stixVocabs:LossPropertyVocab-1.0">Integrity</incident:Property>
                            <incident:Description_Of_Effect>Fraudulent transaction,Defacement</incident:Description_Of_Effect>
                        </incident:Property_Affected>
                        <incident:Property_Affected>
                            <incident:Property xsi:type="stixVocabs:LossPropertyVocab-1.0">Availability</incident:Property>
                            <incident:Type_Of_Availability_Loss xsi:type="stixVocabs:AvailabilityLossTypeVocab-1.1.1">Loss</incident:Type_Of_Availability_Loss>
                        </incident:Property_Affected>
                    </incident:Nature_Of_Security_Effect>
                </incident:Affected_Asset>
            </incident:Affected_Assets>
            <incident:Impact_Assessment>
                <incident:Impact_Qualification xsi:type="stixVocabs:ImpactQualificationVocab-1.0">Unknown</incident:Impact_Qualification>
            </incident:Impact_Assessment>
            <incident:Leveraged_TTPs>
                <incident:Leveraged_TTP>
                    <stixCommon:TTP idref="example:ttp-6a990cfc-9927-4c78-aca6-19eb2289fb45" xsi:type='ttp:TTPType'/>
                </incident:Leveraged_TTP>
            </incident:Leveraged_TTPs>
            <incident:Attributed_Threat_Actors>
                <incident:Threat_Actor>
                    <stixCommon:Threat_Actor idref="example:threatactor-d0fefb9f-6c10-4576-bc15-997050b8bfb8" xsi:type='ta:ThreatActorType'/>
                </incident:Threat_Actor>
            </incident:Attributed_Threat_Actors>
            <incident:Security_Compromise xsi:type="stixVocabs:SecurityCompromiseVocab-1.0">Yes</incident:Security_Compromise>
            <incident:Discovery_Method>Int - reported by employee</incident:Discovery_Method>
            <incident:Information_Source>
                <stixCommon:Identity>
                    <stixCommon:Name>vcdb</stixCommon:Name>
                </stixCommon:Identity>
                <stixCommon:Tools>
                    <cyboxCommon:Tool>
                        <cyboxCommon:Name>veris2stix</cyboxCommon:Name>
                        <cyboxCommon:Vendor>MITRE</cyboxCommon:Vendor>
                        <cyboxCommon:Version>0.1</cyboxCommon:Version>
                    </cyboxCommon:Tool>
                    <cyboxCommon:Tool>
                        <cyboxCommon:Name>VERIS schema</cyboxCommon:Name>
                        <cyboxCommon:Vendor>Verizon</cyboxCommon:Vendor>
                        <cyboxCommon:Version>1.3</cyboxCommon:Version>
                    </cyboxCommon:Tool>
                </stixCommon:Tools>
                <stixCommon:References>
                    <stixCommon:Reference>http://news.softpedia.com/news/West-New-York-Mayor-Acquitted-on-Hacking-Charges-387795.shtml</stixCommon:Reference>
                    <stixCommon:Reference>http://blog.nj.com/hudsoncountynow_impact/print.html?entry=/2013/09/first_day_of_deliberation_passes_without_verdict_in_trial_of_west_new_york_mayor_felix_roque_and_his.html</stixCommon:Reference>
                </stixCommon:References>
            </incident:Information_Source>
        </stix:Incident>
    </stix:Incidents>
    <stix:Threat_Actors>
        <stix:Threat_Actor id="example:threatactor-d0fefb9f-6c10-4576-bc15-997050b8bfb8" timestamp="2014-12-22T16:32:01.894000+00:00" xsi:type='ta:ThreatActorType'>
            <ta:Identity xsi:type='stix-ciqidentity:CIQIdentity3.0InstanceType'>
                <ExtSch:Specification xmlns:ExtSch="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1">
  <xpil:Addresses xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xpil:Address>
      <xal:Country xmlns:xal="urn:oasis:names:tc:ciq:xal:3">
        <xal:NameElement>Unknown</xal:NameElement>
      </xal:Country>
    </xpil:Address>
    <xpil:Address>
      <xal:Country xmlns:xal="urn:oasis:names:tc:ciq:xal:3">
        <xal:NameElement>US</xal:NameElement>
      </xal:Country>
    </xpil:Address>
  </xpil:Addresses>
</ExtSch:Specification>
            </ta:Identity>
            <ta:Type timestamp="2014-12-22T16:32:01.894000+00:00">
                <stixCommon:Value>Competitor</stixCommon:Value>
            </ta:Type>
            <ta:Motivation timestamp="2014-12-22T16:32:01.894000+00:00">
                <stixCommon:Value>Unknown</stixCommon:Value>
            </ta:Motivation>
            <ta:Motivation timestamp="2014-12-22T16:32:01.894000+00:00">
                <stixCommon:Value>Grudge</stixCommon:Value>
            </ta:Motivation>
            <ta:Motivation timestamp="2014-12-22T16:32:01.894000+00:00">
                <stixCommon:Value>Espionage</stixCommon:Value>
            </ta:Motivation>
            <ta:Observed_TTPs>
                <ta:Observed_TTP>
                    <stixCommon:TTP idref="example:ttp-6a990cfc-9927-4c78-aca6-19eb2289fb45" xsi:type='ttp:TTPType'/>
                </ta:Observed_TTP>
            </ta:Observed_TTPs>
        </stix:Threat_Actor>
    </stix:Threat_Actors>
</stix:STIX_Package>


text:
import React from "react";
import styled from "styled-components";
import { graphql, useStaticQuery } from "gatsby";
// Type
import { EducationFeatureType } from "@type/EducationFeature";
// Components
import { ImageCard, TitleSet } from "components";
// Assets
import featuresImg from "assets/img/illusts/feature";
import { SUBTITLE, TITLE } from "assets/static/phrases";
// Utils
import { strainMdxInfo } from "lib/utils";

const EducationFeatures: React.FC = ({}) => {
  const data = useStaticQuery(FeaturesQuery);
  const { features }: { features: EducationFeatureType[] } = strainMdxInfo(data);

  return (
    <EducationFeaturesWrapper>
      <TitleSet subtitle={SUBTITLE.MASTERS_COURSE} title={TITLE.EDUCATION_FEATURES} bigSubtitle />
      <FeatureListWrapper>
        <FeatureList>
          {features.map(({ title, content, img }) => (
            <FeatureItem key={title}>
              <ImageCard description={content} title={title} img={featuresImg[img]} />
            </FeatureItem>
          ))}
        </FeatureList>
      </FeatureListWrapper>
    </EducationFeaturesWrapper>
  );
};

const EducationFeaturesWrapper = styled.div`
  display: flex;
  flex-direction: column;
  @media ${({ theme }) => theme.device.mobile} {
    padding: 0 2.4rem;
    margin-top: 12rem;
  }
  @media ${({ theme }) => theme.device.tablet} {
    padding: 0 8rem;
    margin-top: 18rem;
  }
  @media ${({ theme }) => theme.device.desktop} {
    align-items: center;
    padding: 0 18.9rem;
    margin-top: 18rem;
    min-width: 106.2rem;
  }
`;
const FeatureListWrapper = styled.div`
  display: flex;
  flex-direction: column;
  @media ${({ theme }) => theme.device.desktop} {
    width: 107rem;
  }
`;

const FeatureList = styled.ul`
  @media ${({ theme }) => theme.device.mobile} {
    display: flex;
    flex-direction: column;
  }
  @media ${({ theme }) => theme.device.tablet} {
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-gap: 0 7.9rem;
  }
  @media ${({ theme }) => theme.device.desktop} {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    align-content: flex-start;
    & > *:not(:nth-child(3n)) {
      margin-right: 7.9rem;
    }
  }
`;
const FeatureItem = styled.li`
  @media ${({ theme }) => theme.device.mobile} {
    display: flex;
    margin-top: 4.8rem;
  }
  @media ${({ theme }) => theme.device.tablet} {
    display: inline-flex;
    margin-top: 8rem;
  }
  @media ${({ theme }) => theme.device.desktop} {
    display: inline-flex;
    margin-top: 8rem;
  }
`;

const FeaturesQuery = graphql`
  query FeaturesQuery {
    mdx(frontmatter: { templateKey: { eq: "masters_features" } }) {
      frontmatter {
        features {
          title
          content
          img
        }
      }
    }
  }
`;

export default EducationFeatures;

redpajama_set_name: RedPajamaGithub


text:
cask 'rubymine' do
  version '2017.3.3,173.4548.40'
  sha256 '59293f7efc8e0a40c2e71b8378c05466a297db2a157f93db1dfc8996abc74381'

  url "https://download.jetbrains.com/ruby/RubyMine-#{version.before_comma}.dmg"
  appcast 'https://data.services.jetbrains.com/products/releases?code=RM&latest=true&type=release',
          checkpoint: '7338b2d07e7b8807fba1218b5913316f221bed6c5d3c90ca6287b8833e79ef12'
  name 'RubyMine'
  homepage 'https://www.jetbrains.com/ruby/'

  auto_updates true

  app 'RubyMine.app'

  uninstall_postflight do
    ENV['PATH'].split(File::PATH_SEPARATOR).map { |path| File.join(path, 'mine') }.each { |path| File.delete(path) if File.exist?(path) && File.readlines(path).grep(%r{# see com.intellij.idea.SocketLock for the server side of this interface}).any? }
  end

  zap trash: [
               "~/Library/Application Support/RubyMine#{version.major_minor}",
               "~/Library/Caches/RubyMine#{version.major_minor}",
               "~/Library/Logs/RubyMine#{version.major_minor}",
               "~/Library/Preferences/RubyMine#{version.major_minor}",
             ]
end


text:
/**
 * Created by Jackey Li on 15/9/22.
 */
(function (angular) {
    'use strict';

    var moduleName = 'piggyBank.account';

    /**
     * account module
     */
    angular.module(moduleName, [])
        .config(function ($stateProvider) {
            $stateProvider
                .state('desktop.account', {
                    url: '/account',
                    views: {
                        'desktop-account': {
                            templateUrl: function () {
                                return 'account/templates/account.html'
                            },
                            controller: 'ChatsCtrl'
                        }
                    }
                })
                .state('desktop.account-detail', {
                    url: '/account/:chatId',
                    views: {
                        'desktop-account': {
                            templateUrl: function () {
                                return 'account/templates/account-detail.html'
                            },
                            controller: 'ChatDetailCtrl'
                        }
                    }
                });
        });
})(angular);


text:
## Table of Contents

- [api.proto](#api.proto)
    - [App](#v1alpha.App)
    - [Event](#v1alpha.Event)
    - [EventFilter](#v1alpha.EventFilter)
    - [GetInfoRequest](#v1alpha.GetInfoRequest)
    - [GetInfoResponse](#v1alpha.GetInfoResponse)
    - [GetLogsRequest](#v1alpha.GetLogsRequest)
    - [GetLogsResponse](#v1alpha.GetLogsResponse)
    - [GlobalFlags](#v1alpha.GlobalFlags)
    - [Image](#v1alpha.Image)
    - [ImageFilter](#v1alpha.ImageFilter)
    - [ImageFormat](#v1alpha.ImageFormat)
    - [Info](#v1alpha.Info)
    - [InspectImageRequest](#v1alpha.InspectImageRequest)
    - [InspectImageResponse](#v1alpha.InspectImageResponse)
    - [InspectPodRequest](#v1alpha.InspectPodRequest)
    - [InspectPodResponse](#v1alpha.InspectPodResponse)
    - [KeyValue](#v1alpha.KeyValue)
    - [ListImagesRequest](#v1alpha.ListImagesRequest)
    - [ListImagesResponse](#v1alpha.ListImagesResponse)
    - [ListPodsRequest](#v1alpha.ListPodsRequest)
    - [ListPodsResponse](#v1alpha.ListPodsResponse)
    - [ListenEventsRequest](#v1alpha.ListenEventsRequest)
    - [ListenEventsResponse](#v1alpha.ListenEventsResponse)
    - [Network](#v1alpha.Network)
    - [Pod](#v1alpha.Pod)
    - [PodFilter](#v1alpha.PodFilter)

    - [AppState](#v1alpha.AppState)
    - [EventType](#v1alpha.EventType)
    - [ImageType](#v1alpha.ImageType)
    - [PodState](#v1alpha.PodState)

    - [PublicAPI](#v1alpha.PublicAPI)

- [Scalar Value Types](#scalar-value-types)

Top

## api.proto

### App
App describes the information of an app that's running in a pod.

| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| name | [string](#string) |  | Name of the app, required. |
| image | [Image](#v1alpha.Image) |  | Image used by the app, required. However, this may only contain the image id if it is returned by ListPods(). |
| state | [AppState](#v1alpha.AppState) |  | State of the app. optional, non-empty only if it's returned by InspectPod(). |
| exit_code | [sint32](#sint32) |  | Exit code of the app. optional, only valid if it's returned by InspectPod() and the app has already exited. |
| annotations | [KeyValue](#v1alpha.KeyValue) | repeated | Annotations for this app. |

### Event
Event describes the events that will be received via ListenEvents().

| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| type | [EventType](#v1alpha.EventType) |  | Type of the event, required. |
| id | [string](#string) |  | ID of the subject that causes the event, required. If the event is a pod or app event, the id is the pod's uuid. If the event is an image event, the id is the image's id. |
| from | [string](#string) |  | Name of the subject that causes the event, required. If the event is a pod event, the name is the pod's name. If the event is an app event, the name is the app's name. If the event is an image event, the name is the image's name. |
| time | [int64](#int64) |  | Timestamp of when the event happens, it is the seconds since epoch, required. |
| data | [KeyValue](#v1alpha.KeyValue) | repeated | Data of the event, in the form of key-value pairs, optional. |

### EventFilter
EventFilter defines the condition that the returned events needs to satisfy in ListImages().
The condition are combined by 'AND'.

| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| types | [EventType](#v1alpha.EventType) | repeated | If not empty, then only returns the events that have the listed types. |
| ids | [string](#string) | repeated | If not empty, then only returns the events whose 'id' is included in the listed ids. |
| names | [string](#string) | repeated | If not empty, then only returns the events whose 'from' is included in the listed names. |
| since_time | [int64](#int64) |  | If set, then only returns the events after this timestamp. If the server starts after since_time, then only the events happened after the start of the server will be returned. If since_time is a future timestamp, then no events will be returned until that time. |
| until_time | [int64](#int64) |  | If set, then only returns the events before this timestamp. If it is a future timestamp, then the event stream will be closed at that moment. |

### GetInfoRequest
Request for GetInfo().

### GetInfoResponse
Response for GetInfo().

| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| info | [Info](#v1alpha.Info) |  | Required. |

### GetLogsRequest
Request for GetLogs().

| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| pod_id | [string](#string) |  | ID of the pod which we will get logs from, required. |
| app_name | [string](#string) |  | Name of the app within the pod which we will get logs from, optional. If not set, then the logs of all the apps within the pod will be returned. |
| lines | [int32](#int32) |  | Number of most recent lines to return, optional. |
| follow | [bool](#bool) |  | If true, then a response stream will not be closed, and new log response will be sent via the stream, default is false. |
| since_time | [int64](#int64) |  | If set, then only the logs after the timestamp will be returned, optional. |
| until_time | [int64](#int64) |  | If set, then only the logs before the timestamp will be returned, optional. |

### GetLogsResponse
Response for GetLogs().

| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| lines | [string](#string) | repeated | List of the log lines that returned, optional as the response can contain no logs. |

### GlobalFlags
GlobalFlags describes the flags that passed to rkt api service when it is launched.

| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| dir | [string](#string) |  | Data directory. |
| system_config_dir | [string](#string) |  | System configuration directory. |
| local_config_dir | [string](#string) |  | Local configuration directory. |
| user_config_dir | [string](#string) |  | User configuration directory. |
| insecure_flags | [string](#string) |  | Insecure flags configurates what security features to disable. |
| trust_keys_from_https | [bool](#bool) |  | Whether to automatically trust gpg keys fetched from https |

### Image
Image describes the image's information.

| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| base_format | [ImageFormat](#v1alpha.ImageFormat) |  | Base format of the image, required. This indicates the original format for the image as nowadays all the image formats will be transformed to ACI. |
| id | [string](#string) |  | ID of the image, a string that can be used to uniquely identify the image, e.g. sha512 hash of the ACIs, required. |
| name | [string](#string) |  | Name of the image in the image manifest, e.g. 'coreos.com/etcd', optional. |
| version | [string](#string) |  | Version of the image, e.g. 'latest', '2.0.10', optional. |
| import_timestamp | [int64](#int64) |  | Timestamp of when the image is imported, it is the seconds since epoch, optional. |
| manifest | [bytes](#bytes) |  | JSON-encoded byte array that represents the image manifest, optional. |
| size | [int64](#int64) |  | Size is the size in bytes of this image in the store. |
| annotations | [KeyValue](#v1alpha.KeyValue) | repeated | Annotations on this image. |
| labels | [KeyValue](#v1alpha.KeyValue) | repeated | Labels of this image. |

### ImageFilter
ImageFilter defines the condition that the returned images need to satisfy in ListImages().
The conditions are combined by 'AND', and different filters are combined by 'OR'.

| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| ids | [string](#string) | repeated | If not empty, the images that have any of the ids will be returned. |
| prefixes | [string](#string) | repeated | if not empty, the images that have any of the prefixes in the name will be returned. |
| base_names | [string](#string) | repeated | If not empty, the images that have any of the base names will be returned. For example, both 'coreos.com/etcd' and 'k8s.io/etcd' will be returned if 'etcd' is included, however 'k8s.io/etcd-backup' will not be returned. |
| keywords | [string](#string) | repeated | If not empty, the images that have any of the keywords in the name will be returned. For example, both 'kubernetes-etcd', 'etcd:latest' will be returned if 'etcd' is included, |
| labels | [KeyValue](#v1alpha.KeyValue) | repeated | If not empty, the images that have all of the labels will be returned. |
| imported_after | [int64](#int64) |  | If set, the images that are imported after this timestamp will be returned. |
| imported_before | [int64](#int64) |  | If set, the images that are imported before this timestamp will be returned. |
| annotations | [KeyValue](#v1alpha.KeyValue) | repeated | If not empty, the images that have all of the annotations will be returned. |
| full_names | [string](#string) | repeated | If not empty, the images that have any of the exact full names will be returned. |

### ImageFormat
ImageFormat defines the format of the image.

| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| type | [ImageType](#v1alpha.ImageType) |  | Type of the image, required. |
| version | [string](#string) |  | Version of the image format, required. |

### Info
Info describes the information of rkt on the machine.

| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| rkt_version | [string](#string) |  | Version of rkt, required, in the form of Semantic Versioning 2.0.0 (http://semver.org/). |
| appc_version | [string](#string) |  | Version of appc, required, in the form of Semantic Versioning 2.0.0 (http://semver.org/). |
| api_version | [string](#string) |  | Latest version of the api that's supported by the service, required, in the form of Semantic Versioning 2.0.0 (http://semver.org/). |
| global_flags | [GlobalFlags](#v1alpha.GlobalFlags) |  | The global flags that passed to the rkt api service when it's launched. |

### InspectImageRequest
Request for InspectImage().

| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| id | [string](#string) |  | Required. |

### InspectImageResponse
Response for InspectImage().

| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| image | [Image](#v1alpha.Image) |  | Required. |

### InspectPodRequest
Request for InspectPod().

| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| id | [string](#string) |  | ID of the pod which we are querying status for, required. |

### InspectPodResponse
Response for InspectPod().

| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| pod | [Pod](#v1alpha.Pod) |  | Required. |

### KeyValue

| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| Key | [string](#string) |  | Key part of the key-value pair. |
| value | [string](#string) |  | Value part of the key-value pair. |

### ListImagesRequest
Request for ListImages().

| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| filters | [ImageFilter](#v1alpha.ImageFilter) | repeated | Optional. |
| detail | [bool](#bool) |  | Optional. |

### ListImagesResponse
Response for ListImages().

| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| images | [Image](#v1alpha.Image) | repeated | Required. |

### ListPodsRequest
Request for ListPods().

| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| filters | [PodFilter](#v1alpha.PodFilter) | repeated | Optional. |
| detail | [bool](#bool) |  | Optional. |

### ListPodsResponse
Response for ListPods().

| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| pods | [Pod](#v1alpha.Pod) | repeated | Required. |

### ListenEventsRequest
Request for ListenEvents().

| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| filter | [EventFilter](#v1alpha.EventFilter) |  | Optional. |

### ListenEventsResponse
Response for ListenEvents().

| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| events | [Event](#v1alpha.Event) | repeated | Aggregate multiple events to reduce round trips, optional as the response can contain no events. |

### Network
Network describes the network information of a pod.

| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| name | [string](#string) |  | Name of the network that a pod belongs to, required. |
| ipv4 | [string](#string) |  | Pod's IPv4 address within the network, optional if IPv6 address is given. |
| ipv6 | [string](#string) |  | Pod's IPv6 address within the network, optional if IPv4 address is given. |

### Pod
Pod describes a pod's information.
If a pod is in Embryo, Preparing, AbortedPrepare state,
only id and state will be returned.

If a pod is in other states, the pod manifest and
apps will be returned when 'detailed' is true in the request.

A valid pid of the stage1 process of the pod will be returned
if the pod is Running has run once.

Networks are only returned when a pod is in Running.

| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| id | [string](#string) |  | ID of the pod, in the form of a UUID. |
| pid | [sint32](#sint32) |  | PID of the stage1 process of the pod. |
| state | [PodState](#v1alpha.PodState) |  | State of the pod. |
| apps | [App](#v1alpha.App) | repeated | List of apps in the pod. |
| networks | [Network](#v1alpha.Network) | repeated | Network information of the pod. Note that a pod can be in multiple networks. |
| manifest | [bytes](#bytes) |  | JSON-encoded byte array that represents the pod manifest of the pod. |
| annotations | [KeyValue](#v1alpha.KeyValue) | repeated | Annotations on this pod. |
| cgroup | [string](#string) |  | Cgroup of the pod, empty if the pod is not running. |
| created_at | [int64](#int64) |  | Timestamp of when the pod is created, nanoseconds since epoch. Zero if the pod is not created. |
| started_at | [int64](#int64) |  | Timestamp of when the pod is started, nanoseconds since epoch. Zero if the pod is not started. |
| gc_marked_at | [int64](#int64) |  | Timestamp of when the pod is moved to exited-garbage/garbage, in nanoseconds since epoch. Zero if the pod is not moved to exited-garbage/garbage yet. |

### PodFilter
PodFilter defines the condition that the returned pods need to satisfy in ListPods().
The conditions are combined by 'AND', and different filters are combined by 'OR'.

| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| ids | [string](#string) | repeated | If not empty, the pods that have any of the ids will be returned. |
| states | [PodState](#v1alpha.PodState) | repeated | If not empty, the pods that have any of the states will be returned. |
| app_names | [string](#string) | repeated | If not empty, the pods that all of the apps will be returned. |
| image_ids | [string](#string) | repeated | If not empty, the pods that have all of the images(in the apps) will be returned |
| network_names | [string](#string) | repeated | If not empty, the pods that are in all of the networks will be returned. |
| annotations | [KeyValue](#v1alpha.KeyValue) | repeated | If not empty, the pods that have all of the annotations will be returned. |
| cgroups | [string](#string) | repeated | If not empty, the pods whose cgroup are listed will be returned. |
| pod_sub_cgroups | [string](#string) | repeated | If not empty, the pods whose these cgroup belong to will be returned. i.e. the pod's cgroup is a prefix of the specified cgroup |

### AppState
AppState defines the possible states of the app.

| Name | Number | Description |
| ---- | ------ | ----------- |
| APP_STATE_UNDEFINED | 0 |  |
| APP_STATE_RUNNING | 1 |  |
| APP_STATE_EXITED | 2 |  |

### EventType
EventType defines the type of the events that will be received via ListenEvents().

| Name | Number | Description |
| ---- | ------ | ----------- |
| EVENT_TYPE_UNDEFINED | 0 |  |
| EVENT_TYPE_POD_PREPARED | 1 | Pod events. |
| EVENT_TYPE_POD_PREPARE_ABORTED | 2 |  |
| EVENT_TYPE_POD_STARTED | 3 |  |
| EVENT_TYPE_POD_EXITED | 4 |  |
| EVENT_TYPE_POD_GARBAGE_COLLECTED | 5 |  |
| EVENT_TYPE_APP_STARTED | 6 | App events. |
| EVENT_TYPE_APP_EXITED | 7 | (XXX)yifan: Maybe also return exit code in the event object? |
| EVENT_TYPE_IMAGE_IMPORTED | 8 | Image events. |
| EVENT_TYPE_IMAGE_REMOVED | 9 |  |

### ImageType
ImageType defines the supported image type.

| Name | Number | Description |
| ---- | ------ | ----------- |
| IMAGE_TYPE_UNDEFINED | 0 |  |
| IMAGE_TYPE_APPC | 1 |  |
| IMAGE_TYPE_DOCKER | 2 |  |
| IMAGE_TYPE_OCI | 3 |  |

### PodState
PodState defines the possible states of the pod.
See https://github.com/rkt/rkt/blob/master/Documentation/devel/pod-lifecycle.md for a detailed
explanation of each state.

| Name | Number | Description |
| ---- | ------ | ----------- |
| POD_STATE_UNDEFINED | 0 |  |
| POD_STATE_EMBRYO | 1 | States before the pod is running. Pod is created, ready to entering 'preparing' state. |
| POD_STATE_PREPARING | 2 | Pod is being prepared. On success it will become 'prepared', otherwise it will become 'aborted prepared'. |
| POD_STATE_PREPARED | 3 | Pod has been successfully prepared, ready to enter 'running' state. it can also enter 'deleting' if it's garbage collected before running. |
| POD_STATE_RUNNING | 4 | State that indicates the pod is running. Pod is running, when it exits, it will become 'exited'. |
| POD_STATE_ABORTED_PREPARE | 5 | States that indicates the pod is exited, and will never run. Pod failed to prepare, it will only be garbage collected and will never run again. |
| POD_STATE_EXITED | 6 | Pod has exited, it now can be garbage collected. |
| POD_STATE_DELETING | 7 | Pod is being garbage collected, after that it will enter 'garbage' state. |
| POD_STATE_GARBAGE | 8 | Pod is marked as garbage collected, it no longer exists on the machine. |

### PublicAPI
PublicAPI defines the read-only APIs that will be supported.
These will be handled over TCP sockets.

| Method Name | Request Type | Response Type | Description |
| ----------- | ------------ | ------------- | ------------|
| GetInfo | [GetInfoRequest](#v1alpha.GetInfoRequest) | [GetInfoResponse](#v1alpha.GetInfoRequest) | GetInfo gets the rkt's information on the machine. |
| ListPods | [ListPodsRequest](#v1alpha.ListPodsRequest) | [ListPodsResponse](#v1alpha.ListPodsRequest) | ListPods lists rkt pods on the machine. |
| InspectPod | [InspectPodRequest](#v1alpha.InspectPodRequest) | [InspectPodResponse](#v1alpha.InspectPodRequest) | InspectPod gets detailed pod information of the specified pod. |
| ListImages | [ListImagesRequest](#v1alpha.ListImagesRequest) | [ListImagesResponse](#v1alpha.ListImagesRequest) | ListImages lists the images on the machine. |
| InspectImage | [InspectImageRequest](#v1alpha.InspectImageRequest) | [InspectImageResponse](#v1alpha.InspectImageRequest) | InspectImage gets the detailed image information of the specified image. |
| ListenEvents | [ListenEventsRequest](#v1alpha.ListenEventsRequest) | [ListenEventsResponse](#v1alpha.ListenEventsRequest) | ListenEvents listens for the events, it will return a response stream that will contain event objects. |
| GetLogs | [GetLogsRequest](#v1alpha.GetLogsRequest) | [GetLogsResponse](#v1alpha.GetLogsRequest) | GetLogs gets the logs for a pod, if the app is also specified, then only the logs of the app will be returned. If 'follow' in the 'GetLogsRequest' is set to 'true', then the response stream will not be closed after the first response, the future logs will be sent via the stream. |

## Scalar Value Types

| .proto Type | Notes | C++ Type | Java Type | Python Type |
| ----------- | ----- | -------- | --------- | ----------- |
|  double |  | double | double | float |
|  float |  | float | float | float |
|  int32 | Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint32 instead. | int32 | int | int |
|  int64 | Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint64 instead. | int64 | long | int/long |
|  uint32 | Uses variable-length encoding. | uint32 | int | int/long |
|  uint64 | Uses variable-length encoding. | uint64 | long | int/long |
|  sint32 | Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int32s. | int32 | int | int |
|  sint64 | Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int64s. | int64 | long | int/long |
|  fixed32 | Always four bytes. More efficient than uint32 if values are often greater than 2^28. | uint32 | int | int |
|  fixed64 | Always eight bytes. More efficient than uint64 if values are often greater than 2^56. | uint64 | long | int/long |
|  sfixed32 | Always four bytes. | int32 | int | int |
|  sfixed64 | Always eight bytes. | int64 | long | int/long |
|  bool |  | bool | boolean | boolean |
|  string | A string must always contain UTF-8 encoded or 7-bit ASCII text. | string | String | str/unicode |
|  bytes | May contain any arbitrary sequence of bytes. | string | ByteString | str |


text:
package com.github.agjacome.httpserver.server.http;

import java.io.OutputStream;
import java.util.Map;
import java.util.Optional;

import com.github.agjacome.httpserver.server.http.HttpStatusCode.StandardHttpStatusCode;
import com.github.agjacome.httpserver.util.CaseInsensitiveString;
import com.sun.net.httpserver.HttpExchange;

import static java.util.Objects.requireNonNull;

import static com.github.agjacome.httpserver.server.http.HttpHeader.parseHeaders;
import static com.github.agjacome.httpserver.util.CaseInsensitiveString.uncased;

public class HttpExchangeResponseAdapter implements HttpResponse {

    private final HttpExchange                           exchange;
    private final Map<CaseInsensitiveString, HttpHeader> headers;

    HttpExchangeResponseAdapter(final HttpExchange exchange) {
        this.exchange = requireNonNull(exchange);
        this.headers  = parseHeaders(exchange.getResponseHeaders());
    }

    @Override
    public HttpStatusCode getStatusCode() {
        return StandardHttpStatusCode.ofCode(exchange.getResponseCode()).get();
    }

    @Override
    public long getContentLength() {
        return Long.parseLong(
            headers.get(uncased("Content-Length")).getValues().get(0)
        );
    }

    @Override
    public Optional<HttpHeader> getHeader(final CaseInsensitiveString key) {
        return Optional.ofNullable(headers.get(key));
    }

    @Override
    public OutputStream getBodyOutputStream() {
        return exchange.getResponseBody();
    }

    public HttpExchange getExchange() {
        return exchange;
    }

}


text:
package org.apache.hadoop.tools.fedbalance;

import com.google.common.annotations.VisibleForTesting;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RemoteIterator;
import org.apache.hadoop.fs.permission.AclStatus;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.protocol.HdfsConstants;
import org.apache.hadoop.hdfs.protocol.OpenFileEntry;
import org.apache.hadoop.hdfs.protocol.OpenFilesIterator.OpenFilesType;
import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport;
import org.apache.hadoop.hdfs.protocol.proto.AclProtos;
import org.apache.hadoop.hdfs.protocolPB.PBHelperClient;
import org.apache.hadoop.tools.DistCp;
import org.apache.hadoop.tools.OptionsParser;
import org.apache.hadoop.tools.fedbalance.procedure.BalanceProcedure;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobID;
import org.apache.hadoop.mapred.RunningJob;
import org.apache.hadoop.mapreduce.Job;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;

import static org.apache.hadoop.tools.fedbalance.FedBalanceConfigs.CURRENT_SNAPSHOT_NAME;
import static org.apache.hadoop.tools.fedbalance.FedBalanceConfigs.LAST_SNAPSHOT_NAME;

/**
 * Copy data through distcp. Super user privilege needed.
 *
 * PRE_CHECK               :pre-check of src and dst.
 * INIT_DISTCP             :the first round of distcp.
 * DIFF_DISTCP             :copy snapshot diff round by round until there is
 *                          no diff.
 * DISABLE_WRITE           :disable write operations.
 * FINAL_DISTCP            :close all open files and do the final round distcp.
 * FINISH                  :procedure finish.
 */
public class DistCpProcedure extends BalanceProcedure {

  public static final Logger LOG =
      LoggerFactory.getLogger(DistCpProcedure.class);

  /* Stages of this procedure. */
  enum Stage {
    PRE_CHECK, INIT_DISTCP, DIFF_DISTCP, DISABLE_WRITE, FINAL_DISTCP, FINISH
  }

  private FedBalanceContext context; // the balance context.
  private Path src; // the source path including the source cluster.
  private Path dst; // the dst path including the dst cluster.
  private Configuration conf;
  private int mapNum; // the number of map tasks.
  private int bandWidth; // the bandwidth limit of each distcp task.
  private String jobId; // the id of the current distcp.
  private Stage stage; // current stage of this procedure.

  /* Force close all open files when there is no diff between src and dst */
  private boolean forceCloseOpenFiles;
  /* Disable write by setting the mount point readonly. */
  private boolean useMountReadOnly;

  private FsPermission fPerm; // the permission of the src.
  private AclStatus acl; // the acl of the src.

  private JobClient client;
  private DistributedFileSystem srcFs; // fs of the src cluster.
  private DistributedFileSystem dstFs; // fs of the dst cluster.

  /**
   * Test only. In unit test we use the LocalJobRunner to run the distcp jobs.
   * Here we save the job to look up the job status. The localJob won't be
   * serialized thus won't be recovered.
   */
  @VisibleForTesting
  private Job localJob;
  /**
   * Enable test mode. Use LocalJobRunner to run the distcp jobs.
   */
  @VisibleForTesting
  static boolean enabledForTest = false;

  public DistCpProcedure() {
  }

  /**
   * The constructor of DistCpProcedure.
   *
   * @param name the name of the procedure.
   * @param nextProcedure the name of the next procedure.
   * @param delayDuration the delay duration when this procedure is delayed.
   * @param context the federation balance context.
   */
  public DistCpProcedure(String name, String nextProcedure, long delayDuration,
      FedBalanceContext context) throws IOException {
    super(name, nextProcedure, delayDuration);
    this.context = context;
    this.src = context.getSrc();
    this.dst = context.getDst();
    this.conf = context.getConf();
    this.client = new JobClient(conf);
    this.stage = Stage.PRE_CHECK;
    this.mapNum = context.getMapNum();
    this.bandWidth = context.getBandwidthLimit();
    this.forceCloseOpenFiles = context.getForceCloseOpenFiles();
    this.useMountReadOnly = context.getUseMountReadOnly();
    srcFs = (DistributedFileSystem) context.getSrc().getFileSystem(conf);
    dstFs = (DistributedFileSystem) context.getDst().getFileSystem(conf);
  }

  @Override
  public boolean execute() throws RetryException, IOException {
    LOG.info("Stage={}", stage.name());
    switch (stage) {
    case PRE_CHECK:
      preCheck();
      return false;
    case INIT_DISTCP:
      initDistCp();
      return false;
    case DIFF_DISTCP:
      diffDistCp();
      return false;
    case DISABLE_WRITE:
      disableWrite();
      return false;
    case FINAL_DISTCP:
      finalDistCp();
      return false;
    case FINISH:
      finish();
      return true;
    default:
      throw new IOException("Unexpected stage=" + stage);
    }
  }

  /**
   * Pre check of src and dst.
   */
  void preCheck() throws IOException {
    FileStatus status = srcFs.getFileStatus(src);
    if (!status.isDirectory()) {
      throw new IOException(src + " should be a directory.");
    }
    if (dstFs.exists(dst)) {
      throw new IOException(dst + " already exists.");
    }
    if (srcFs.exists(new Path(src, HdfsConstants.DOT_SNAPSHOT_DIR))) {
      throw new IOException(src + " shouldn't enable snapshot.");
    }
    updateStage(Stage.INIT_DISTCP);
  }

  /**
   * The initial distcp. Copying src to dst.
   */
  void initDistCp() throws IOException, RetryException {
    RunningJobStatus job = getCurrentJob();
    if (job != null) {
      // the distcp has been submitted.
      if (job.isComplete()) {
        jobId = null; // unset jobId because the job is done.
        if (job.isSuccessful()) {
          updateStage(Stage.DIFF_DISTCP);
          return;
        } else {
          LOG.warn("DistCp failed. Failure={}", job.getFailureInfo());
        }
      } else {
        throw new RetryException();
      }
    } else {
      pathCheckBeforeInitDistcp();
      srcFs.createSnapshot(src, CURRENT_SNAPSHOT_NAME);
      jobId = submitDistCpJob(
          src.toString() + HdfsConstants.SEPARATOR_DOT_SNAPSHOT_DIR_SEPARATOR
              + CURRENT_SNAPSHOT_NAME, dst.toString(), false);
    }
  }

  /**
   * The distcp copying diffs between LAST_SNAPSHOT_NAME and
   * CURRENT_SNAPSHOT_NAME.
   */
  void diffDistCp() throws IOException, RetryException {
    RunningJobStatus job = getCurrentJob();
    if (job != null) {
      if (job.isComplete()) {
        jobId = null;
        if (job.isSuccessful()) {
          LOG.info("DistCp succeeded. jobId={}", job.getJobID());
        } else {
          throw new IOException("DistCp failed. jobId=" + job.getJobID()
              + " failure=" + job.getFailureInfo());
        }
      } else {
        throw new RetryException(); // wait job complete.
      }
    } else if (!verifyDiff()) {
      if (!verifyOpenFiles() || forceCloseOpenFiles) {
        updateStage(Stage.DISABLE_WRITE);
      } else {
        throw new RetryException();
      }
    } else {
      submitDiffDistCp();
    }
  }

  /**
   * Disable write either by making the mount entry readonly or cancelling the
   * execute permission of the source path.
   */
  void disableWrite() throws IOException {
    if (useMountReadOnly) {
      String mount = context.getMount();
      MountTableProcedure.disableWrite(mount, conf);
    } else {
      // Save and cancel permission.
      FileStatus status = srcFs.getFileStatus(src);
      fPerm = status.getPermission();
      acl = srcFs.getAclStatus(src);
      srcFs.setPermission(src, FsPermission.createImmutable((short) 0));
    }
    updateStage(Stage.FINAL_DISTCP);
  }

  /**
   * Enable write by restoring the x permission.
   */
  void restorePermission() throws IOException {
    // restore permission.
    dstFs.removeAcl(dst);
    if (acl != null) {
      dstFs.modifyAclEntries(dst, acl.getEntries());
    }
    if (fPerm != null) {
      dstFs.setPermission(dst, fPerm);
    }
  }

  /**
   * Close all open files then submit the distcp with -diff.
   */
  void finalDistCp() throws IOException, RetryException {
    // Close all open files then do the final distcp.
    closeAllOpenFiles(srcFs, src);
    // Final distcp.
    RunningJobStatus job = getCurrentJob();
    if (job != null) {
      // the distcp has been submitted.
      if (job.isComplete()) {
        jobId = null; // unset jobId because the job is done.
        if (job.isSuccessful()) {
          updateStage(Stage.FINISH);
          return;
        } else {
          throw new IOException(
              "Final DistCp failed. Failure: " + job.getFailureInfo());
        }
      } else {
        throw new RetryException();
      }
    } else {
      submitDiffDistCp();
    }
  }

  void finish() throws IOException {
    if (!useMountReadOnly) {
      restorePermission();
    }
    if (srcFs.exists(src)) {
      cleanupSnapshot(srcFs, src);
    }
    if (dstFs.exists(dst)) {
      cleanupSnapshot(dstFs, dst);
    }
  }

  @VisibleForTesting
  Stage getStage() {
    return stage;
  }

  @VisibleForTesting
  void updateStage(Stage value) {
    String oldStage = stage == null ? "null" : stage.name();
    String newStage = value == null ? "null" : value.name();
    LOG.info("Stage updated from {} to {}.", oldStage, newStage);
    stage = value;
  }

  /**
   * Submit distcp with -diff option to do the incremental copy.
   *
   * |   the source path      |     the dst path     |
   * | LAST_SNAPSHOT_NAME     |   LAST_SNAPSHOT_NAME |
   * | CURRENT_SNAPSHOT_NAME  |
   *
   * 1. Cleanup all the last snapshots. If there are no last snapshots then do
   *    nothing.
   * 2. Create the dst path snapshot named the last snapshot.
   * 3. Rename the source path current snapshot as the last snapshot. The dst
   *    path last snapshot and the source path last snapshot are the same now.
   * 4. Create the current snapshot of the source path.
   * 5. Submit the distcp job. The incremental part is from the source path last
   *    snapshot to the source path current snapshot.
   */
  private void submitDiffDistCp() throws IOException {
    enableSnapshot(dstFs, dst);
    deleteSnapshot(srcFs, src, LAST_SNAPSHOT_NAME);
    deleteSnapshot(dstFs, dst, LAST_SNAPSHOT_NAME);
    dstFs.createSnapshot(dst, LAST_SNAPSHOT_NAME);
    srcFs.renameSnapshot(src, CURRENT_SNAPSHOT_NAME, LAST_SNAPSHOT_NAME);
    srcFs.createSnapshot(src, CURRENT_SNAPSHOT_NAME);
    jobId = submitDistCpJob(src.toString(), dst.toString(), true);
  }

  /**
   * Close all open files. Block until all the files are closed.
   */
  private void closeAllOpenFiles(DistributedFileSystem dfs, Path path)
      throws IOException {
    String pathStr = path.toUri().getPath();
    while (true) {
      RemoteIterator<OpenFileEntry> iterator =
          dfs.listOpenFiles(EnumSet.of(OpenFilesType.ALL_OPEN_FILES), pathStr);
      if (!iterator.hasNext()) { // all files has been closed.
        break;
      }
      while (iterator.hasNext()) {
        OpenFileEntry e = iterator.next();
        try {
          srcFs.recoverLease(new Path(e.getFilePath()));
        } catch (IOException re) {
          // ignore recoverLease error.
        }
      }
    }
  }

  /**
   * Verify whether the src has changed since CURRENT_SNAPSHOT_NAME snapshot.
   *
   * @return true if the src has changed.
   */
  private boolean verifyDiff() throws IOException {
    SnapshotDiffReport diffReport =
        srcFs.getSnapshotDiffReport(src, CURRENT_SNAPSHOT_NAME, "");
    return diffReport.getDiffList().size() > 0;
  }

  /**
   * Verify whether there is any open files under src.
   *
   * @return true if there are open files.
   */
  private boolean verifyOpenFiles() throws IOException {
    RemoteIterator<OpenFileEntry> iterator = srcFs
        .listOpenFiles(EnumSet.of(OpenFilesType.ALL_OPEN_FILES),
            src.toString());
    return iterator.hasNext();
  }

  private RunningJobStatus getCurrentJob() throws IOException {
    if (jobId != null) {
      if (enabledForTest) {
        return getCurrentLocalJob();
      } else {
        RunningJob latestJob = client.getJob(JobID.forName(jobId));
        return latestJob == null ? null : new YarnRunningJobStatus(latestJob);
      }
    }
    return null;
  }

  private LocalJobStatus getCurrentLocalJob() throws IOException {
    if (localJob != null) {
      Job latestJob;
      try {
        latestJob = localJob.getCluster().getJob(JobID.forName(jobId));
      } catch (InterruptedException e) {
        throw new IOException(e);
      }
      return latestJob == null ? null : new LocalJobStatus(latestJob);
    } else {
      return null;
    }
  }

  private void pathCheckBeforeInitDistcp() throws IOException {
    if (dstFs.exists(dst)) { // clean up.
      throw new IOException("The dst path=" + dst + " already exists. The admin"
          + " should delete it before submitting the initial distcp job.");
    }
    Path snapshotPath = new Path(src,
        HdfsConstants.DOT_SNAPSHOT_DIR_SEPARATOR + CURRENT_SNAPSHOT_NAME);
    if (srcFs.exists(snapshotPath)) {
      throw new IOException("The src snapshot=" + snapshotPath +
          " already exists. The admin should delete the snapshot before"
          + " submitting the initial distcp.");
    }
    srcFs.allowSnapshot(src);
  }

  /**
   * Submit distcp job and return jobId.
   */
  private String submitDistCpJob(String srcParam, String dstParam,
      boolean useSnapshotDiff) throws IOException {
    List<String> command = new ArrayList<>();
    command.addAll(Arrays
        .asList(new String[] {"-async", "-update", "-append", "-pruxgpcab"}));
    if (useSnapshotDiff) {
      command.add("-diff");
      command.add(LAST_SNAPSHOT_NAME);
      command.add(CURRENT_SNAPSHOT_NAME);
    }
    command.add("-m");
    command.add(mapNum + "");
    command.add("-bandwidth");
    command.add(bandWidth + "");
    command.add(srcParam);
    command.add(dstParam);

    Configuration config = new Configuration(conf);
    DistCp distCp;
    try {
      distCp = new DistCp(config,
          OptionsParser.parse(command.toArray(new String[]{})));
      Job job = distCp.createAndSubmitJob();
      LOG.info("Submit distcp job={}", job);
      if (enabledForTest) {
        localJob = job;
      }
      return job.getJobID().toString();
    } catch (Exception e) {
      throw new IOException("Submit job failed.", e);
    }
  }

  @Override
  public void write(DataOutput out) throws IOException {
    super.write(out);
    context.write(out);
    if (jobId == null) {
      out.writeBoolean(false);
    } else {
      out.writeBoolean(true);
      Text.writeString(out, jobId);
    }
    out.writeInt(stage.ordinal());
    if (fPerm == null) {
      out.writeBoolean(false);
    } else {
      out.writeBoolean(true);
      out.writeShort(fPerm.toShort());
    }
    if (acl == null) {
      out.writeBoolean(false);
    } else {
      out.writeBoolean(true);
      ByteArrayOutputStream bout = new ByteArrayOutputStream();
      PBHelperClient.convert(acl).writeDelimitedTo(bout);
      byte[] data = bout.toByteArray();
      out.writeInt(data.length);
      out.write(data);
    }
  }

  @Override
  public void readFields(DataInput in) throws IOException {
    super.readFields(in);
    context = new FedBalanceContext();
    context.readFields(in);
    src = context.getSrc();
    dst = context.getDst();
    conf = context.getConf();
    if (in.readBoolean()) {
      jobId = Text.readString(in);
    }
    stage = Stage.values()[in.readInt()];
    if (in.readBoolean()) {
      fPerm = FsPermission.read(in);
    }
    if (in.readBoolean()) {
      int len = in.readInt();
      byte[] data = new byte[len];
      in.readFully(data);
      ByteArrayInputStream bin = new ByteArrayInputStream(data);
      AclProtos.GetAclStatusResponseProto proto =
          AclProtos.GetAclStatusResponseProto.parseDelimitedFrom(bin);
      acl = PBHelperClient.convert(proto);
    }
    srcFs = (DistributedFileSystem) context.getSrc().getFileSystem(conf);
    dstFs = (DistributedFileSystem) context.getDst().getFileSystem(conf);
    mapNum = context.getMapNum();
    bandWidth = context.getBandwidthLimit();
    forceCloseOpenFiles = context.getForceCloseOpenFiles();
    useMountReadOnly = context.getUseMountReadOnly();
    this.client = new JobClient(conf);
  }

  private static void enableSnapshot(DistributedFileSystem dfs, Path path)
      throws IOException {
    if (!dfs.exists(new Path(path, HdfsConstants.DOT_SNAPSHOT_DIR))) {
      dfs.allowSnapshot(path);
    }
  }

  static void deleteSnapshot(DistributedFileSystem dfs, Path path,
      String snapshotName) throws IOException {
    Path snapshot =
        new Path(path, HdfsConstants.DOT_SNAPSHOT_DIR_SEPARATOR + snapshotName);
    if (dfs.exists(snapshot)) {
      dfs.deleteSnapshot(path, snapshotName);
    }
  }

  static void cleanupSnapshot(DistributedFileSystem dfs, Path path)
      throws IOException {
    if (dfs.exists(new Path(path, HdfsConstants.DOT_SNAPSHOT_DIR))) {
      FileStatus[] status =
          dfs.listStatus(new Path(path, HdfsConstants.DOT_SNAPSHOT_DIR));
      for (FileStatus s : status) {
        deleteSnapshot(dfs, path, s.getPath().getName());
      }
      dfs.disallowSnapshot(path);
    }
  }

  interface RunningJobStatus {
    String getJobID();

    boolean isComplete() throws IOException;

    boolean isSuccessful() throws IOException;

    String getFailureInfo() throws IOException;
  }

  private static class YarnRunningJobStatus implements RunningJobStatus {

    private final RunningJob job;

    YarnRunningJobStatus(RunningJob job) {
      this.job = job;
    }

    @Override
    public String getJobID() {
      return job.getID().toString();
    }

    @Override
    public boolean isComplete() throws IOException {
      return job.isComplete();
    }

    @Override
    public boolean isSuccessful() throws IOException {
      return job.isSuccessful();
    }

    @Override
    public String getFailureInfo() throws IOException {
      return job.getFailureInfo();
    }
  }

  private static class LocalJobStatus implements RunningJobStatus {

    private final Job testJob;

    LocalJobStatus(Job testJob) {
      this.testJob = testJob;
    }

    @Override
    public String getJobID() {
      return testJob.getJobID().toString();
    }

    @Override
    public boolean isComplete() throws IOException {
      return testJob.isComplete();
    }

    @Override
    public boolean isSuccessful() throws IOException {
      return testJob.isSuccessful();
    }

    @Override
    public String getFailureInfo() throws IOException {
      try {
        return testJob.getStatus().getFailureInfo();
      } catch (InterruptedException e) {
        throw new IOException(e);
      }
    }
  }
}


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>do_bootstrap (Bud)</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <link rel="stylesheet" href="../.././rdoc-style.css" type="text/css" media="screen" />

# File lib/bud.rb, line 1005
  def do_bootstrap
    # Evaluate bootstrap for imported modules
    @this_rule_context = self
    imported = import_defs.keys
    imported.each do |mod_alias|
      wrapper = import_instance mod_alias
      wrapper.do_bootstrap
    end
    self.class.ancestors.reverse.each do |anc|
      anc.instance_methods(false).each do |m|
        if /^__bootstrap__/.match m
          self.method(m.to_sym).call
        end
      end
    end
    bootstrap

    if toplevel == self
      @tables.each_value {|t| t.bootstrap}
      @lattices.each_value {|l| l.bootstrap}
    end
    @done_bootstrap = true
  end


text:
namespace Metrics.Sampling
{
    public interface Reservoir
    {
        void Update(long value, string userValue = null);
        Snapshot GetSnapshot(bool resetReservoir = false);
        void Reset();
    }
}


text:
class ProcessingRule:

    def __init__(self, user_implementation):
        self.user_implementation = user_implementation


text:
package com.hp.ov.sdk.dto.servers.serverprofile;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;

public class OsDeploymentSettings implements Serializable{

    private static final long serialVersionUID = 8145922189736788062L;

    private List<OsCustomAttribute> osCustomAttributes = new ArrayList<>();
    private String osDeploymentPlanUri;
    private String osVolumeUri;

    /**
     * @return the osCustomAttributes
     */
    public List<OsCustomAttribute> getOsCustomAttributes() {
        return osCustomAttributes;
    }

    /**
     * @param osCustomAttributes the osCustomAttributes to set
     */
    public void setOsCustomAttributes(List<OsCustomAttribute> osCustomAttributes) {
        this.osCustomAttributes = osCustomAttributes;
    }

    /**
     * @return the osDeploymentPlanUri
     */
    public String getOsDeploymentPlanUri() {
        return osDeploymentPlanUri;
    }

    /**
     * @param osDeploymentPlanUri the osDeploymentPlanUri to set
     */
    public void setOsDeploymentPlanUri(String osDeploymentPlanUri) {
        this.osDeploymentPlanUri = osDeploymentPlanUri;
    }

    /**
     * @return the osVolumeUri
     */
    public String getOsVolumeUri() {
        return osVolumeUri;
    }

    /**
     * @param osVolumeUri the osVolumeUri to set
     */
    public void setOsVolumeUri(String osVolumeUri) {
        this.osVolumeUri = osVolumeUri;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }

    @Override
    public int hashCode() {
        return HashCodeBuilder.reflectionHashCode(this);
    }

    @Override
    public boolean equals(Object obj) {
        return EqualsBuilder.reflectionEquals(this, obj);
    }

}


text:
from questgen.quests.base_quest import QuestBetween2, ROLES, RESULTS
from questgen import facts
from questgen import logic
from questgen import requirements
from questgen import actions
from questgen import relations

class Help(QuestBetween2):
    TYPE = 'help'
    TAGS = ('can_start', 'has_subquests', 'can_continue')

    @classmethod
    def find_receiver(cls, selector, initiator):
        return selector.new_person(restrict_social_connections=((initiator.uid, relations.SOCIAL_RELATIONS.CONCURRENT),),
                                   social_connections=((initiator.uid, relations.SOCIAL_RELATIONS.PARTNER),))

    @classmethod
    def construct(cls, nesting, selector, initiator, initiator_position, receiver, receiver_position):

        hero = selector.heroes()[0]

        ns = selector._kb.get_next_ns()

        start = facts.Start(uid=ns+'start',
                            type=cls.TYPE,
                            nesting=nesting,
                            description='Начало: помочь знакомому',
                            require=[requirements.LocatedIn(object=hero.uid, place=initiator_position.uid),
                                     requirements.LocatedIn(object=receiver.uid, place=receiver_position.uid)],
                            actions=[actions.Message(type='intro')])

        participants = [facts.QuestParticipant(start=start.uid, participant=initiator.uid, role=ROLES.INITIATOR),
                        facts.QuestParticipant(start=start.uid, participant=receiver.uid, role=ROLES.RECEIVER) ]

        finish_successed = facts.Finish(uid=ns+'finish_successed',
                                        start=start.uid,
                                        results={ initiator.uid: RESULTS.SUCCESSED,
                                                  receiver.uid: RESULTS.SUCCESSED},
                                        nesting=nesting,
                                        description='помощь оказана',
                                        require=[requirements.LocatedIn(object=hero.uid, place=initiator_position.uid)],
                                        actions=[actions.GiveReward(object=hero.uid, type='finish_successed')])

        finish_failed = facts.Finish(uid=ns+'finish_failed',
                                     start=start.uid,
                                     results={ initiator.uid: RESULTS.FAILED,
                                               receiver.uid: RESULTS.FAILED},
                                     nesting=nesting,
                                     description='не удалось помочь',
                                     actions=[actions.GiveReward(object=hero.uid, type='finish_failed')])

        help_quest = selector.create_quest_from_person(nesting=nesting+1, initiator=receiver, tags=('can_continue',))
        help_extra = []

        for help_fact in logic.filter_subquest(help_quest, nesting):
            if isinstance(help_fact, facts.Start):
                help_extra.append(facts.Jump(state_from=start.uid, state_to=help_fact.uid, start_actions=[actions.Message(type='before_help')]))
            elif isinstance(help_fact, facts.Finish):
                if help_fact.results[receiver.uid] == RESULTS.SUCCESSED:
                    help_extra.append(facts.Jump(state_from=help_fact.uid, state_to=finish_successed.uid, start_actions=[actions.Message(type='after_successed_help')]))
                else:
                    help_extra.append(facts.Jump(state_from=help_fact.uid, state_to=finish_failed.uid))

        subquest = facts.SubQuest(uid=ns+'help_subquest', members=logic.get_subquest_members(help_quest))

        line = [ start,
                 finish_successed,
                 finish_failed,
                 subquest ]

        line.extend(participants)
        line.extend(help_quest)
        line.extend(help_extra)

        return line


text:
IdleMonitor = Proto.clone().newSlots({
	protoType: "IdleMonitor",
	dt: 2,
	vertex: null,
	callback: null
}).setSlots({
	start: function()
	{
		var self = this;
		this._vertex.timer().setCallback(function()
		{
			if(new Date().getTime() - self._vertex.lastReqTime() > self._dt * 1000)
			{
				if(self._callback)
				{
					self._callback();
				}
			}
		}).start();
		return this;
	},

	stop: function()
	{
		this._vertex.timer().stop();
		return this;
	}
});


text:
tinyMCE.addI18n('no.simple',{
bold_desc:"Fet (Ctrl+B)",
italic_desc:"Kursiv (Ctrl+I)",
underline_desc:"Understreke (Ctrl+U)",
striketrough_desc:"Gjennomstreke",
bullist_desc:"Punktliste",
numlist_desc:"Nummerliste",
undo_desc:"Angre",
redo_desc:"Gj\u00F8r om",
cleanup_desc:"Rense grisete kode"
});


text:
class ContactMailer < ActionMailer::Base

  def contact_email(name, email, phone, subject, message)
    @name = name
    @email = email
    @phone = phone
    @subject = subject
    @message = message
    mail(to: Spree::ContactUsSetting.new[:email], from: @email, subject: @subject, reply_to:@email)
  end

end


text:
title: Reports v3
layout: reference

redirect_from:
  - /api-reference/expense/expense-report/reports.html
---

* [Retrieve reports owned by the user based on search criteria](#get)
* [Retrieve a report by ID](#getID)
* [Create a new report](#post)
* [Update a report](#put)
* [Schema](#schema)

## Prior Versions

* [Expense Reports v2](/api-reference/expense/expense-report/v2.reports.html)
* [Expense Report Header 1.1](/api-reference/expense/expense-report/v1dot1.reports.html)

## Retrieve reports owned by the user based on search criteria

```
GET  /api/v3.0/expense/reports
```
### Parameters

Name|Type|Format|Description
---|---|---|---
`offset`|`string`|`query`|Starting page offset
`limit`|`Int32`|`query`|Number of records to return (default 25)
`user`|`string`|`query`|Optional. The login ID of the report owner(s) to use when searching for reports. If the value is set to LoginID, reports for the report owner with this login ID value are returned. If the value is set to ALL, reports for all report owners are returned. If this parameter is not specified, reports for the OAuth Consumer are returned. The access token owner (OAuth Consumer) must have the Web Services Admin role to use this parameter.
`approvalStatusCode`|`string`|`query`|The status code for the Approval Status. The values can include Concur Expense standard codes or custom codes. The Concur Expense standard code values are: A_AAFH - Report submission triggered an anomaly and fraud check; A_ACCO - Report is pending reviews; A_APPR - Report has been approved; A_EXTV - Report is pending external validation; A_FILE - Report has been submitted; A_NOTF - Report has not been submitted; A_PBDG - Report approval is pending Budget approval; A_PECO - Report approval is pending Cost object approval; A_PEND - Report is pending manager approval; A_PVAL - Report is pending prepayment validation; A_RESU - Report needs to be resubmitted; A_RHLD - Report submission is pending receipt images; A_TEXP - Report expired in approval queue. For custom codes, contact Concur Developer Support.
`paymentStatusCode`|`string`|`query`|The payment status code for the report. The values can include Concur Expense standard codes or custom codes. The Concur Expense standard code values are: P_HOLD - Report payment is on hold; P_NOTP - Report has not been paid; P_PAID - Report has been paid; P_PAYC - Payment is confirmed. Some or all of the report expenses have been paid; P_PROC - Report is in process to be paid. For custom codes, contact Concur Developer Support.
`currencyCode`|`string`|`query`|The 3-letter ISO 4217 currency code for the report currency. Example: USD.
`paymentType`|`string`|`query`|The unique identifier for the payment type that is the payment type for at least one expense entry in the report. Use PaymentTypeID from Response of GET Expense Group Configurations V3 to obtain valid payment types.
`reimbursementMethod`|`string`|`query`|The method the report owner will be reimbursed. VALUES: ADPPAYR - ADP Payroll; APCHECK - AP (Company Check); CNQRPAY - Expense Pay; PMTSERV - Other Payment Service. NOTE: PAY_PAL is NOT supported.
`approverLoginID`|`string`|`query`|The login ID for the report approver that is the current approver assigned to the report.
`expenseTypeCode`|`string`|`query`|The expense type code that is the expense type for at least one expense entry in the report. Use ExpenseTypeCode from Response of GET Expense Group Configurations V3.
`attendeeTypeCode`|`string`|`query`|The report contains expense entries that have attendees of the specified type.
`countryCode`|`string`|`query`|The report country. Maximum 2 characters. Format: The ISO 3166-1 alpha-2 country code. Example: United States is US.
`batchID`|`string`|`query`|The unique identifier for a payment batch where there is at least one report payee within the report. Use the BatchID from Response of GET Payment Batch List.
`vendorName`|`string`|`query`|The Vendor Description that is the vendor for at least one expense entry in the report.
`hasVAT`|`Boolean`|`query`|Determines if the report has at least one expense entry with VAT details. Format: true or false.
`hasImages`|`Boolean`|`query`|Determines if the report has at least one expense entry with an entry image or if there is a report image for this report. Format: true or false.
`hasAttendees`|`Boolean`|`query`|Determines if the report has at least one expense entry with an attendee. Format: true or false.
`hasBillableExpenses`|`Boolean`|`query`|The IsBillable flag for at least one expense entry in the report. Format: true or false.
`isTestUser`|`Boolean`|`query`|The report owner is a test user using the report for testing purposes in a non-production environment. Format: true or false.
`expenseGroupConfigID`|`string`|`query`|The unique identifier for the expense group configuration associated to the report's expense group. Use the ID from the Response of the Expense Group Configurations V3.
`entryTransactionDateBefore`|`DateTime`|`query`|The entry transaction date for at least one expense entry in the report is before this date. Format: YYYY-MM-DD
`entryTransactionDateAfter`|`DateTime`|`query`|The entry transaction date for at least one expense entry in the report is after this date. Format: YYYY-MM-DD
`createDateBefore`|`DateTime`|`query`|The report create date is before this date. Format: YYYY-MM-DD
`createDateAfter`|`DateTime`|`query`|The report create date is after this date. Format: YYYY-MM-DD
`userDefinedDateBefore`|`DateTime`|`query`|The report user defined date is before this date. Format: YYYY-MM-DD
`userDefinedDateAfter`|`DateTime`|`query`|The report user defined date is after this date. Format: YYYY-MM-DD
`submitDateBefore`|`DateTime`|`query`|The report submit date is before this date. Format: YYYY-MM-DD
`submitDateAfter`|`DateTime`|`query`|The report submit date is after this date. Format: YYYY-MM-DD
`processingPaymentDateBefore`|`DateTime`|`query`|The report processing payment date is before this date. Format: YYYY-MM-DD
`processingPaymentDateAfter`|`DateTime`|`query`|The report processing payment date is after this date. Format: YYYY-MM-DD
`paidDateBefore`|`DateTime`|`query`|The report paid date is before this date. Format: YYYY-MM-DD
`paidDateAfter`|`DateTime`|`query`|The report paid date is after this date. Format: YYYY-MM-DD
`modifiedDateBefore`|`DateTime`|`query`|The report modified date is before this date. Format: YYYY-MM-DD
`modifiedDateAfter`|`DateTime`|`query`|The report modified date is after this date. Format: YYYY-MM-DD

### Request URL

```
https://www.concursolutions.com/api/v3.0/expense/reports?limit=15&user=ALL
```

### JSON example of a successful response

```json
{
  "Items": [
    {
      "Name": "Canadian Tax",
      "Total": 1900,
      "CurrencyCode": "CAD",
      "Country": "CA",
      "CountrySubdivision": "CA-BC",
      "CreateDate": "2013-09-02T19:05:57.687",
      "SubmitDate": "2013-09-02T19:18:35.537",
      "ProcessingPaymentDate": "2013-09-02T19:40:48.533",
      "PaidDate": "2013-09-02T19:46:01.57",
      "ReceiptsReceived": false,
      "UserDefinedDate": "2013-09-02T00:00:00",
      "LastComment": "",
      "OwnerLoginID": "CAtraveler@concurconnect2.com",
      "OwnerName": "Canadian Traveler",
      "ApproverLoginID": null,
      "ApproverName": null,
      "ApprovalStatusName": "Approved",
      "ApprovalStatusCode": "A_APPR",
      "PaymentStatusName": "Sent for Payment",
      "PaymentStatusCode": "P_PAID",
      "LastModifiedDate": "2013-09-02T19:46:01.98",
      "PersonalAmount": 0,
      "AmountDueEmployee": 1500,
      "AmountDueCompanyCard": 0,
      "TotalClaimedAmount": 1900,
      "TotalApprovedAmount": 1900,
      "LedgerName": "DEFAULT",
      "PolicyID": "gWmINGEAkQoamAzOARD9NEBtuv0ppnbJ4lQ",
      "EverSentBack": false,
      "HasException": false,
      "WorkflowActionUrl": "http://www.concursolutions.com/api/v3.0/expense/reports/report/gWpkOyRxJoH6lOiUHqNhW93UWxhOZZw/WorkFlowAction?limit=15&user=ALL",
      "OrgUnit1": null,
      "OrgUnit2": null,
      "OrgUnit3": null,
      "OrgUnit4": null,
      "OrgUnit5": null,
      "OrgUnit6": null,
      "Custom1": null,
      "Custom2": null,
      "Custom3": null,
      "Custom4": null,
      "Custom5": null,
      "Custom6": null,
      "Custom7": null,
      "Custom8": null,
      "Custom9": null,
      "Custom10": null,
      "Custom11": null,
      "Custom12": null,
      "Custom13": null,
      "Custom14": null,
      "Custom15": null,
      "Custom16": null,
      "Custom17": null,
      "Custom18": null,
      "Custom19": null,
      "Custom20": null,
      "ID": "F4F027007E814C1CA70E",
      "URI": "https://www.concursolutions.com/api/v3.0/expense/reports/F4F027007E814C1CA70E"
    }
  ]
}
```

## Retrieve a report by ID

    GET  /api/v3.0/expense/reports/{id}

### Parameters

Name|Type|Format|Description
-----|------|--------|------------
`id`|`string`|`path`|**Required** Report ID
`user`|`string`|`query`|Optional. The login ID of the report owner(s) to use when searching for reports. If the value is set to LoginID, reports for the report owner with this login ID value are returned. If the value is set to ALL, reports for all report owners are returned. If this parameter is not specified, reports for the OAuth Consumer are returned. The access token owner (OAuth Consumer) must have the Web Services Admin role to use this parameter.

### Request URL

```
https://www.concursolutions.com/api/v3.0/expense/reports/39BD9F7C5C3F4986A6A5
```

### JSON example of a successful response

```json
{
  "Name": "Test 02",
  "Total": 307.01,
  "CurrencyCode": "USD",
  "Country": "US",
  "CountrySubdivision": null,
  "CreateDate": "2016-04-04T23:33:08.21",
  "SubmitDate": null,
  "ProcessingPaymentDate": null,
  "PaidDate": null,
  "ReceiptsReceived": false,
  "UserDefinedDate": "2016-04-04T00:00:00",
  "LastComment": "",
  "OwnerLoginID": "jimadmin@concurconnect2.com",
  "OwnerName": "Jim Admin",
  "ApproverLoginID": null,
  "ApproverName": null,
  "ApprovalStatusName": "Not Submitted",
  "ApprovalStatusCode": "A_NOTF",
  "PaymentStatusName": "Not Paid",
  "PaymentStatusCode": "P_NOTP",
  "LastModifiedDate": "2016-04-23T02:53:23.7",
  "PersonalAmount": 0,
  "AmountDueEmployee": 290,
  "AmountDueCompanyCard": 0,
  "TotalClaimedAmount": 307.01,
  "TotalApprovedAmount": 307.01,
  "LedgerName": "DEFAULT",
  "PolicyID": "gWmINGEAkQoapyOLKfSdm0A9qK0ZVUvwolA",
  "EverSentBack": false,
  "HasException": true,
  "WorkflowActionUrl": "",
  "OrgUnit1": null,
  "OrgUnit2": null,
  "OrgUnit3": null,
  "OrgUnit4": null,
  "OrgUnit5": null,
  "OrgUnit6": null,
  "Custom1": null,
  "Custom2": null,
  "Custom3": null,
  "Custom4": null,
  "Custom5": null,
  "Custom6": null,
  "Custom7": null,
  "Custom8": null,
  "Custom9": null,
  "Custom10": null,
  "Custom11": null,
  "Custom12": null,
  "Custom13": null,
  "Custom14": null,
  "Custom15": null,
  "Custom16": null,
  "Custom17": null,
  "Custom18": null,
  "Custom19": null,
  "Custom20": null,
  "ID": "39BD9F7C5C3F4986A6A5",
  "URI": "http://www.concursolutions.com/api/v3.0/expense/reports/39BD9F7C5C3F4986A6A5"
}
```

## Create a new report

    POST  /api/v3.0/expense/reports

### Parameters

Name|Type|Format|Description
-----|------|--------|------------
`content`|-|`body`|**Required** Report object to create

## Update a report

### Request URL

```
https://www.concursolutions.com/api/v3.0/expense/reports
```

### JSON example of a successful response

```json
{
  "ID": "DD683A53018A4349B7CD",
  "URI": "https://www.concursolutions.com/api/v3.0/expense/reports/DD683A53018A4349B7CD"
}
```

    PUT  /api/v3.0/expense/reports/{id}

### Parameters

Name|Type|Format|Description
-----|------|--------|------------
`id`|`string`|`path`|**Required** The unique identifier for the report.
`content`||`body`|**Required** The report object to update

## Schema

### Reports

Name|Type|Format|Description
-----|------|--------|------------
`Items`|``array``|[Report](#report)|The result collection.
`NextPage`|``string``|-|The URI of the next page of results, if any.

### Report

Name|Type|Format|Description
-----|------|--------|------------
`AmountDueCompanyCard`|`Decimal`|-|The total amount due to the company card for the report. Maximum 23 characters.
`AmountDueEmployee`|`Decimal`|-|The total amount due to the employee for the report. Maximum 23 characters.
`ApprovalStatusCode`|`string`|-|The approval status code for the report.
`ApprovalStatusName`|`string`|-|The report's approval status, in the OAuth consumer's language.
`ApproverLoginID`|`string`|-|The Login ID of the report owner's expense approver.
`ApproverName`|`string`|-|The name of the report owner's expense approver.
`Country`|`string`|-|The report country. Maximum 2 characters. Format: The ISO 3166-1 alpha-2 country code. Example: United States is US.
`CountrySubdivision`|`string`|-|The report country subdivision. Format: ISO 3166-2:2007 country subdivision.
`CreateDate`|`DateTime`|-|The date the report was created.
`CurrencyCode`|`string`|-|The 3-letter ISO 4217 currency code for the expense report currency. Examples: USD - US dollars; BRL - Brazilian real; CAD - Canadian dollar; CHF - Swiss franc; EUR - Euro; GBO - Pound sterling; HKD - Hong Kong dollar; INR - Indian rupee; MXN - Mexican peso; NOK - Norwegian krone; SEK - Swedish krona.
`Custom1 thorugh Custom20`|`CustomField`|-|The details from the Custom fields. These may not have data, depending on configuration.
`EverSentBack`|`Boolean`|-|Whether the report has ever been sent back to the employee. Format: Y/N
`HasException`|`Boolean`|-|Whether the report has exceptions. Format: Y/N
`ID`|`string`|-|The unique identifier of the resource.
`LastComment`|`string`|-|The text of the most recent comment on the report.
`LastModifiedDate`|`DateTime`|-|The date the report header was last modified.
`LedgerName`|`string`|-|The name of the expense report ledger. Maximum 20 characters.
`Name`|`string`|-| **Required** The name of the report.
`OrgUnit1 through OrgUnit6`|`CustomField`|-|The details from the Org Unit fields. These may not have data, depending on configuration.
`OwnerLoginID`|`string`|-|The Login ID of the user this report belongs to.
`OwnerName`|`string`|-|The name of the expense report owner.
`PaidDate`|`DateTime`|-|The date when all journal entries in the report was integrated with or extracted to the financial system.
`PaymentStatusCode`|`string`|-|The code for the payment status of the report.
`PaymentStatusName`|`string`|-|The report's payment status, in the OAuth consumer's language.
`PersonalAmount`|`Decimal`|-|The total amount of expenses marked as personal. Maximum 23 characters.
`PolicyID`|`string`|-|The unique identifier of the policy that applies to this report. Maximum 64 characters. User's default expense policy is being used when creating a new expense report
`ProcessingPaymentDate`|`DateTime`|-|The date that the report completed all approvals and was ready to be extracted for payment.
`ReceiptsReceived`|`Boolean`|-|If Y, then this entry has been marked as confirmed by the Expense Processor. Format: Y/N
`SubmitDate`|`DateTime`|-|The date the report was submitted.
`Total`|`Decimal`|-|The total amount of the report.
`TotalApprovedAmount`|`Decimal`|-|The total amount of approved expenses in the report. Maximum 23 characters.
`TotalClaimedAmount`|`Decimal`|-|The total amount of all non-personal expenses in the report. Maximum 23 characters.
`URI`|`string`|-|The URI to the resource.
`UserDefinedDate`|`DateTime`|-|The date of the report assigned by the user.
`WorkflowActionUrl`|`string`|-|The URL to post a workflow action to the report using the Post Report Workflow Action function.

### Custom Field

Name|Type|Format|Description
-----|------|--------|------------
`Code`|`string`|-|For list fields, this is the list item code.
`ListItemID`|`string`|-|For list fields, this is the list item ID.
`Type`|`string`|-|The custom field type. Possible values: Amount, Boolean, ConnectedList, Date, Integer, List, Number, Text
`Value`|`string`|-|The value in the Org Unit or Custom field. For list fields, this is the name of the list item. Maximum length: 48 characters

### Request URL

```
https://www.concursolutions.com/api/v3.0/expense/reports/39BD9F7C5C3F4986A6A5
```

### JSON example of a successful response

```
no content
```


text:
package com.iappsam.servlet.app;

import java.io.File;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.iappsam.forms.APP;
import com.iappsam.forms.Form;
import com.iappsam.logging.Logger;
import com.iappsam.managers.APPManager;
import com.iappsam.managers.DivisionOfficeManager;
import com.iappsam.managers.PersonManager;
import com.iappsam.managers.exceptions.TransactionException;
import com.iappsam.reporting.APPReport;
import com.iappsam.reporting.ReportException;
import com.iappsam.servlet.form.AbstractFormUtility;
import com.iappsam.servlet.form.FormUtility;
import com.iappsam.util.ApplicationContext;

public class APPUtility extends AbstractFormUtility implements FormUtility {

	private HttpServletRequest request;
	private PersonManager pm;
	private DivisionOfficeManager dom;
	private APPManager appm;

	public APPUtility() {
		super("app", ApplicationContext.INSTANCE, new AppParser());
		dom = appContext.getDivisionOfficeManager();
		pm = appContext.getPersonManager();
		appm = appContext.getAPPManager();
	}

	@Override
	public void beforeNewForm(HttpServletRequest request) throws TransactionException {
		this.request = request;
		Object ob = request.getSession().getAttribute("form");
		Object ob2 = request.getAttribute("form");

		if (!(ob instanceof APP || ob2 instanceof APP)) {
			String retain = (String) request.getParameter("retain");
			if (retain == null) {
				request.getSession().removeAttribute("form");
				request.removeAttribute("form");
			}
		}
		request.setAttribute("offices", dom.getAllDivisionOffice());
		request.setAttribute("employees", pm.getAllNonSupplierEmployee());
	}

	@Override
	public void add(Form form) throws TransactionException {
		appm.addAPP((APP) form);
		Logger.log(request, "Annual Procurement Plan for year " + ((APP) form).getYear() + " was added");
	}

	@Override
	public List<? extends Form> getAllForms() throws TransactionException {
		return appm.getAllAPP();
	}

	@Override
	public Form getForm(int id) throws TransactionException {
		return appm.getAPP(id);
	}

	@Override
	public File getPdf(Form form) throws ReportException {
		return new APPReport((APP) form).toPDF();
	}

	@Override
	public File getXls(Form form) throws ReportException {
		return new APPReport((APP) form).toXLS();
	}
}


text:
<?php

require_once "lib/autoload.php";

use Task\AbstractTask;
use Task\ActionTaskInterface;

/**
 * Class DevTask
 *
 * @author Javi H. Gil <https://github.com/javihgil>
 */
class DevTask extends AbstractTask implements ActionTaskInterface
{

    /**
     * Inits task
     */
    public function init()
    {
        $this->jsonFile = 'composer.json';
    }

    /**
     * @var string
     */
    protected $action;

    /**
     * @param string $action
     */
    public function setAction($action)
    {
        $this->action = $action;
    }

    /**
     * @return string
     */
    public function getAction()
    {
        return $this->action;
    }

    /**
     * @var string
     */
    protected $jsonFile;

    /**
     * @param string $jsonFile
     */
    public function setJsonFile($jsonFile)
    {
        $this->jsonFile = $jsonFile;
    }

    /**
     * @return string
     */
    public function getJsonFile()
    {
        return $this->jsonFile;
    }

    /**
     * TODO Rename vendorDir to "target"
     * @var string
     */
    protected $vendorDir;

    /**
     * TODO Rename localDir to "origin"
     * @var string
     */
    protected $localDir;

    /**
     * @param string $localDir
     */
    public function setLocalDir($localDir)
    {
        $this->localDir = $localDir;
    }

    /**
     * @return string
     */
    public function getLocalDir()
    {
        return $this->localDir;
    }

    /**
     * @param string $vendorDir
     */
    public function setVendorDir($vendorDir)
    {
        $this->vendorDir = $vendorDir;
    }

    /**
     * @return string
     */
    public function getVendorDir()
    {
        return $this->vendorDir;
    }

    /**
     * @throws BuildException
     */
    public function main()
    {
        switch ($this->action) {
            case 'create-symlink':
                $this->createSymlink();
                break;

            case 'remove-symlink':
                $this->removeSymlink();
                break;

            default:
                throw new \BuildException("$this->action action is not valid");
        }
    }

    /**
     * @return bool
     * @throws BuildException
     */
    protected function createSymlink()
    {
        $this->requireParam('vendorDir');
        $this->requireParam('localDir');

        if (file_exists($this->vendorDir) && is_link($this->vendorDir)) {
            $this->log("$this->vendorDir link already exists", \Project::MSG_INFO);
            return false;
        }

        if (strpos($this->localDir, '/') === 0) /* absolute path */ {
            if (!is_dir("$this->localDir")) {
                $this->log("$this->localDir directory does not exist", \Project::MSG_WARN);
                return false;
            }
        }

        if (file_exists($this->vendorDir) && is_dir($this->vendorDir)) {
            // remove dir
            $this->log("Remove dir $this->vendorDir", \Project::MSG_INFO);
            self::rmRf($this->vendorDir);
        }

        // create symlink
        $this->log("Create link $this->vendorDir to $this->localDir", \Project::MSG_INFO);
        symlink($this->localDir, $this->vendorDir);

        return true;
    }

    /**
     * @return bool
     * @throws BuildException
     */
    protected function removeSymlink()
    {
        $this->requireParam('vendorDir');

        if (!file_exists($this->vendorDir)) {
            $this->log("$this->vendorDir does not exist", \Project::MSG_INFO);
            return false;
        }

        if (!is_link($this->vendorDir)) {
            $this->log("$this->vendorDir is not a symlink", \Project::MSG_INFO);
            return false;
        }

        $this->log("Remove symlink $this->vendorDir", \Project::MSG_INFO);
        unlink($this->vendorDir);

        return true;
    }

    /**
     * @param string $path
     */
    protected static function rmRf($path)
    {
        if (!file_exists($path)) {
            return;
        }

        $paths = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($paths as $subpath) {
            $subpath->isFile() ? unlink($subpath->getPathname()) : rmdir($subpath->getPathname());
        }
        rmdir($path);
    }
}