text:
#include "webrtc/modules/rtp_rtcp/source/rtp_sender_video.h"

#include <assert.h>
#include <stdlib.h>
#include <string.h>

#include "webrtc/modules/rtp_rtcp/interface/rtp_rtcp_defines.h"
#include "webrtc/modules/rtp_rtcp/source/producer_fec.h"
#include "webrtc/modules/rtp_rtcp/source/rtp_format_video_generic.h"
#include "webrtc/modules/rtp_rtcp/source/rtp_format_vp8.h"
#include "webrtc/modules/rtp_rtcp/source/rtp_utility.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/logging.h"
#include "webrtc/system_wrappers/interface/trace_event.h"

namespace webrtc {
enum { REDForFECHeaderLength = 1 };

struct RtpPacket {
  uint16_t rtpHeaderLength;
  ForwardErrorCorrection::Packet* pkt;
};

RTPSenderVideo::RTPSenderVideo(Clock* clock,
                               RTPSenderInterface* rtpSender)
    : _rtpSender(*rtpSender),
      _sendVideoCritsect(CriticalSectionWrapper::CreateCriticalSection()),
      _videoType(kRtpVideoGeneric),
      _videoCodecInformation(NULL),
      _maxBitrate(0),
      _retransmissionSettings(kRetransmitBaseLayer),

      // Generic FEC
      _fec(),
      _fecEnabled(false),
      _payloadTypeRED(-1),
      _payloadTypeFEC(-1),
      _numberFirstPartition(0),
      delta_fec_params_(),
      key_fec_params_(),
      producer_fec_(&_fec),
      _fecOverheadRate(clock, NULL),
      _videoBitrate(clock, NULL) {
  memset(&delta_fec_params_, 0, sizeof(delta_fec_params_));
  memset(&key_fec_params_, 0, sizeof(key_fec_params_));
  delta_fec_params_.max_fec_frames = key_fec_params_.max_fec_frames = 1;
  delta_fec_params_.fec_mask_type = key_fec_params_.fec_mask_type =
        kFecMaskRandom;
}

RTPSenderVideo::~RTPSenderVideo()
{
    if(_videoCodecInformation)
    {
        delete _videoCodecInformation;
    }
    delete _sendVideoCritsect;
}

void
RTPSenderVideo::SetVideoCodecType(RtpVideoCodecTypes videoType)
{
    CriticalSectionScoped cs(_sendVideoCritsect);
    _videoType = videoType;
}

RtpVideoCodecTypes
RTPSenderVideo::VideoCodecType() const
{
    return _videoType;
}

int32_t RTPSenderVideo::RegisterVideoPayload(
    const char payloadName[RTP_PAYLOAD_NAME_SIZE],
    const int8_t payloadType,
    const uint32_t maxBitRate,
    RtpUtility::Payload*& payload) {
  CriticalSectionScoped cs(_sendVideoCritsect);

  RtpVideoCodecTypes videoType = kRtpVideoGeneric;
  if (RtpUtility::StringCompare(payloadName, "VP8", 3)) {
    videoType = kRtpVideoVp8;
  } else if (RtpUtility::StringCompare(payloadName, "H264", 4)) {
    videoType = kRtpVideoH264;
  } else if (RtpUtility::StringCompare(payloadName, "I420", 4)) {
    videoType = kRtpVideoGeneric;
  } else {
    videoType = kRtpVideoGeneric;
  }
  payload = new RtpUtility::Payload;
  payload->name[RTP_PAYLOAD_NAME_SIZE - 1] = 0;
  strncpy(payload->name, payloadName, RTP_PAYLOAD_NAME_SIZE - 1);
  payload->typeSpecific.Video.videoCodecType = videoType;
  payload->typeSpecific.Video.maxRate = maxBitRate;
  payload->audio = false;
  return 0;
}

int32_t
RTPSenderVideo::SendVideoPacket(uint8_t* data_buffer,
                                const uint16_t payload_length,
                                const uint16_t rtp_header_length,
                                const uint32_t capture_timestamp,
                                int64_t capture_time_ms,
                                StorageType storage,
                                bool protect) {
  if(_fecEnabled) {
    int ret = 0;
    int fec_overhead_sent = 0;
    int video_sent = 0;

    RedPacket* red_packet = producer_fec_.BuildRedPacket(data_buffer,
                                                         payload_length,
                                                         rtp_header_length,
                                                         _payloadTypeRED);
    TRACE_EVENT_INSTANT2("webrtc_rtp", "Video::PacketRed",
                         "timestamp", capture_timestamp,
                         "seqnum", _rtpSender.SequenceNumber());
    // Sending the media packet with RED header.
    int packet_success = _rtpSender.SendToNetwork(
        red_packet->data(),
        red_packet->length() - rtp_header_length,
        rtp_header_length,
        capture_time_ms,
        storage,
        PacedSender::kNormalPriority);

    ret |= packet_success;

    if (packet_success == 0) {
      video_sent += red_packet->length();
    }
    delete red_packet;
    red_packet = NULL;

    if (protect) {
      ret = producer_fec_.AddRtpPacketAndGenerateFec(data_buffer,
                                                     payload_length,
                                                     rtp_header_length);
      if (ret != 0)
        return ret;
    }

    while (producer_fec_.FecAvailable()) {
      red_packet = producer_fec_.GetFecPacket(
          _payloadTypeRED,
          _payloadTypeFEC,
          _rtpSender.IncrementSequenceNumber(),
          rtp_header_length);
      StorageType storage = kDontRetransmit;
      if (_retransmissionSettings & kRetransmitFECPackets) {
        storage = kAllowRetransmission;
      }
      TRACE_EVENT_INSTANT2("webrtc_rtp", "Video::PacketFec",
                           "timestamp", capture_timestamp,
                           "seqnum", _rtpSender.SequenceNumber());
      // Sending FEC packet with RED header.
      int packet_success = _rtpSender.SendToNetwork(
          red_packet->data(),
          red_packet->length() - rtp_header_length,
          rtp_header_length,
          capture_time_ms,
          storage,
          PacedSender::kNormalPriority);

      ret |= packet_success;

      if (packet_success == 0) {
        fec_overhead_sent += red_packet->length();
      }
      delete red_packet;
      red_packet = NULL;
    }
    _videoBitrate.Update(video_sent);
    _fecOverheadRate.Update(fec_overhead_sent);
    return ret;
  }
  TRACE_EVENT_INSTANT2("webrtc_rtp", "Video::PacketNormal",
                       "timestamp", capture_timestamp,
                       "seqnum", _rtpSender.SequenceNumber());
  int ret = _rtpSender.SendToNetwork(data_buffer,
                                     payload_length,
                                     rtp_header_length,
                                     capture_time_ms,
                                     storage,
                                     PacedSender::kNormalPriority);
  if (ret == 0) {
    _videoBitrate.Update(payload_length + rtp_header_length);
  }
  return ret;
}

int32_t
RTPSenderVideo::SendRTPIntraRequest()
{
    // RFC 2032
    // 5.2.1.  Full intra-frame Request (FIR) packet

    uint16_t length = 8;
    uint8_t data[8];
    data[0] = 0x80;
    data[1] = 192;
    data[2] = 0;
    data[3] = 1; // length

    RtpUtility::AssignUWord32ToBuffer(data + 4, _rtpSender.SSRC());

    TRACE_EVENT_INSTANT1("webrtc_rtp",
                         "Video::IntraRequest",
                         "seqnum", _rtpSender.SequenceNumber());
    return _rtpSender.SendToNetwork(data, 0, length, -1, kDontStore,
                                    PacedSender::kNormalPriority);
}

int32_t
RTPSenderVideo::SetGenericFECStatus(const bool enable,
                                    const uint8_t payloadTypeRED,
                                    const uint8_t payloadTypeFEC)
{
    _fecEnabled = enable;
    _payloadTypeRED = payloadTypeRED;
    _payloadTypeFEC = payloadTypeFEC;
    memset(&delta_fec_params_, 0, sizeof(delta_fec_params_));
    memset(&key_fec_params_, 0, sizeof(key_fec_params_));
    delta_fec_params_.max_fec_frames = key_fec_params_.max_fec_frames = 1;
    delta_fec_params_.fec_mask_type = key_fec_params_.fec_mask_type =
          kFecMaskRandom;
    return 0;
}

int32_t
RTPSenderVideo::GenericFECStatus(bool& enable,
                                 uint8_t& payloadTypeRED,
                                 uint8_t& payloadTypeFEC) const
{
    enable = _fecEnabled;
    payloadTypeRED = _payloadTypeRED;
    payloadTypeFEC = _payloadTypeFEC;
    return 0;
}

uint16_t
RTPSenderVideo::FECPacketOverhead() const
{
    if (_fecEnabled)
    {
      // Overhead is FEC headers plus RED for FEC header plus anything in RTP
      // header beyond the 12 bytes base header (CSRC list, extensions...)
      // This reason for the header extensions to be included here is that
      // from an FEC viewpoint, they are part of the payload to be protected.
      // (The base RTP header is already protected by the FEC header.)
      return ForwardErrorCorrection::PacketOverhead() + REDForFECHeaderLength +
             (_rtpSender.RTPHeaderLength() - kRtpHeaderSize);
    }
    return 0;
}

int32_t RTPSenderVideo::SetFecParameters(
    const FecProtectionParams* delta_params,
    const FecProtectionParams* key_params) {
  assert(delta_params);
  assert(key_params);
  delta_fec_params_ = *delta_params;
  key_fec_params_ = *key_params;
  return 0;
}

int32_t RTPSenderVideo::SendVideo(const RtpVideoCodecTypes videoType,
                                  const FrameType frameType,
                                  const int8_t payloadType,
                                  const uint32_t captureTimeStamp,
                                  int64_t capture_time_ms,
                                  const uint8_t* payloadData,
                                  const uint32_t payloadSize,
                                  const RTPFragmentationHeader* fragmentation,
                                  VideoCodecInformation* codecInfo,
                                  const RTPVideoTypeHeader* rtpTypeHdr) {
  if (payloadSize == 0) {
    return -1;
  }

  if (frameType == kVideoFrameKey) {
    producer_fec_.SetFecParameters(&key_fec_params_, _numberFirstPartition);
  } else {
    producer_fec_.SetFecParameters(&delta_fec_params_, _numberFirstPartition);
  }

  // Default setting for number of first partition packets:
  // Will be extracted in SendVP8 for VP8 codec; other codecs use 0
  _numberFirstPartition = 0;

  switch (videoType) {
    case kRtpVideoGeneric:
      return SendGeneric(frameType,
                         payloadType,
                         captureTimeStamp,
                         capture_time_ms,
                         payloadData,
                         payloadSize);
    case kRtpVideoVp8:
      return SendVP8(frameType,
                     payloadType,
                     captureTimeStamp,
                     capture_time_ms,
                     payloadData,
                     payloadSize,
                     fragmentation,
                     rtpTypeHdr);
    case kRtpVideoH264:
      return SendH264(frameType,
                      payloadType,
                      captureTimeStamp,
                      capture_time_ms,
                      payloadData,
                      payloadSize,
                      fragmentation,
                      rtpTypeHdr)
                 ? 0
                 : -1;
    default:
      assert(false);
      break;
  }
  return 0;
}

int32_t RTPSenderVideo::SendGeneric(const FrameType frame_type,
                                    const int8_t payload_type,
                                    const uint32_t capture_timestamp,
                                    int64_t capture_time_ms,
                                    const uint8_t* payload,
                                    uint32_t size) {
  assert(frame_type == kVideoFrameKey || frame_type == kVideoFrameDelta);
  uint16_t rtp_header_length = _rtpSender.RTPHeaderLength();
  uint16_t max_length = _rtpSender.MaxPayloadLength() - FECPacketOverhead() -
                        rtp_header_length - (1 /* generic header length */);

  // Fragment packets more evenly by splitting the payload up evenly.
  uint32_t num_packets = (size + max_length - 1) / max_length;
  uint32_t payload_length = (size + num_packets - 1) / num_packets;
  assert(payload_length <= max_length);

  // Fragment packet into packets of max MaxPayloadLength bytes payload.
  uint8_t buffer[IP_PACKET_SIZE];

  uint8_t generic_header = RtpFormatVideoGeneric::kFirstPacketBit;
  if (frame_type == kVideoFrameKey) {
    generic_header |= RtpFormatVideoGeneric::kKeyFrameBit;
  }

  while (size > 0) {
    if (size < payload_length) {
      payload_length = size;
    }
    size -= payload_length;

    // MarkerBit is 1 on final packet (bytes_to_send == 0)
    if (_rtpSender.BuildRTPheader(buffer, payload_type, size == 0,
                                  capture_timestamp,
                                  capture_time_ms) != rtp_header_length) {
      return -1;
    }

    uint8_t* out_ptr = &buffer[rtp_header_length];

    // Put generic header in packet
    *out_ptr++ = generic_header;
    // Remove first-packet bit, following packets are intermediate
    generic_header &= ~RtpFormatVideoGeneric::kFirstPacketBit;

    // Put payload in packet
    memcpy(out_ptr, payload, payload_length);
    payload += payload_length;

    if (SendVideoPacket(buffer, payload_length + 1, rtp_header_length,
                        capture_timestamp, capture_time_ms,
                        kAllowRetransmission, true)) {
      return -1;
    }
  }
  return 0;
}

VideoCodecInformation*
RTPSenderVideo::CodecInformationVideo()
{
    return _videoCodecInformation;
}

void
RTPSenderVideo::SetMaxConfiguredBitrateVideo(const uint32_t maxBitrate)
{
    _maxBitrate = maxBitrate;
}

uint32_t
RTPSenderVideo::MaxConfiguredBitrateVideo() const
{
    return _maxBitrate;
}

int32_t
RTPSenderVideo::SendVP8(const FrameType frameType,
                        const int8_t payloadType,
                        const uint32_t captureTimeStamp,
                        int64_t capture_time_ms,
                        const uint8_t* payloadData,
                        const uint32_t payloadSize,
                        const RTPFragmentationHeader* fragmentation,
                        const RTPVideoTypeHeader* rtpTypeHdr)
{
    const uint16_t rtpHeaderLength = _rtpSender.RTPHeaderLength();

    int32_t payloadBytesToSend = payloadSize;
    const uint8_t* data = payloadData;

    uint16_t maxPayloadLengthVP8 = _rtpSender.MaxDataPayloadLength();

    assert(rtpTypeHdr);
    // Initialize disregarding partition boundaries: this will use kEqualSize
    // packetization mode, which produces ~equal size packets for each frame.
    RtpPacketizerVp8 packetizer(rtpTypeHdr->VP8, maxPayloadLengthVP8);
    packetizer.SetPayloadData(data, payloadBytesToSend, NULL);

    StorageType storage = kAllowRetransmission;
    if (rtpTypeHdr->VP8.temporalIdx == 0 &&
        !(_retransmissionSettings & kRetransmitBaseLayer)) {
      storage = kDontRetransmit;
    } else if (rtpTypeHdr->VP8.temporalIdx != kNoTemporalIdx &&
        rtpTypeHdr->VP8.temporalIdx > 0 &&
        !(_retransmissionSettings & kRetransmitHigherLayers)) {
      storage = kDontRetransmit;
    }

    bool last = false;
    _numberFirstPartition = 0;
    // |rtpTypeHdr->VP8.temporalIdx| is zero for base layers, or kNoTemporalIdx
    // if the field isn't used (so all layers are the base layer).  We currently
    // only protect base layers, so look for these two cases.
    bool protect = rtpTypeHdr->VP8.temporalIdx == 0 ||
        rtpTypeHdr->VP8.temporalIdx == kNoTemporalIdx;
    while (!last)
    {
        // Write VP8 Payload Descriptor and VP8 payload.
        uint8_t dataBuffer[IP_PACKET_SIZE] = {0};
        size_t payloadBytesInPacket = 0;
        if (!packetizer.NextPacket(
                &dataBuffer[rtpHeaderLength], &payloadBytesInPacket, &last))
          return -1;

        // Write RTP header.
        // Set marker bit true if this is the last packet in frame.
        _rtpSender.BuildRTPheader(dataBuffer, payloadType, last,
            captureTimeStamp, capture_time_ms);
        if (-1 == SendVideoPacket(dataBuffer, payloadBytesInPacket,
                                  rtpHeaderLength, captureTimeStamp,
                                  capture_time_ms, storage, protect))
        {
          LOG(LS_WARNING)
              << "RTPSenderVideo::SendVP8 failed to send packet number "
              << _rtpSender.SequenceNumber();
        }
    }
    TRACE_EVENT_ASYNC_END1("webrtc", "Video", capture_time_ms,
                           "timestamp", _rtpSender.Timestamp());
    return 0;
}

bool RTPSenderVideo::SendH264(const FrameType frameType,
                              const int8_t payloadType,
                              const uint32_t captureTimeStamp,
                              int64_t capture_time_ms,
                              const uint8_t* payloadData,
                              const uint32_t payloadSize,
                              const RTPFragmentationHeader* fragmentation,
                              const RTPVideoTypeHeader* rtpTypeHdr) {
  size_t rtp_header_length = _rtpSender.RTPHeaderLength();
  int32_t payload_bytes_to_send = payloadSize;
  const uint8_t* data = payloadData;
  size_t max_payload_length = _rtpSender.MaxDataPayloadLength();

  scoped_ptr<RtpPacketizer> packetizer(
      RtpPacketizer::Create(kRtpVideoH264, max_payload_length));
  packetizer->SetPayloadData(data, payload_bytes_to_send, fragmentation);

  StorageType storage = kAllowRetransmission;
  bool protect = (frameType == kVideoFrameKey);
  bool last = false;

  while (!last) {
    // Write H264 payload.
    uint8_t dataBuffer[IP_PACKET_SIZE] = {0};
    size_t payload_bytes_in_packet = 0;
    if (!packetizer->NextPacket(
            &dataBuffer[rtp_header_length], &payload_bytes_in_packet, &last)) {
      return false;
    }

    // Write RTP header.
    // Set marker bit true if this is the last packet in frame.
    _rtpSender.BuildRTPheader(
        dataBuffer, payloadType, last, captureTimeStamp, capture_time_ms);
    if (SendVideoPacket(dataBuffer,
                        payload_bytes_in_packet,
                        rtp_header_length,
                        captureTimeStamp,
                        capture_time_ms,
                        storage,
                        protect)) {
      LOG(LS_WARNING)
          << "RTPSenderVideo::SendH264 failed to send packet number "
          << _rtpSender.SequenceNumber();
    }
  }
  return true;
}

void RTPSenderVideo::ProcessBitrate() {
  _videoBitrate.Process();
  _fecOverheadRate.Process();
}

uint32_t RTPSenderVideo::VideoBitrateSent() const {
  return _videoBitrate.BitrateLast();
}

uint32_t RTPSenderVideo::FecOverheadRate() const {
  return _fecOverheadRate.BitrateLast();
}

int RTPSenderVideo::SelectiveRetransmissions() const {
  return _retransmissionSettings;
}

int RTPSenderVideo::SetSelectiveRetransmissions(uint8_t settings) {
  _retransmissionSettings = settings;
  return 0;
}

}  // namespace webrtc


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>
#include <assert.h>
#include <exception>

// UnityEngine.Font/FontTextureRebuildCallback
struct FontTextureRebuildCallback_t401089076;
// System.Object
struct Il2CppObject;
// System.IAsyncResult
struct IAsyncResult_t537683269;
// System.AsyncCallback
struct AsyncCallback_t1363551830;

#include "codegen/il2cpp-codegen.h"
#include "mscorlib_System_Object837106420.h"
#include "mscorlib_System_IntPtr676692020.h"
#include "mscorlib_System_AsyncCallback1363551830.h"

// System.Void UnityEngine.Font/FontTextureRebuildCallback::.ctor(System.Object,System.IntPtr)
extern "C"  void FontTextureRebuildCallback__ctor_m2909762077 (FontTextureRebuildCallback_t401089076 * __this, Il2CppObject * ___object, IntPtr_t ___method, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void UnityEngine.Font/FontTextureRebuildCallback::Invoke()
extern "C"  void FontTextureRebuildCallback_Invoke_m3507488951 (FontTextureRebuildCallback_t401089076 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
extern "C" void pinvoke_delegate_wrapper_FontTextureRebuildCallback_t401089076(Il2CppObject* delegate);
// System.IAsyncResult UnityEngine.Font/FontTextureRebuildCallback::BeginInvoke(System.AsyncCallback,System.Object)
extern "C"  Il2CppObject * FontTextureRebuildCallback_BeginInvoke_m2984345076 (FontTextureRebuildCallback_t401089076 * __this, AsyncCallback_t1363551830 * ___callback, Il2CppObject * ___object, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void UnityEngine.Font/FontTextureRebuildCallback::EndInvoke(System.IAsyncResult)
extern "C"  void FontTextureRebuildCallback_EndInvoke_m2078440109 (FontTextureRebuildCallback_t401089076 * __this, Il2CppObject * ___result, const MethodInfo* method) IL2CPP_METHOD_ATTR;

redpajama_set_name: RedPajamaGithub


text:
package com.coolweather.coolweather.db;

import org.litepal.crud.DataSupport;

/**
 * Created by macbookpro on 3/22/17.
 */

public class City extends DataSupport {
    private int id;

    private String cityName;

    private int cityCode;

    private int provinceId;

    public int getId(){
        return id;
    }

    public void setId (int id){
        this.id = id;
    }

    public String getCityName(){
        return cityName;
    }

    public void setCityName(String cityName){
        this.cityName = cityName;
    }

    public int getCityCode(){
        return cityCode;
    }

    public void setCityCode (int cityCode){
        this.cityCode = cityCode;
    }

    public int getProvinceId(){
        return provinceId;
    }

    public void  setProvinceId(int provinceId){
        this.provinceId = provinceId;
    }

}


text:
Rails.application.routes.draw do
  resources :events

  resources :locations do
    resources :events
  end

  resources :participants do
    resources :events
  end

  resources :locations do
    resources :events, only: :index
  end

  resources :events do
    resources :participants, only: :index
  end

  get 'welcome/home'
  root 'welcome#home'

  get '/signin' => "sessions#signin"
  post '/signin' => 'sessions#signin_post', as: "signin_post"
  get '/signup' => 'sessions#signup'
  post '/signup' => 'sessions#signup_post', as: "signup_post"
  delete "/signout" => 'sessions#signout'

  get '/auth/facebook/callback' => 'sessions#facebook'
end


text:
+++
date = "2017-06-11T13:05:10-03:00"
title = "Directives"
weight = 55

+++

This directives **remove** or **add** the element from the DOM based on security credentials.

* __*secIsAutheticated__
* __*secIsNotAuthenticated__
* __*secHasRole__
* __*secHasAllRoles__
* __*secHasAnyRole__
* __*secHasNotRoles__

{{% notice tip %}}
**Note:** In all directives, you can also opt-in to add a class in the element, instead of removing it. Useful if you want
to keep the element in DOM. For example to just disable a button using css class _disabled_
{{% /notice %}}

To opt-in for this behavior check [Configuration]({{< relref "#configuration" >}})

{{% notice info %}}
**Second Note:** Works only if a login is associated with the page, if not the expression will always return false.
In other words pages Not protected by a LoginGuard will always evaluate to false and will *NOT* display the element.
That is true for all directives
{{% /notice %}}

## secIsAuthenticated

Display the DOM element if user is authenticated, remove if not

### Examples

```html

<div *secIsAuthenticated>This will show if user is autheticated</div>

```

## secIsNotAuthenticated

Display the DOM element if _NOT_ authenticated (anonymous users), remove otherwise.

### Examples

```html

<div *secIsNotAuthenticated>This will show if user is NOT autheticated</div>

```

## secHasRole

Check if user has role, if not hide element from DOM.

Parameters:

* _role_ - The role of the user. Need to be a string
* _resource_ - The resource to check the role. Defaults to the clientId.

### Examples

Suppose a user in role *ROLE_ADMIN* on *client-id* resource (default, in keycloak means the current application)

```html
    <div *secHasRole="'ROLE_ADMIN'">this should display</div>
    <div *secHasRole="'ROLE_ADMIN'; resource 'client-id'">this should display</div>
    <div *secHasRole="'ROLE_ADMIN'; resource 'other'">this should NOT display</div>
    <div *secHasRole="'ROLE_USER'; resource 'client-id'">this should NOT display</div>
```
## secHasAnyRoles

Check if user is on **Any** of the roles. Roles are a string separated by **,** or a array of strings

Examples
```html
    <div *secHasAnyRoles="'ROLE_ADMIN, ACTION_EDIT'">this should display</div>
    <div *secHasAnyRoles="rolesArray">this should display</div>
```
```typescript
 export class PageComponent {
      rolesArray = ['ROLE_ADMIN', 'ACTION_EDIT']
 }
```

## secHasAllRoles

Check if user in on **All** roles. Roles is a string separated by **,** or a array of strings

Examples
```html
    <div *secHasAllRoles="'ACTION_UPDATE, ACTION_EDIT'">this should display</div>
```

## secHasNotRoles

Check if user in **NOT** on **Any** roles. Roles is a string separated by **,** or  a array of strings

Examples
```html
    <div *secHasNotRoles="'ROLE_USER, ROLE_LIGHT_USER'">this should display</div>
```

# Configuration

Any directive can be configured with the follow properties:

* __action__ Action to be performed. Acepted values are: __remove__, __addClass__. Defaults to __remove__
* __resource__ Resource to check the element. Keycloak JS default is __client-id__
* __cssClass__ CSS class to be added in the element, instead of remove it from DOM. Defaults to __disabled__

Examples

```html
<div *secHasRole="'ROLE_ADMIN'; action 'remove'">this should be removed</div>
<div *secHasAnyRoles="'ROLE_ADMIN'; action 'addClass'; cssClass 'invisible' ">this should has class <b>invisible</b></div>
<div *secHasRole="'ROLE_ADMIN' action 'addClass'">this should has class <b>disabled</b></div>
```

You can also configure the global behaviour. Overriding the provider for **SecDirectiveConfig**

```typescript

    import { NgModule } from '@angular/core'

    import { AppComponent } from './app.component'

    import {AuthModule, SecDirectiveConfig, SecAction, InitOptions} from "angular-spa/auth"

    export class CustomSecDirectiveConfig extends SecDirectiveConfig {
        action: SecAction = 'addClass'
        defaultClass = 'myClass'
    }

    @NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        AuthModule
    ],
    providers: [
       {
         provide: InitOptions,
         useValue: {
            url: 'http://localhost:9080/auth',
            realm: 'master',
            clientId: 'con-client'
         }
       }, {
         provide: SecDirectiveConfig,
         useClass: CustomSecDirectiveConfig
       }
      ],
    bootstrap: [AppComponent]
    })
    export class AppModule { }

```


text:
using System;
using System.Runtime.Serialization;

namespace NuGet
{
    [DataContract]
    public class PackageSource : IEquatable<PackageSource>
    {
        [DataMember]
        public string Name { get; private set; }

        [DataMember]
        public string Source { get; private set; }

        /// <summary>
        /// This does not represent just the NuGet Official Feed alone
        /// It may also represent a Default Package Source set by Configuration Defaults
        /// </summary>
        public bool IsOfficial { get; set; }

        public bool IsMachineWide { get; set; }

        public bool IsEnabled { get; set; }

        public string UserName { get; set; }

        public string Password { get; set; }

        public bool IsPasswordClearText { get; set; }

        public PackageSource(string source) :
            this(source, source, isEnabled: true)
        {
        }

        public PackageSource(string source, string name) :
            this(source, name, isEnabled: true)
        {
        }

        public PackageSource(string source, string name, bool isEnabled)
            : this(source, name, isEnabled, isOfficial: false)
        {
        }

        public PackageSource(string source, string name, bool isEnabled, bool isOfficial)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

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

            Name = name;
            Source = source;
            IsEnabled = isEnabled;
            IsOfficial = isOfficial;
        }

        public bool Equals(PackageSource other)
        {
            if (other == null)
            {
                return false;
            }

            return Name.Equals(other.Name, StringComparison.CurrentCultureIgnoreCase) &&
                Source.Equals(other.Source, StringComparison.OrdinalIgnoreCase);
        }

        public override bool Equals(object obj)
        {
            var source = obj as PackageSource;
            if (source != null)
            {
                return Equals(source);
            }
            return base.Equals(obj);
        }

        public override string ToString()
        {
            return Name + " [" + Source + "]";
        }

        public override int GetHashCode()
        {
            return Name.GetHashCode() * 3137 + Source.GetHashCode();
        }

        public PackageSource Clone()
        {
            return new PackageSource(Source, Name, IsEnabled, IsOfficial) { UserName = UserName, Password = Password, IsPasswordClearText = IsPasswordClearText, IsMachineWide = IsMachineWide };
        }
    }
}


text:
/**
 * External dependencies
 */
import PropTypes from 'prop-types';
import { sprintf, __ } from '@googleforcreators/i18n';
import {
  Button,
  BUTTON_SIZES,
  BUTTON_TYPES,
  Headline,
  THEME_CONSTANTS,
  InfiniteScroller,
} from '@googleforcreators/design-system';

/**
 * Internal dependencies
 */
import { resolveRoute } from '../../../router';
import { APP_ROUTES } from '../../../../constants';
import { Layout, StandardViewContentGutter } from '../../../../components';
import { StoriesPropType, StoryActionsPropType } from '../../../../types';
import {
  ViewPropTypes,
  PagePropTypes,
  ShowStoriesWhileLoadingPropType,
} from '../../../../utils/useStoryView';
import { EmptyContentMessage } from '../../shared';
import StoriesView from './storiesView';

function NoAvailableContent({ filtersObject }) {
  const { search } = filtersObject;
  if (search) {
    return sprintf(
      /* translators: %s: search term. */
      __('Sorry, we couldn\'t find any results matching "%s"', 'web-stories'),
      search
    );
  } else if (Object.keys(filtersObject).length !== 0) {
    return __("Sorry, we couldn't find any results", 'web-stories');
  } else {
    return __('Start telling Stories.', 'web-stories');
  }
}
NoAvailableContent.propTypes = {
  filtersObject: PropTypes.object,
};

function Content({
  allPagesFetched,
  canViewDefaultTemplates,
  filtersObject = {},
  loading,
  page,
  stories,
  storyActions,
  view,
}) {
  return (
    <Layout.Scrollable>
      <StandardViewContentGutter>
        {stories.length > 0 ? (
          <>
            <StoriesView
              storyActions={storyActions}
              stories={stories}
              view={view}
              loading={loading}
            />
            <InfiniteScroller
              canLoadMore={!allPagesFetched}
              isLoading={loading?.isLoading}
              allDataLoadedMessage={__('No more stories', 'web-stories')}
              allDataLoadedAriaMessage={__(
                'All stories are loaded',
                'web-stories'
              )}
              loadingAriaMessage={__('Loading more stories', 'web-stories')}
              onLoadMore={page.requestNextPage}
            />
          </>
        ) : (
          !loading?.isLoading && (
            <EmptyContentMessage>
              <Headline
                size={THEME_CONSTANTS.TYPOGRAPHY.PRESET_SIZES.SMALL}
                as="h3"
              >
                <NoAvailableContent filtersObject={filtersObject} />
              </Headline>
              {Object.keys(filtersObject).length === 0 &&
                canViewDefaultTemplates && (
                  <Button
                    type={BUTTON_TYPES.PRIMARY}
                    size={BUTTON_SIZES.MEDIUM}
                    as="a"
                    href={resolveRoute(APP_ROUTES.TEMPLATES_GALLERY)}
                  >
                    {__('Explore Templates', 'web-stories')}
                  </Button>
                )}
            </EmptyContentMessage>
          )
        )}
      </StandardViewContentGutter>
    </Layout.Scrollable>
  );
}
Content.propTypes = {
  allPagesFetched: PropTypes.bool,
  canViewDefaultTemplates: PropTypes.bool,
  filtersObject: PropTypes.object,
  loading: PropTypes.shape({
    isLoading: PropTypes.bool,
    showStoriesWhileLoading: ShowStoriesWhileLoadingPropType,
  }),
  page: PagePropTypes,
  stories: StoriesPropType,
  storyActions: StoryActionsPropType,
  view: ViewPropTypes,
};

export default Content;


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using NConsoleMenu;

namespace NConsoleMenu.Sample.Examples
{
	/// <summary>
	/// When the command takes a complex argument, comprised of
	/// multiple parts, a Regex is a simple and quite powerful way
	/// to handle it.
	///
	/// This command 'Greet' uses two parameters, a string and a
	/// number. Parsing them is done in the action body.
	/// </summary>
	public class MI_ComplexArgument : CMenuItem
	{
		public MI_ComplexArgument ()
			: base ("greet")
		{
			HelpText = "Greets a name a number of times.";
		}

		public override void Execute (string arg)
		{
			var regex = new Regex (@"(?<name>[^ ]*) (?<times>[0-9]*)");
			var match = regex.Match (arg);
			var name = match.Groups["name"].Value;
			var times = int.Parse (match.Groups["times"].Value);
			for (int i = 0; i < times; i++) {
				Console.WriteLine ($"Hello {name}!");
			}
		}
	}
}


text:
import mock
import json
import library.openshift_resource

from mock import ANY

@mock.patch('library.openshift_resource.ResourceModule.patch_resource', autospec=True)
@mock.patch('library.openshift_resource.ResourceModule.export_resource', autospec=True)
@mock.patch('library.openshift_resource.AnsibleModule', autospec=True)
def test_patch_change(module_cls, export_resource, patch_resource):
  with open('tests/data/dc_openshift3-docker-hello.json', 'r') as f:
    dc = json.load(f)

  export_resource.return_value = dc

  with open('tests/data/dc_patch1.json', 'r') as f:
    dc_patch = json.load(f)

  module = module_cls.return_value
  module.params = {
    "namespace": "test",
    "type": "dc",
    "name": "openshift3-hello-world",
    "patch": dc_patch,
  }

  library.openshift_resource.main()

  patch_resource.assert_called_once_with(ANY, 'dc', 'openshift3-hello-world', dc_patch)

  module.exit_json.assert_called_with(msg=ANY, changed=True)

@mock.patch('library.openshift_resource.ResourceModule.patch_resource', autospec=True)
@mock.patch('library.openshift_resource.ResourceModule.export_resource', autospec=True)
@mock.patch('library.openshift_resource.AnsibleModule', autospec=True)
def test_patch_no_change(module_cls, export_resource, patch_resource):
  with open('tests/data/dc_openshift3-docker-hello_2.json', 'r') as f:
    dc = json.load(f)

  export_resource.return_value = dc

  with open('tests/data/dc_patch1.json', 'r') as f:
    dc_patch = json.load(f)

  module = module_cls.return_value
  module.params = {
    "namespace": "test",
    "type": "dc",
    "name": "openshift3-hello-world",
    "patch": dc_patch,
  }

  library.openshift_resource.main()

  assert patch_resource.call_count == 0

  module.exit_json.assert_called_with(msg=ANY, changed=False)

@mock.patch('library.openshift_resource.ResourceModule.patch_resource', autospec=True)
@mock.patch('library.openshift_resource.ResourceModule.export_resource', autospec=True)
@mock.patch('library.openshift_resource.ResourceModule.process_template', autospec=True)
@mock.patch('library.openshift_resource.AnsibleModule', autospec=True)
def test_template(module_cls, process_template, export_resource, patch_resource):
  with open('tests/data/template_pruner.json', 'r') as f:
    template = json.load(f)

  with open('tests/data/is_rhel7.json', 'r') as f:
    imagestream = json.load(f)

  process_template.return_value = template
  export_resource.return_value = imagestream

  with open('tests/data/dc_patch1.json', 'r') as f:
    dc_patch = json.load(f)

  module = module_cls.return_value
  module.params = {
    "namespace": "test",
    "template": template,
  }

  library.openshift_resource.main()

  assert patch_resource.call_count == 0

  module.exit_json.assert_called_with(msg=ANY, changed=False)


text:
package org.matrix.androidsdk.rest.model.bingrules;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.text.TextUtils;

import java.util.ArrayList;
import java.util.List;

public class PushRuleSet {
    public List<BingRule> override;
    public List<ContentRule> content;
    public List<BingRule> room;
    public List<BingRule> sender;
    public List<BingRule> underride;

    /**
     * Constructor
     */
    public PushRuleSet() {
        override = new ArrayList<>();
        content = new ArrayList<>();
        room = new ArrayList<>();
        sender = new ArrayList<>();
        underride = new ArrayList<>();
    }

    /**
     * Find a rule from its rule ID.
     *
     * @param rules  the rules list.
     * @param ruleID the rule ID.
     * @return the bing rule if it exists, else null.
     */
    @Nullable
    private BingRule findRule(List<BingRule> rules, String ruleID) {
        for (BingRule rule : rules) {
            if (TextUtils.equals(ruleID, rule.ruleId)) {
                return rule;
            }
        }
        return null;
    }

    @Nullable
    private List<BingRule> getBingRulesList(String kind) {
        List<BingRule> res = null;

        if (BingRule.KIND_OVERRIDE.equals(kind)) {
            res = override;
        } else if (BingRule.KIND_ROOM.equals(kind)) {
            res = room;
        } else if (BingRule.KIND_SENDER.equals(kind)) {
            res = sender;
        } else if (BingRule.KIND_UNDERRIDE.equals(kind)) {
            res = underride;
        }

        return res;
    }

    /**
     * Add a rule from the bingRules
     *
     * @param rule the rule to add.
     */
    public void addAtTop(BingRule rule) {
        if (TextUtils.equals(BingRule.KIND_CONTENT, rule.kind)) {
            if (null != content) {
                if (rule instanceof ContentRule) {
                    content.add(0, (ContentRule) rule);
                }
            }
        } else {
            List<BingRule> rulesList = getBingRulesList(rule.kind);

            if (null != rulesList) {
                rulesList.add(0, rule);
            }
        }
    }

    /**
     * Remove a rule from the bingRules
     *
     * @param rule the rule to delete.
     * @return true if the rule has been deleted
     */
    public boolean remove(BingRule rule) {
        boolean res = false;

        if (BingRule.KIND_CONTENT.equals(rule.kind)) {
            if (null != content) {
                res = content.remove(rule);
            }
        } else {
            List<BingRule> rulesList = getBingRulesList(rule.kind);

            if (null != rulesList) {
                res = rulesList.remove(rule);
            }
        }

        return res;
    }

    /**
     * Find a rule from its rule ID.
     *
     * @param rules  the rules list.
     * @param ruleID the rule ID.
     * @return the bing rule if it exists, else null.
     */
    @Nullable
    private BingRule findContentRule(List<ContentRule> rules, String ruleID) {
        for (BingRule rule : rules) {
            if (TextUtils.equals(ruleID, rule.ruleId)) {
                return rule;
            }
        }
        return null;
    }

    /**
     * Find a rule from its ruleID.
     *
     * @param ruleId a RULE_ID_XX value
     * @return the matched bing rule or null it doesn't exist.
     */
    @Nullable
    public BingRule findDefaultRule(String ruleId) {
        BingRule rule = null;

        // sanity check
        if (null != ruleId) {
            if (TextUtils.equals(BingRule.RULE_ID_CONTAIN_USER_NAME, ruleId)) {
                rule = findContentRule(content, ruleId);
            } else {
                // assume that the ruleId is unique.
                rule = findRule(override, ruleId);

                if (null == rule) {
                    rule = findRule(underride, ruleId);
                }
            }
        }

        return rule;
    }

    /**
     * Return the content rules list.
     *
     * @return the content rules list.
     */
    @NonNull
    public List<BingRule> getContentRules() {
        List<BingRule> res = new ArrayList<>();

        if (null != content) {
            for (BingRule rule : content) {
                if (!rule.ruleId.startsWith(".m.")) {
                    res.add(rule);
                }
            }
        }

        return res;
    }

    /**
     * Return the room rules list.
     *
     * @return the room rules list.
     */
    @NonNull
    public List<BingRule> getRoomRules() {
        if (null == room) {
            return new ArrayList<>();
        } else {
            return room;
        }
    }

    /**
     * Return the room rules list.
     *
     * @return the sender rules list.
     */
    @NonNull
    public List<BingRule> getSenderRules() {
        if (null == sender) {
            return new ArrayList<>();
        } else {
            return sender;
        }
    }
}


text:
require "rails"

%w(
  active_record
  action_controller
  action_mailer
  active_resource
  rails/test_unit
).each do |framework|
  begin
    require "#{framework}/railtie"
  rescue LoadError
  end
end


text:
package org.jfree.data;

import org.jfree.chart.TestUtilities;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.fail;

/**
 * Tests for the {@link ComparableObjectItem} class.
 */
public class ComparableObjectItemTest {

    /**
     * Some checks for the constructor.
     */
    @Test
    public void testConstructor() {
        // check null argument 1
        try {
            /* ComparableObjectItem item1 = */ new ComparableObjectItem(null,
                    "XYZ");
            fail("There should be an exception.");
        }
        catch (IllegalArgumentException e) {
            // expected
        }
    }

    /**
     * Confirm that the equals method can distinguish all the required fields.
     */
    @Test
    public void testEquals() {
        ComparableObjectItem item1 = new ComparableObjectItem(new Integer(1),
                "XYZ");
        ComparableObjectItem item2 = new ComparableObjectItem(new Integer(1),
                "XYZ");
        assertEquals(item1, item2);

        item1 = new ComparableObjectItem(new Integer(2), "XYZ");
        assertNotEquals(item1, item2);
        item2 = new ComparableObjectItem(new Integer(2), "XYZ");
        assertEquals(item1, item2);

        item1 = new ComparableObjectItem(new Integer(2), null);
        assertNotEquals(item1, item2);
        item2 = new ComparableObjectItem(new Integer(2), null);
        assertEquals(item1, item2);
    }

    /**
     * Some checks for the clone() method.
     */
    @Test
    public void testCloning() throws CloneNotSupportedException {
        ComparableObjectItem item1 = new ComparableObjectItem(new Integer(1),
                "XYZ");
        ComparableObjectItem item2 = (ComparableObjectItem) item1.clone();
        assertNotSame(item1, item2);
        assertSame(item1.getClass(), item2.getClass());
        assertEquals(item1, item2);
    }

    /**
     * Serialize an instance, restore it, and check for equality.
     */
    @Test
    public void testSerialization() {
        ComparableObjectItem item1 = new ComparableObjectItem(new Integer(1),
                "XYZ");
        ComparableObjectItem item2 = (ComparableObjectItem)
                TestUtilities.serialised(item1);
        assertEquals(item1, item2);
    }

    /**
     * Some checks for the compareTo() method.
     */
    @Test
    public void testCompareTo() {
        ComparableObjectItem item1 = new ComparableObjectItem(new Integer(1),
                "XYZ");
        ComparableObjectItem item2 = new ComparableObjectItem(new Integer(2),
                "XYZ");
        ComparableObjectItem item3 = new ComparableObjectItem(new Integer(3),
                "XYZ");
        ComparableObjectItem item4 = new ComparableObjectItem(new Integer(1),
                "XYZ");
        assertTrue(item2.compareTo(item1) > 0);
        assertTrue(item3.compareTo(item1) > 0);
        assertTrue(item4.compareTo(item1) == 0);
        assertTrue(item1.compareTo(item2) < 0);
    }

}


text:
#include <stdio.h>

#include "libavutil/intreadwrite.h"
#include "avformat.h"
#include "internal.h"
#include "apetag.h"

/* The earliest and latest file formats supported by this library */
#define APE_MIN_VERSION 3800
#define APE_MAX_VERSION 3990

#define MAC_FORMAT_FLAG_8_BIT                 1 // is 8-bit [OBSOLETE]
#define MAC_FORMAT_FLAG_CRC                   2 // uses the new CRC32 error detection [OBSOLETE]
#define MAC_FORMAT_FLAG_HAS_PEAK_LEVEL        4 // uint32 nPeakLevel after the header [OBSOLETE]
#define MAC_FORMAT_FLAG_24_BIT                8 // is 24-bit [OBSOLETE]
#define MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS    16 // has the number of seek elements after the peak level
#define MAC_FORMAT_FLAG_CREATE_WAV_HEADER    32 // create the wave header on decompression (not stored)

#define APE_EXTRADATA_SIZE 6

typedef struct APEFrame {
    int64_t pos;
    int nblocks;
    int size;
    int skip;
    int64_t pts;
} APEFrame;

typedef struct APEContext {
    /* Derived fields */
    uint32_t junklength;
    uint32_t firstframe;
    uint32_t totalsamples;
    int currentframe;
    APEFrame *frames;

    /* Info from Descriptor Block */
    int16_t fileversion;
    int16_t padding1;
    uint32_t descriptorlength;
    uint32_t headerlength;
    uint32_t seektablelength;
    uint32_t wavheaderlength;
    uint32_t audiodatalength;
    uint32_t audiodatalength_high;
    uint32_t wavtaillength;
    uint8_t md5[16];

    /* Info from Header Block */
    uint16_t compressiontype;
    uint16_t formatflags;
    uint32_t blocksperframe;
    uint32_t finalframeblocks;
    uint32_t totalframes;
    uint16_t bps;
    uint16_t channels;
    uint32_t samplerate;

    /* Seektable */
    uint32_t *seektable;
    uint8_t  *bittable;
} APEContext;

static int ape_probe(const AVProbeData * p)
{
    int version = AV_RL16(p->buf+4);
    if (AV_RL32(p->buf) != MKTAG('M', 'A', 'C', ' '))
        return 0;

    if (version < APE_MIN_VERSION || version > APE_MAX_VERSION)
        return AVPROBE_SCORE_MAX/4;

    return AVPROBE_SCORE_MAX;
}

static void ape_dumpinfo(AVFormatContext * s, APEContext * ape_ctx)
{
#ifdef DEBUG
    int i;

    av_log(s, AV_LOG_DEBUG, "Descriptor Block:\n\n");
    av_log(s, AV_LOG_DEBUG, "fileversion          = %"PRId16"\n", ape_ctx->fileversion);
    av_log(s, AV_LOG_DEBUG, "descriptorlength     = %"PRIu32"\n", ape_ctx->descriptorlength);
    av_log(s, AV_LOG_DEBUG, "headerlength         = %"PRIu32"\n", ape_ctx->headerlength);
    av_log(s, AV_LOG_DEBUG, "seektablelength      = %"PRIu32"\n", ape_ctx->seektablelength);
    av_log(s, AV_LOG_DEBUG, "wavheaderlength      = %"PRIu32"\n", ape_ctx->wavheaderlength);
    av_log(s, AV_LOG_DEBUG, "audiodatalength      = %"PRIu32"\n", ape_ctx->audiodatalength);
    av_log(s, AV_LOG_DEBUG, "audiodatalength_high = %"PRIu32"\n", ape_ctx->audiodatalength_high);
    av_log(s, AV_LOG_DEBUG, "wavtaillength        = %"PRIu32"\n", ape_ctx->wavtaillength);
    av_log(s, AV_LOG_DEBUG, "md5                  = ");
    for (i = 0; i < 16; i++)
         av_log(s, AV_LOG_DEBUG, "%02x", ape_ctx->md5[i]);
    av_log(s, AV_LOG_DEBUG, "\n");

    av_log(s, AV_LOG_DEBUG, "\nHeader Block:\n\n");

    av_log(s, AV_LOG_DEBUG, "compressiontype      = %"PRIu16"\n", ape_ctx->compressiontype);
    av_log(s, AV_LOG_DEBUG, "formatflags          = %"PRIu16"\n", ape_ctx->formatflags);
    av_log(s, AV_LOG_DEBUG, "blocksperframe       = %"PRIu32"\n", ape_ctx->blocksperframe);
    av_log(s, AV_LOG_DEBUG, "finalframeblocks     = %"PRIu32"\n", ape_ctx->finalframeblocks);
    av_log(s, AV_LOG_DEBUG, "totalframes          = %"PRIu32"\n", ape_ctx->totalframes);
    av_log(s, AV_LOG_DEBUG, "bps                  = %"PRIu16"\n", ape_ctx->bps);
    av_log(s, AV_LOG_DEBUG, "channels             = %"PRIu16"\n", ape_ctx->channels);
    av_log(s, AV_LOG_DEBUG, "samplerate           = %"PRIu32"\n", ape_ctx->samplerate);

    av_log(s, AV_LOG_DEBUG, "\nSeektable\n\n");
    if ((ape_ctx->seektablelength / sizeof(uint32_t)) != ape_ctx->totalframes) {
        av_log(s, AV_LOG_DEBUG, "No seektable\n");
    } else {
        for (i = 0; i < ape_ctx->seektablelength / sizeof(uint32_t); i++) {
            if (i < ape_ctx->totalframes - 1) {
                av_log(s, AV_LOG_DEBUG, "%8d   %"PRIu32" (%"PRIu32" bytes)",
                       i, ape_ctx->seektable[i],
                       ape_ctx->seektable[i + 1] - ape_ctx->seektable[i]);
                if (ape_ctx->bittable)
                    av_log(s, AV_LOG_DEBUG, " + %2d bits\n",
                           ape_ctx->bittable[i]);
                av_log(s, AV_LOG_DEBUG, "\n");
            } else {
                av_log(s, AV_LOG_DEBUG, "%8d   %"PRIu32"\n", i, ape_ctx->seektable[i]);
            }
        }
    }

    av_log(s, AV_LOG_DEBUG, "\nFrames\n\n");
    for (i = 0; i < ape_ctx->totalframes; i++)
        av_log(s, AV_LOG_DEBUG, "%8d   %8"PRId64" %8d (%d samples)\n", i,
               ape_ctx->frames[i].pos, ape_ctx->frames[i].size,
               ape_ctx->frames[i].nblocks);

    av_log(s, AV_LOG_DEBUG, "\nCalculated information:\n\n");
    av_log(s, AV_LOG_DEBUG, "junklength           = %"PRIu32"\n", ape_ctx->junklength);
    av_log(s, AV_LOG_DEBUG, "firstframe           = %"PRIu32"\n", ape_ctx->firstframe);
    av_log(s, AV_LOG_DEBUG, "totalsamples         = %"PRIu32"\n", ape_ctx->totalsamples);
#endif
}

static int ape_read_header(AVFormatContext * s)
{
    AVIOContext *pb = s->pb;
    APEContext *ape = s->priv_data;
    AVStream *st;
    uint32_t tag;
    int i, ret;
    int total_blocks, final_size = 0;
    int64_t pts, file_size;

    /* Skip any leading junk such as id3v2 tags */
    ape->junklength = avio_tell(pb);

    tag = avio_rl32(pb);
    if (tag != MKTAG('M', 'A', 'C', ' '))
        return AVERROR_INVALIDDATA;

    ape->fileversion = avio_rl16(pb);

    if (ape->fileversion < APE_MIN_VERSION || ape->fileversion > APE_MAX_VERSION) {
        av_log(s, AV_LOG_ERROR, "Unsupported file version - %d.%02d\n",
               ape->fileversion / 1000, (ape->fileversion % 1000) / 10);
        return AVERROR_PATCHWELCOME;
    }

    if (ape->fileversion >= 3980) {
        ape->padding1             = avio_rl16(pb);
        ape->descriptorlength     = avio_rl32(pb);
        ape->headerlength         = avio_rl32(pb);
        ape->seektablelength      = avio_rl32(pb);
        ape->wavheaderlength      = avio_rl32(pb);
        ape->audiodatalength      = avio_rl32(pb);
        ape->audiodatalength_high = avio_rl32(pb);
        ape->wavtaillength        = avio_rl32(pb);
        avio_read(pb, ape->md5, 16);

        /* Skip any unknown bytes at the end of the descriptor.
           This is for future compatibility */
        if (ape->descriptorlength > 52)
            avio_skip(pb, ape->descriptorlength - 52);

        /* Read header data */
        ape->compressiontype      = avio_rl16(pb);
        ape->formatflags          = avio_rl16(pb);
        ape->blocksperframe       = avio_rl32(pb);
        ape->finalframeblocks     = avio_rl32(pb);
        ape->totalframes          = avio_rl32(pb);
        ape->bps                  = avio_rl16(pb);
        ape->channels             = avio_rl16(pb);
        ape->samplerate           = avio_rl32(pb);
    } else {
        ape->descriptorlength = 0;
        ape->headerlength = 32;

        ape->compressiontype      = avio_rl16(pb);
        ape->formatflags          = avio_rl16(pb);
        ape->channels             = avio_rl16(pb);
        ape->samplerate           = avio_rl32(pb);
        ape->wavheaderlength      = avio_rl32(pb);
        ape->wavtaillength        = avio_rl32(pb);
        ape->totalframes          = avio_rl32(pb);
        ape->finalframeblocks     = avio_rl32(pb);

        if (ape->formatflags & MAC_FORMAT_FLAG_HAS_PEAK_LEVEL) {
            avio_skip(pb, 4); /* Skip the peak level */
            ape->headerlength += 4;
        }

        if (ape->formatflags & MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS) {
            ape->seektablelength = avio_rl32(pb);
            ape->headerlength += 4;
            ape->seektablelength *= sizeof(int32_t);
        } else
            ape->seektablelength = ape->totalframes * sizeof(int32_t);

        if (ape->formatflags & MAC_FORMAT_FLAG_8_BIT)
            ape->bps = 8;
        else if (ape->formatflags & MAC_FORMAT_FLAG_24_BIT)
            ape->bps = 24;
        else
            ape->bps = 16;

        if (ape->fileversion >= 3950)
            ape->blocksperframe = 73728 * 4;
        else if (ape->fileversion >= 3900 || (ape->fileversion >= 3800  && ape->compressiontype >= 4000))
            ape->blocksperframe = 73728;
        else
            ape->blocksperframe = 9216;

        /* Skip any stored wav header */
        if (!(ape->formatflags & MAC_FORMAT_FLAG_CREATE_WAV_HEADER))
            avio_skip(pb, ape->wavheaderlength);
    }

    if(!ape->totalframes){
        av_log(s, AV_LOG_ERROR, "No frames in the file!\n");
        return AVERROR(EINVAL);
    }
    if(ape->totalframes > UINT_MAX / sizeof(APEFrame)){
        av_log(s, AV_LOG_ERROR, "Too many frames: %"PRIu32"\n",
               ape->totalframes);
        return AVERROR_INVALIDDATA;
    }
    if (ape->seektablelength / sizeof(*ape->seektable) < ape->totalframes) {
        av_log(s, AV_LOG_ERROR,
               "Number of seek entries is less than number of frames: %"SIZE_SPECIFIER" vs. %"PRIu32"\n",
               ape->seektablelength / sizeof(*ape->seektable), ape->totalframes);
        return AVERROR_INVALIDDATA;
    }
    ape->frames       = av_malloc_array(ape->totalframes, sizeof(APEFrame));
    if(!ape->frames)
        return AVERROR(ENOMEM);
    ape->firstframe   = ape->junklength + ape->descriptorlength + ape->headerlength + ape->seektablelength + ape->wavheaderlength;
    if (ape->fileversion < 3810)
        ape->firstframe += ape->totalframes;
    ape->currentframe = 0;

    ape->totalsamples = ape->finalframeblocks;
    if (ape->totalframes > 1)
        ape->totalsamples += ape->blocksperframe * (ape->totalframes - 1);

    if (ape->seektablelength > 0) {
        ape->seektable = av_mallocz(ape->seektablelength);
        if (!ape->seektable)
            return AVERROR(ENOMEM);
        for (i = 0; i < ape->seektablelength / sizeof(uint32_t) && !pb->eof_reached; i++)
            ape->seektable[i] = avio_rl32(pb);
        if (ape->fileversion < 3810) {
            ape->bittable = av_mallocz(ape->totalframes);
            if (!ape->bittable)
                return AVERROR(ENOMEM);
            for (i = 0; i < ape->totalframes && !pb->eof_reached; i++)
                ape->bittable[i] = avio_r8(pb);
        }
        if (pb->eof_reached)
            av_log(s, AV_LOG_WARNING, "File truncated\n");
    }

    ape->frames[0].pos     = ape->firstframe;
    ape->frames[0].nblocks = ape->blocksperframe;
    ape->frames[0].skip    = 0;
    for (i = 1; i < ape->totalframes; i++) {
        ape->frames[i].pos      = ape->seektable[i] + ape->junklength;
        ape->frames[i].nblocks  = ape->blocksperframe;
        ape->frames[i - 1].size = ape->frames[i].pos - ape->frames[i - 1].pos;
        ape->frames[i].skip     = (ape->frames[i].pos - ape->frames[0].pos) & 3;
    }
    ape->frames[ape->totalframes - 1].nblocks = ape->finalframeblocks;
    /* calculate final packet size from total file size, if available */
    file_size = avio_size(pb);
    if (file_size > 0) {
        final_size = file_size - ape->frames[ape->totalframes - 1].pos -
                     ape->wavtaillength;
        final_size -= final_size & 3;
    }
    if (file_size <= 0 || final_size <= 0)
        final_size = ape->finalframeblocks * 8;
    ape->frames[ape->totalframes - 1].size = final_size;

    for (i = 0; i < ape->totalframes; i++) {
        if(ape->frames[i].skip){
            ape->frames[i].pos  -= ape->frames[i].skip;
            ape->frames[i].size += ape->frames[i].skip;
        }
        ape->frames[i].size = (ape->frames[i].size + 3) & ~3;
    }
    if (ape->fileversion < 3810) {
        for (i = 0; i < ape->totalframes; i++) {
            if (i < ape->totalframes - 1 && ape->bittable[i + 1])
                ape->frames[i].size += 4;
            ape->frames[i].skip <<= 3;
            ape->frames[i].skip  += ape->bittable[i];
        }
    }

    ape_dumpinfo(s, ape);

    av_log(s, AV_LOG_VERBOSE, "Decoding file - v%d.%02d, compression level %"PRIu16"\n",
           ape->fileversion / 1000, (ape->fileversion % 1000) / 10,
           ape->compressiontype);

    /* now we are ready: build format streams */
    st = avformat_new_stream(s, NULL);
    if (!st)
        return AVERROR(ENOMEM);

    total_blocks = (ape->totalframes == 0) ? 0 : ((ape->totalframes - 1) * ape->blocksperframe) + ape->finalframeblocks;

    st->codecpar->codec_type      = AVMEDIA_TYPE_AUDIO;
    st->codecpar->codec_id        = AV_CODEC_ID_APE;
    st->codecpar->codec_tag       = MKTAG('A', 'P', 'E', ' ');
    st->codecpar->channels        = ape->channels;
    st->codecpar->sample_rate     = ape->samplerate;
    st->codecpar->bits_per_coded_sample = ape->bps;

    st->nb_frames = ape->totalframes;
    st->start_time = 0;
    st->duration  = total_blocks;
    avpriv_set_pts_info(st, 64, 1, ape->samplerate);

    if ((ret = ff_alloc_extradata(st->codecpar, APE_EXTRADATA_SIZE)) < 0)
        return ret;
    AV_WL16(st->codecpar->extradata + 0, ape->fileversion);
    AV_WL16(st->codecpar->extradata + 2, ape->compressiontype);
    AV_WL16(st->codecpar->extradata + 4, ape->formatflags);

    pts = 0;
    for (i = 0; i < ape->totalframes; i++) {
        ape->frames[i].pts = pts;
        av_add_index_entry(st, ape->frames[i].pos, ape->frames[i].pts, 0, 0, AVINDEX_KEYFRAME);
        pts += ape->blocksperframe;
    }

    /* try to read APE tags */
    if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
        ff_ape_parse_tag(s);
        avio_seek(pb, 0, SEEK_SET);
    }

    return 0;
}

static int ape_read_packet(AVFormatContext * s, AVPacket * pkt)
{
    int ret;
    int nblocks;
    APEContext *ape = s->priv_data;
    uint32_t extra_size = 8;
    int64_t ret64;

    if (avio_feof(s->pb))
        return AVERROR_EOF;
    if (ape->currentframe >= ape->totalframes)
        return AVERROR_EOF;

    ret64 = avio_seek(s->pb, ape->frames[ape->currentframe].pos, SEEK_SET);
    if (ret64 < 0)
        return ret64;

    /* Calculate how many blocks there are in this frame */
    if (ape->currentframe == (ape->totalframes - 1))
        nblocks = ape->finalframeblocks;
    else
        nblocks = ape->blocksperframe;

    if (ape->frames[ape->currentframe].size <= 0 ||
        ape->frames[ape->currentframe].size > INT_MAX - extra_size) {
        av_log(s, AV_LOG_ERROR, "invalid packet size: %d\n",
               ape->frames[ape->currentframe].size);
        ape->currentframe++;
        return AVERROR(EIO);
    }

    ret = av_new_packet(pkt, ape->frames[ape->currentframe].size + extra_size);
    if (ret < 0)
        return ret;

    AV_WL32(pkt->data    , nblocks);
    AV_WL32(pkt->data + 4, ape->frames[ape->currentframe].skip);
    ret = avio_read(s->pb, pkt->data + extra_size, ape->frames[ape->currentframe].size);
    if (ret < 0) {
        return ret;
    }

    pkt->pts = ape->frames[ape->currentframe].pts;
    pkt->stream_index = 0;

    /* note: we need to modify the packet size here to handle the last
       packet */
    pkt->size = ret + extra_size;

    ape->currentframe++;

    return 0;
}

static int ape_read_close(AVFormatContext * s)
{
    APEContext *ape = s->priv_data;

    av_freep(&ape->frames);
    av_freep(&ape->seektable);
    av_freep(&ape->bittable);
    return 0;
}

static int ape_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
{
    AVStream *st = s->streams[stream_index];
    APEContext *ape = s->priv_data;
    int index = av_index_search_timestamp(st, timestamp, flags);
    int64_t ret;

    if (index < 0)
        return -1;

    if ((ret = avio_seek(s->pb, st->index_entries[index].pos, SEEK_SET)) < 0)
        return ret;
    ape->currentframe = index;
    return 0;
}

AVInputFormat ff_ape_demuxer = {
    .name           = "ape",
    .long_name      = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
    .priv_data_size = sizeof(APEContext),
    .read_probe     = ape_probe,
    .read_header    = ape_read_header,
    .read_packet    = ape_read_packet,
    .read_close     = ape_read_close,
    .read_seek      = ape_read_seek,
    .extensions     = "ape,apl,mac",
};