text:
{% extends "base_sidebar.html" %}
{% load widget_tweaks %}

{%  block content %}

Change Password

        <form class="list-group-item" role="form" action="{% url 'password' %}" method="post">
            {% csrf_token %}

              {{ form.current_password|attr:"class:form-control"|attr:"placeholder:Enter Current Password" }}

              {{ form.new_password1|attr:"class:form-control"|attr:"placeholder:Enter New Password" }}

              {{ form.new_password2|attr:"class:form-control"|attr:"placeholder:Verify New Password" }}

            <input class="btn btn-success btn-lg" type="submit" value="Change Password" />
        </form>

    [ edit details ]
     [ cancel password change ]
{%  endblock %}

{% block sidekick %}
{% endblock sidekick %}


text:
//  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
//  This source code is licensed under both the GPLv2 (found in the
//  COPYING file in the root directory) and Apache 2.0 License
//  (found in the LICENSE.Apache file in the root directory).
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
//

#pragma once
#include <map>
#include <string>
#include <vector>

#include "db/version_set.h"

class ColumnFamilyData;

namespace rocksdb {

class DBImpl;
class MemTableList;

// Config for retrieving a property's value.
struct DBPropertyInfo {
  bool need_out_of_mutex;

  // gcc had an internal error for initializing union of pointer-to-member-
  // functions. Workaround is to populate exactly one of the following function
  // pointers with a non-nullptr value.

  // @param value Value-result argument for storing the property's string value
  // @param suffix Argument portion of the property. For example, suffix would
  //      be "5" for the property "rocksdb.num-files-at-level5". So far, only
  //      certain string properties take an argument.
  bool (InternalStats::*handle_string)(std::string* value, Slice suffix);

  // @param value Value-result argument for storing the property's uint64 value
  // @param db Many of the int properties rely on DBImpl methods.
  // @param version Version is needed in case the property is retrieved without
  //      holding db mutex, which is only supported for int properties.
  bool (InternalStats::*handle_int)(uint64_t* value, DBImpl* db,
                                    Version* version);

  // @param props Map of general properties to populate
  bool (InternalStats::*handle_map)(std::map<std::string, std::string>* props);

  // handle the string type properties rely on DBImpl methods
  // @param value Value-result argument for storing the property's string value
  bool (DBImpl::*handle_string_dbimpl)(std::string* value);
};

extern const DBPropertyInfo* GetPropertyInfo(const Slice& property);

#ifndef ROCKSDB_LITE
#undef SCORE
enum class LevelStatType {
  INVALID = 0,
  NUM_FILES,
  COMPACTED_FILES,
  SIZE_BYTES,
  SCORE,
  READ_GB,
  RN_GB,
  RNP1_GB,
  WRITE_GB,
  W_NEW_GB,
  MOVED_GB,
  WRITE_AMP,
  READ_MBPS,
  WRITE_MBPS,
  COMP_SEC,
  COMP_CPU_SEC,
  COMP_COUNT,
  AVG_SEC,
  KEY_IN,
  KEY_DROP,
  TOTAL  // total number of types
};

struct LevelStat {
  // This what will be L?.property_name in the flat map returned to the user
  std::string property_name;
  // This will be what we will print in the header in the cli
  std::string header_name;
};

class InternalStats {
 public:
  static const std::map<LevelStatType, LevelStat> compaction_level_stats;

  enum InternalCFStatsType {
    L0_FILE_COUNT_LIMIT_SLOWDOWNS,
    LOCKED_L0_FILE_COUNT_LIMIT_SLOWDOWNS,
    MEMTABLE_LIMIT_STOPS,
    MEMTABLE_LIMIT_SLOWDOWNS,
    L0_FILE_COUNT_LIMIT_STOPS,
    LOCKED_L0_FILE_COUNT_LIMIT_STOPS,
    PENDING_COMPACTION_BYTES_LIMIT_SLOWDOWNS,
    PENDING_COMPACTION_BYTES_LIMIT_STOPS,
    WRITE_STALLS_ENUM_MAX,
    BYTES_FLUSHED,
    BYTES_INGESTED_ADD_FILE,
    INGESTED_NUM_FILES_TOTAL,
    INGESTED_LEVEL0_NUM_FILES_TOTAL,
    INGESTED_NUM_KEYS_TOTAL,
    INTERNAL_CF_STATS_ENUM_MAX,
  };

  enum InternalDBStatsType {
    WAL_FILE_BYTES,
    WAL_FILE_SYNCED,
    BYTES_WRITTEN,
    NUMBER_KEYS_WRITTEN,
    WRITE_DONE_BY_OTHER,
    WRITE_DONE_BY_SELF,
    WRITE_WITH_WAL,
    WRITE_STALL_MICROS,
    INTERNAL_DB_STATS_ENUM_MAX,
  };

  InternalStats(int num_levels, Env* env, ColumnFamilyData* cfd)
      : db_stats_{},
        cf_stats_value_{},
        cf_stats_count_{},
        comp_stats_(num_levels),
        comp_stats_by_pri_(Env::Priority::TOTAL),
        file_read_latency_(num_levels),
        bg_error_count_(0),
        number_levels_(num_levels),
        env_(env),
        cfd_(cfd),
        started_at_(env->NowMicros()) {}

  // Per level compaction stats.  comp_stats_[level] stores the stats for
  // compactions that produced data for the specified "level".
  struct CompactionStats {
    uint64_t micros;
    uint64_t cpu_micros;

    // The number of bytes read from all non-output levels
    uint64_t bytes_read_non_output_levels;

    // The number of bytes read from the compaction output level.
    uint64_t bytes_read_output_level;

    // Total number of bytes written during compaction
    uint64_t bytes_written;

    // Total number of bytes moved to the output level
    uint64_t bytes_moved;

    // The number of compaction input files in all non-output levels.
    int num_input_files_in_non_output_levels;

    // The number of compaction input files in the output level.
    int num_input_files_in_output_level;

    // The number of compaction output files.
    int num_output_files;

    // Total incoming entries during compaction between levels N and N+1
    uint64_t num_input_records;

    // Accumulated diff number of entries
    // (num input entries - num output entires) for compaction  levels N and N+1
    uint64_t num_dropped_records;

    // Number of compactions done
    int count;

    // Number of compactions done per CompactionReason
    int counts[static_cast<int>(CompactionReason::kNumOfReasons)];

    explicit CompactionStats()
        : micros(0),
          cpu_micros(0),
          bytes_read_non_output_levels(0),
          bytes_read_output_level(0),
          bytes_written(0),
          bytes_moved(0),
          num_input_files_in_non_output_levels(0),
          num_input_files_in_output_level(0),
          num_output_files(0),
          num_input_records(0),
          num_dropped_records(0),
          count(0) {
      int num_of_reasons = static_cast<int>(CompactionReason::kNumOfReasons);
      for (int i = 0; i < num_of_reasons; i++) {
        counts[i] = 0;
      }
    }

    explicit CompactionStats(CompactionReason reason, int c)
        : micros(0),
          cpu_micros(0),
          bytes_read_non_output_levels(0),
          bytes_read_output_level(0),
          bytes_written(0),
          bytes_moved(0),
          num_input_files_in_non_output_levels(0),
          num_input_files_in_output_level(0),
          num_output_files(0),
          num_input_records(0),
          num_dropped_records(0),
          count(c) {
      int num_of_reasons = static_cast<int>(CompactionReason::kNumOfReasons);
      for (int i = 0; i < num_of_reasons; i++) {
        counts[i] = 0;
      }
      int r = static_cast<int>(reason);
      if (r >= 0 && r < num_of_reasons) {
        counts[r] = c;
      } else {
        count = 0;
      }
    }

    explicit CompactionStats(const CompactionStats& c)
        : micros(c.micros),
          cpu_micros(c.cpu_micros),
          bytes_read_non_output_levels(c.bytes_read_non_output_levels),
          bytes_read_output_level(c.bytes_read_output_level),
          bytes_written(c.bytes_written),
          bytes_moved(c.bytes_moved),
          num_input_files_in_non_output_levels(
              c.num_input_files_in_non_output_levels),
          num_input_files_in_output_level(c.num_input_files_in_output_level),
          num_output_files(c.num_output_files),
          num_input_records(c.num_input_records),
          num_dropped_records(c.num_dropped_records),
          count(c.count) {
      int num_of_reasons = static_cast<int>(CompactionReason::kNumOfReasons);
      for (int i = 0; i < num_of_reasons; i++) {
        counts[i] = c.counts[i];
      }
    }

    void Clear() {
      this->micros = 0;
      this->cpu_micros = 0;
      this->bytes_read_non_output_levels = 0;
      this->bytes_read_output_level = 0;
      this->bytes_written = 0;
      this->bytes_moved = 0;
      this->num_input_files_in_non_output_levels = 0;
      this->num_input_files_in_output_level = 0;
      this->num_output_files = 0;
      this->num_input_records = 0;
      this->num_dropped_records = 0;
      this->count = 0;
      int num_of_reasons = static_cast<int>(CompactionReason::kNumOfReasons);
      for (int i = 0; i < num_of_reasons; i++) {
        counts[i] = 0;
      }
    }

    void Add(const CompactionStats& c) {
      this->micros += c.micros;
      this->cpu_micros += c.cpu_micros;
      this->bytes_read_non_output_levels += c.bytes_read_non_output_levels;
      this->bytes_read_output_level += c.bytes_read_output_level;
      this->bytes_written += c.bytes_written;
      this->bytes_moved += c.bytes_moved;
      this->num_input_files_in_non_output_levels +=
          c.num_input_files_in_non_output_levels;
      this->num_input_files_in_output_level +=
          c.num_input_files_in_output_level;
      this->num_output_files += c.num_output_files;
      this->num_input_records += c.num_input_records;
      this->num_dropped_records += c.num_dropped_records;
      this->count += c.count;
      int num_of_reasons = static_cast<int>(CompactionReason::kNumOfReasons);
      for (int i = 0; i< num_of_reasons; i++) {
        counts[i] += c.counts[i];
      }
    }

    void Subtract(const CompactionStats& c) {
      this->micros -= c.micros;
      this->cpu_micros -= c.cpu_micros;
      this->bytes_read_non_output_levels -= c.bytes_read_non_output_levels;
      this->bytes_read_output_level -= c.bytes_read_output_level;
      this->bytes_written -= c.bytes_written;
      this->bytes_moved -= c.bytes_moved;
      this->num_input_files_in_non_output_levels -=
          c.num_input_files_in_non_output_levels;
      this->num_input_files_in_output_level -=
          c.num_input_files_in_output_level;
      this->num_output_files -= c.num_output_files;
      this->num_input_records -= c.num_input_records;
      this->num_dropped_records -= c.num_dropped_records;
      this->count -= c.count;
      int num_of_reasons = static_cast<int>(CompactionReason::kNumOfReasons);
      for (int i = 0; i < num_of_reasons; i++) {
        counts[i] -= c.counts[i];
      }
    }
  };

  void Clear() {
    for (int i = 0; i < INTERNAL_DB_STATS_ENUM_MAX; i++) {
      db_stats_[i].store(0);
    }
    for (int i = 0; i < INTERNAL_CF_STATS_ENUM_MAX; i++) {
      cf_stats_count_[i] = 0;
      cf_stats_value_[i] = 0;
    }
    for (auto& comp_stat : comp_stats_) {
      comp_stat.Clear();
    }
    for (auto& h : file_read_latency_) {
      h.Clear();
    }
    cf_stats_snapshot_.Clear();
    db_stats_snapshot_.Clear();
    bg_error_count_ = 0;
    started_at_ = env_->NowMicros();
  }

  void AddCompactionStats(int level, Env::Priority thread_pri,
                          const CompactionStats& stats) {
    comp_stats_[level].Add(stats);
    comp_stats_by_pri_[thread_pri].Add(stats);
  }

  void IncBytesMoved(int level, uint64_t amount) {
    comp_stats_[level].bytes_moved += amount;
  }

  void AddCFStats(InternalCFStatsType type, uint64_t value) {
    cf_stats_value_[type] += value;
    ++cf_stats_count_[type];
  }

  void AddDBStats(InternalDBStatsType type, uint64_t value,
                  bool concurrent = false) {
    auto& v = db_stats_[type];
    if (concurrent) {
      v.fetch_add(value, std::memory_order_relaxed);
    } else {
      v.store(v.load(std::memory_order_relaxed) + value,
              std::memory_order_relaxed);
    }
  }

  uint64_t GetDBStats(InternalDBStatsType type) {
    return db_stats_[type].load(std::memory_order_relaxed);
  }

  HistogramImpl* GetFileReadHist(int level) {
    return &file_read_latency_[level];
  }

  uint64_t GetBackgroundErrorCount() const { return bg_error_count_; }

  uint64_t BumpAndGetBackgroundErrorCount() { return ++bg_error_count_; }

  bool GetStringProperty(const DBPropertyInfo& property_info,
                         const Slice& property, std::string* value);

  bool GetMapProperty(const DBPropertyInfo& property_info,
                      const Slice& property,
                      std::map<std::string, std::string>* value);

  bool GetIntProperty(const DBPropertyInfo& property_info, uint64_t* value,
                      DBImpl* db);

  bool GetIntPropertyOutOfMutex(const DBPropertyInfo& property_info,
                                Version* version, uint64_t* value);

  const std::vector<CompactionStats>& TEST_GetCompactionStats() const {
    return comp_stats_;
  }

  // Store a mapping from the user-facing DB::Properties string to our
  // DBPropertyInfo struct used internally for retrieving properties.
  static const std::unordered_map<std::string, DBPropertyInfo> ppt_name_to_info;

 private:
  void DumpDBStats(std::string* value);
  void DumpCFMapStats(std::map<std::string, std::string>* cf_stats);
  void DumpCFMapStats(
      std::map<int, std::map<LevelStatType, double>>* level_stats,
      CompactionStats* compaction_stats_sum);
  void DumpCFMapStatsByPriority(
      std::map<int, std::map<LevelStatType, double>>* priorities_stats);
  void DumpCFMapStatsIOStalls(std::map<std::string, std::string>* cf_stats);
  void DumpCFStats(std::string* value);
  void DumpCFStatsNoFileHistogram(std::string* value);
  void DumpCFFileHistogram(std::string* value);

  bool HandleBlockCacheStat(Cache** block_cache);

  // Per-DB stats
  std::atomic<uint64_t> db_stats_[INTERNAL_DB_STATS_ENUM_MAX];
  // Per-ColumnFamily stats
  uint64_t cf_stats_value_[INTERNAL_CF_STATS_ENUM_MAX];
  uint64_t cf_stats_count_[INTERNAL_CF_STATS_ENUM_MAX];
  // Per-ColumnFamily/level compaction stats
  std::vector<CompactionStats> comp_stats_;
  std::vector<CompactionStats> comp_stats_by_pri_;
  std::vector<HistogramImpl> file_read_latency_;

  // Used to compute per-interval statistics
  struct CFStatsSnapshot {
    // ColumnFamily-level stats
    CompactionStats comp_stats;
    uint64_t ingest_bytes_flush;      // Bytes written to L0 (Flush)
    uint64_t stall_count;             // Stall count
    // Stats from compaction jobs - bytes written, bytes read, duration.
    uint64_t compact_bytes_write;
    uint64_t compact_bytes_read;
    uint64_t compact_micros;
    double seconds_up;

    // AddFile specific stats
    uint64_t ingest_bytes_addfile;     // Total Bytes ingested
    uint64_t ingest_files_addfile;     // Total number of files ingested
    uint64_t ingest_l0_files_addfile;  // Total number of files ingested to L0
    uint64_t ingest_keys_addfile;      // Total number of keys ingested

    CFStatsSnapshot()
        : ingest_bytes_flush(0),
          stall_count(0),
          compact_bytes_write(0),
          compact_bytes_read(0),
          compact_micros(0),
          seconds_up(0),
          ingest_bytes_addfile(0),
          ingest_files_addfile(0),
          ingest_l0_files_addfile(0),
          ingest_keys_addfile(0) {}

    void Clear() {
      comp_stats.Clear();
      ingest_bytes_flush = 0;
      stall_count = 0;
      compact_bytes_write = 0;
      compact_bytes_read = 0;
      compact_micros = 0;
      seconds_up = 0;
      ingest_bytes_addfile = 0;
      ingest_files_addfile = 0;
      ingest_l0_files_addfile = 0;
      ingest_keys_addfile = 0;
    }
  } cf_stats_snapshot_;

  struct DBStatsSnapshot {
    // DB-level stats
    uint64_t ingest_bytes;            // Bytes written by user
    uint64_t wal_bytes;               // Bytes written to WAL
    uint64_t wal_synced;              // Number of times WAL is synced
    uint64_t write_with_wal;          // Number of writes that request WAL
    // These count the number of writes processed by the calling thread or
    // another thread.
    uint64_t write_other;
    uint64_t write_self;
    // Total number of keys written. write_self and write_other measure number
    // of write requests written, Each of the write request can contain updates
    // to multiple keys. num_keys_written is total number of keys updated by all
    // those writes.
    uint64_t num_keys_written;
    // Total time writes delayed by stalls.
    uint64_t write_stall_micros;
    double seconds_up;

    DBStatsSnapshot()
        : ingest_bytes(0),
          wal_bytes(0),
          wal_synced(0),
          write_with_wal(0),
          write_other(0),
          write_self(0),
          num_keys_written(0),
          write_stall_micros(0),
          seconds_up(0) {}

    void Clear() {
      ingest_bytes = 0;
      wal_bytes = 0;
      wal_synced = 0;
      write_with_wal = 0;
      write_other = 0;
      write_self = 0;
      num_keys_written = 0;
      write_stall_micros = 0;
      seconds_up = 0;
    }
  } db_stats_snapshot_;

  // Handler functions for getting property values. They use "value" as a value-
  // result argument, and return true upon successfully setting "value".
  bool HandleNumFilesAtLevel(std::string* value, Slice suffix);
  bool HandleCompressionRatioAtLevelPrefix(std::string* value, Slice suffix);
  bool HandleLevelStats(std::string* value, Slice suffix);
  bool HandleStats(std::string* value, Slice suffix);
  bool HandleCFMapStats(std::map<std::string, std::string>* compaction_stats);
  bool HandleCFStats(std::string* value, Slice suffix);
  bool HandleCFStatsNoFileHistogram(std::string* value, Slice suffix);
  bool HandleCFFileHistogram(std::string* value, Slice suffix);
  bool HandleDBStats(std::string* value, Slice suffix);
  bool HandleSsTables(std::string* value, Slice suffix);
  bool HandleAggregatedTableProperties(std::string* value, Slice suffix);
  bool HandleAggregatedTablePropertiesAtLevel(std::string* value, Slice suffix);
  bool HandleNumImmutableMemTable(uint64_t* value, DBImpl* db,
                                  Version* version);
  bool HandleNumImmutableMemTableFlushed(uint64_t* value, DBImpl* db,
                                         Version* version);
  bool HandleMemTableFlushPending(uint64_t* value, DBImpl* db,
                                  Version* version);
  bool HandleNumRunningFlushes(uint64_t* value, DBImpl* db, Version* version);
  bool HandleCompactionPending(uint64_t* value, DBImpl* db, Version* version);
  bool HandleNumRunningCompactions(uint64_t* value, DBImpl* db,
                                   Version* version);
  bool HandleBackgroundErrors(uint64_t* value, DBImpl* db, Version* version);
  bool HandleCurSizeActiveMemTable(uint64_t* value, DBImpl* db,
                                   Version* version);
  bool HandleCurSizeAllMemTables(uint64_t* value, DBImpl* db, Version* version);
  bool HandleSizeAllMemTables(uint64_t* value, DBImpl* db, Version* version);
  bool HandleNumEntriesActiveMemTable(uint64_t* value, DBImpl* db,
                                      Version* version);
  bool HandleNumEntriesImmMemTables(uint64_t* value, DBImpl* db,
                                    Version* version);
  bool HandleNumDeletesActiveMemTable(uint64_t* value, DBImpl* db,
                                      Version* version);
  bool HandleNumDeletesImmMemTables(uint64_t* value, DBImpl* db,
                                    Version* version);
  bool HandleEstimateNumKeys(uint64_t* value, DBImpl* db, Version* version);
  bool HandleNumSnapshots(uint64_t* value, DBImpl* db, Version* version);
  bool HandleOldestSnapshotTime(uint64_t* value, DBImpl* db, Version* version);
  bool HandleNumLiveVersions(uint64_t* value, DBImpl* db, Version* version);
  bool HandleCurrentSuperVersionNumber(uint64_t* value, DBImpl* db,
                                       Version* version);
  bool HandleIsFileDeletionsEnabled(uint64_t* value, DBImpl* db,
                                    Version* version);
  bool HandleBaseLevel(uint64_t* value, DBImpl* db, Version* version);
  bool HandleTotalSstFilesSize(uint64_t* value, DBImpl* db, Version* version);
  bool HandleLiveSstFilesSize(uint64_t* value, DBImpl* db, Version* version);
  bool HandleEstimatePendingCompactionBytes(uint64_t* value, DBImpl* db,
                                            Version* version);
  bool HandleEstimateTableReadersMem(uint64_t* value, DBImpl* db,
                                     Version* version);
  bool HandleEstimateLiveDataSize(uint64_t* value, DBImpl* db,
                                  Version* version);
  bool HandleMinLogNumberToKeep(uint64_t* value, DBImpl* db, Version* version);
  bool HandleMinObsoleteSstNumberToKeep(uint64_t* value, DBImpl* db,
                                        Version* version);
  bool HandleActualDelayedWriteRate(uint64_t* value, DBImpl* db,
                                    Version* version);
  bool HandleIsWriteStopped(uint64_t* value, DBImpl* db, Version* version);
  bool HandleEstimateOldestKeyTime(uint64_t* value, DBImpl* db,
                                   Version* version);
  bool HandleBlockCacheCapacity(uint64_t* value, DBImpl* db, Version* version);
  bool HandleBlockCacheUsage(uint64_t* value, DBImpl* db, Version* version);
  bool HandleBlockCachePinnedUsage(uint64_t* value, DBImpl* db,
                                   Version* version);
  // Total number of background errors encountered. Every time a flush task
  // or compaction task fails, this counter is incremented. The failure can
  // be caused by any possible reason, including file system errors, out of
  // resources, or input file corruption. Failing when retrying the same flush
  // or compaction will cause the counter to increase too.
  uint64_t bg_error_count_;

  const int number_levels_;
  Env* env_;
  ColumnFamilyData* cfd_;
  uint64_t started_at_;
};

#else

class InternalStats {
 public:
  enum InternalCFStatsType {
    L0_FILE_COUNT_LIMIT_SLOWDOWNS,
    LOCKED_L0_FILE_COUNT_LIMIT_SLOWDOWNS,
    MEMTABLE_LIMIT_STOPS,
    MEMTABLE_LIMIT_SLOWDOWNS,
    L0_FILE_COUNT_LIMIT_STOPS,
    LOCKED_L0_FILE_COUNT_LIMIT_STOPS,
    PENDING_COMPACTION_BYTES_LIMIT_SLOWDOWNS,
    PENDING_COMPACTION_BYTES_LIMIT_STOPS,
    WRITE_STALLS_ENUM_MAX,
    BYTES_FLUSHED,
    BYTES_INGESTED_ADD_FILE,
    INGESTED_NUM_FILES_TOTAL,
    INGESTED_LEVEL0_NUM_FILES_TOTAL,
    INGESTED_NUM_KEYS_TOTAL,
    INTERNAL_CF_STATS_ENUM_MAX,
  };

  enum InternalDBStatsType {
    WAL_FILE_BYTES,
    WAL_FILE_SYNCED,
    BYTES_WRITTEN,
    NUMBER_KEYS_WRITTEN,
    WRITE_DONE_BY_OTHER,
    WRITE_DONE_BY_SELF,
    WRITE_WITH_WAL,
    WRITE_STALL_MICROS,
    INTERNAL_DB_STATS_ENUM_MAX,
  };

  InternalStats(int /*num_levels*/, Env* /*env*/, ColumnFamilyData* /*cfd*/) {}

  struct CompactionStats {
    uint64_t micros;
    uint64_t cpu_micros;
    uint64_t bytes_read_non_output_levels;
    uint64_t bytes_read_output_level;
    uint64_t bytes_written;
    uint64_t bytes_moved;
    int num_input_files_in_non_output_levels;
    int num_input_files_in_output_level;
    int num_output_files;
    uint64_t num_input_records;
    uint64_t num_dropped_records;
    int count;

    explicit CompactionStats() {}

    explicit CompactionStats(CompactionReason /*reason*/, int /*c*/) {}

    explicit CompactionStats(const CompactionStats& /*c*/) {}

    void Add(const CompactionStats& /*c*/) {}

    void Subtract(const CompactionStats& /*c*/) {}
  };

  void AddCompactionStats(int /*level*/, Env::Priority /*thread_pri*/,
                          const CompactionStats& /*stats*/) {}

  void IncBytesMoved(int /*level*/, uint64_t /*amount*/) {}

  void AddCFStats(InternalCFStatsType /*type*/, uint64_t /*value*/) {}

  void AddDBStats(InternalDBStatsType /*type*/, uint64_t /*value*/,
                  bool /*concurrent */ = false) {}

  HistogramImpl* GetFileReadHist(int /*level*/) { return nullptr; }

  uint64_t GetBackgroundErrorCount() const { return 0; }

  uint64_t BumpAndGetBackgroundErrorCount() { return 0; }

  bool GetStringProperty(const DBPropertyInfo& /*property_info*/,
                         const Slice& /*property*/, std::string* /*value*/) {
    return false;
  }

  bool GetMapProperty(const DBPropertyInfo& /*property_info*/,
                      const Slice& /*property*/,
                      std::map<std::string, std::string>* /*value*/) {
    return false;
  }

  bool GetIntProperty(const DBPropertyInfo& /*property_info*/, uint64_t* /*value*/,
                      DBImpl* /*db*/) const {
    return false;
  }

  bool GetIntPropertyOutOfMutex(const DBPropertyInfo& /*property_info*/,
                                Version* /*version*/, uint64_t* /*value*/) const {
    return false;
  }
};
#endif  // !ROCKSDB_LITE

}  // namespace rocksdb

redpajama_set_name: RedPajamaGithub


text:
from django.contrib import admin
from food.models import Recipe, Comment

class RecipeAdmin(admin.ModelAdmin):
    list_display = [
        'title',
    ]

class CommentAdmin(admin.ModelAdmin):
    list_display = [
        'user', 'recipe_id', 'date'
    ]

admin.site.register(Recipe, RecipeAdmin)
admin.site.register(Comment, CommentAdmin)


text:
<!DOCTYPE html>

    <title>Terms of Service</title>
    <meta charset="UTF-8"/>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui"/>
    <meta name="apple-mobile-web-app-capable" content="yes"/>
    <meta name="apple-touch-fullscreen" content="yes"/>
    <meta name="apple-mobile-web-app-status-bar-style" content="default"/>

    <meta name="theme-color" content="#673AB7">
    <meta name="msapplication-navbutton-color" content="#673AB7">
    <meta name="apple-mobile-web-app-status-bar-style" content="#673AB7">

    <link rel="shortcut icon" href="/img/icon.png" />

    <link th:href="@{/webjars/mui/packages/cdn/css/mui.min.css}" rel="stylesheet" type="text/css"/>

ZHCET Terms of Service

1. Terms

By accessing the website at http://zhcet.tk, you are agreeing to be bound by these terms of service, all applicable laws and regulations, and agree that you are responsible for compliance with any applicable local laws. If you do not agree with any of these terms, you are prohibited from using or accessing this site. The materials contained in this website are protected by applicable copyright and trademark law.

2. Use License

Permission is granted to temporarily download one copy of the materials (information or software) on ZHCET's website for personal, non-commercial transitory viewing only. This is the grant of a license, not a transfer of title, and under this license you may not:

modify or copy the materials;

use the materials for any commercial purpose, or for any public display (commercial or non-commercial);

attempt to decompile or reverse engineer any software contained on ZHCET's website;

remove any copyright or other proprietary notations from the materials; or

transfer the materials to another person or "mirror" the materials on any other server.

This license shall automatically terminate if you violate any of these restrictions and may be terminated by ZHCET at any time. Upon terminating your viewing of these materials or upon the termination of this license, you must destroy any downloaded materials in your possession whether in electronic or printed format.

3. Disclaimer

The materials on ZHCET's website are provided on an 'as is' basis. ZHCET makes no warranties, expressed or implied, and hereby disclaims and negates all other warranties including, without limitation, implied warranties or conditions of merchantability, fitness for a particular purpose, or non-infringement of intellectual property or other violation of rights.

Further, ZHCET does not warrant or make any representations concerning the accuracy, likely results, or reliability of the use of the materials on its website or otherwise relating to such materials or on any sites linked to this site.

4. Limitations

In no event shall ZHCET or its suppliers be liable for any damages (including, without limitation, damages for loss of data or profit, or due to business interruption) arising out of the use or inability to use the materials on ZHCET's website, even if ZHCET or a ZHCET authorized representative has been notified orally or in writing of the possibility of such damage. Because some jurisdictions do not allow limitations on implied warranties, or limitations of liability for consequential or incidental damages, these limitations may not apply to you.

5. Accuracy of materials

The materials appearing on ZHCET website could include technical, typographical, or photographic errors. ZHCET does not warrant that any of the materials on its website are accurate, complete or current. ZHCET may make changes to the materials contained on its website at any time without notice. However ZHCET does not make any commitment to update the materials.

6. Links

ZHCET has not reviewed all of the sites linked to its website and is not responsible for the contents of any such linked site. The inclusion of any link does not imply endorsement by ZHCET of the site. Use of any such linked website is at the user's own risk.

7. Modifications

ZHCET may revise these terms of service for its website at any time without notice. By using this website you are agreeing to be bound by the then current version of these terms of service.

8. Governing Law

These terms and conditions are governed by and construed in accordance with the laws of India and you irrevocably submit to the exclusive jurisdiction of the courts in that State or location.


text:
* Original: [Release electron v4.0.0-beta.10 - electron/electron](https://github.com/electron/electron/releases/tag/v4.0.0-beta.10)

Note: This is a beta release. Please file new issues for any bugs you find in it.

This release is published to npm under the beta tag and can be installed via `npm install electron@beta`, or `npm i electron@4.0.0-beta.10`.

> Note: これはベータ リリースです。なにかバグを見つけた場合は issue 報告してください。
>
> 本リリースは `beta` タグの [npm](https://www.npmjs.com/package/electron) として公開しており `npm install electron@beta` または `npm i electron@4.0.0-beta.10` でインストールできます。

## Fixes

* Added `--disable-color-correct-rendering` switch. [#16020](https://github.com/electron/electron/pull/16020)
  * `--disable-color-correct-rendering` スイッチを追加しました
  * Electron 2.0 では色補正において `--disable-features=ColorCorrectRendering` を指定すると sRGB ではなくディスプレイの色空間を使用していたが Chromium 62 以降で適切な設定が自動選択されるようになりオプションは無視されるようになった、この機能は旧来のオプション相当の機能を復活させたものとのこと、WebGL などで色補正が適切に扱われない問題への対策として暫定的に必要ということらしい
* Fixed 4-0-x regression that broke original-fs. [#16038](https://github.com/electron/electron/pull/16038)
  * original-fs をおかしくする 4.0.x の機能退行を修正しました
  * `createWriteStream` がエラーになる問題 ([#15543](https://github.com/electron/electron/issues/15543)) の修正
* Fixed `BrowserWindow.getNativeWindowHandle()` returning invalid handle. [#16022](https://github.com/electron/electron/pull/16022)
  * `BrowserWindow.getNativeWindowHandle()` が不正なハンドルを返す問題を修正しました
  * この API がウィンドウ単位の一意ではなく、どのウィンドウでもない不正な値を返す問題 ([#15911](https://github.com/electron/electron/issues/15911)) を修正
* Fixed cpu pegging on single-core windows. [#16012](https://github.com/electron/electron/pull/16012)
  * Windows のシングル コア環境における CPU ペギングを修正しました
  * この条件を満たす Windows で CPU 使用率が 100% になる問題などの修正
* Fixed crash with mouse wheel event monitor on app quit in macOS. [#16063](https://github.com/electron/electron/pull/16063)
  * macOS にてアプリケーション終了した際のマウス ホイールのイベント監視がクラッシュする問題を修正しました
  * イベント監視ハンドラーの寿命管理が不適切、ウィンドウ破棄時にハンドラーを削除することで修正
* Fixed several bugs related to printing. [#15976](https://github.com/electron/electron/pull/15976)
  * 印刷に関するいくつかのバグを修正しました
  * 複数ページにまたがるコンテンツを印刷すると最初のページだけが対象となる問題などを修正

## Other Changes

* In Electron 5.0, the default for nodeIntegration will change from true to false. Electron 4 will log a warning in the renderer when nodeIntegration is enabled by default. [#16004](https://github.com/electron/electron/pull/16004)
  * Electron 5.0 では nodeIntegration の既定値は true から false に変更されます、Electron 4 では nodeIntegration が標準で有効になっていると Renderer で警告をログ出力するようにしました
  * Electron 5 移行のための施策
* Upgraded sqlite from 3.24 to 3.26. [#16073](https://github.com/electron/electron/pull/16073)
  * SQLite を 3.24 から 3.26 へ更新しました
  * [「SQLite」データベースに脆弱性--「Chromium」ベースのブラウザにも影響 - ZDNet Japan](https://japan.zdnet.com/article/35130205/) の件に対する更新だろうか?
* Warn if you try to use Electron APIs from a non-electron environment. [#15977](https://github.com/electron/electron/pull/15977)
  * Electron ではない環境から Electron API を使用しようとすると警告するようにしました
  * Electron アプリ上ではなく Node.js から `electron` モジュールの機能を呼び出した場合に警告を表示するとのこと


text:
package me.chanjar.weixin.mp.bean.message;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamConverter;
import lombok.Data;
import lombok.EqualsAndHashCode;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.util.xml.XStreamCDataConverter;

@XStreamAlias("xml")
@Data
@EqualsAndHashCode(callSuper = true)
public class WxMpXmlOutTextMessage extends WxMpXmlOutMessage {
  private static final long serialVersionUID = -3972786455288763361L;

  @XStreamAlias("Content")
  @XStreamConverter(value = XStreamCDataConverter.class)
  private String content;

  public WxMpXmlOutTextMessage() {
    this.msgType = WxConsts.XmlMsgType.TEXT;
  }

}


text:
@interface WattpadPOSTError : NSObject
@property int httpCode;
@property int code;
@property NSString *type;
@property NSString *message;
@end


text:
module Sass
  module Tree
    class Node
      unless method_defined?(:visit_depth_first)
        def visit_depth_first(visitor)
          visitor.visit(self)
          visitor.down(self) if children.any? and visitor.respond_to?(:down)
          if is_a?(ImportNode) && visitor.import?(self)
            root = Sass::Engine.for_file(import, @options).to_tree
            imported_children = root.children
          end

          (imported_children || children).each do |child|
            break if visitor.respond_to?(:stop?) && visitor.stop?
            child.visit_depth_first(visitor)
          end
          visitor.up(self) if children.any?
        end
      end
    end
  end
end


text:
angular.module('app').controller("LoginController",
  ['$location', '$scope', 'AuthService', 'urlToGoToAfterLogin',
  function ($location, $scope, AuthService, urlToGoToAfterLogin) {
    if(AuthService.isLoggedIn()){
      return $location.path('/');
    }
      // Hide the ui-view blur background
      $scope.hideBackground = false;

    $scope.login = function () {
      var credentials = {
        user: {
          email: $scope.email,
          password: $scope.password,
          rememberme: $scope.rememberme
        }
      };

      AuthService.login(credentials,
        function(res) {
          $scope.user.isLoggedIn = true;
          // Set username on the parent scope as this
          // is displayed in the main app controller on load.
          $scope.$parent.userName = res.username;
          $location.path(urlToGoToAfterLogin.url);
          urlToGoToAfterLogin.url = '/';
        },
        function(err) {
          $scope.errors = [err];
        }
      );
    }
    $scope.events = [
      {title: 'All Day Event',start: new Date()},
      {title: 'Long Event',start: new Date(),end: new Date()},
      {id: 999,title: 'Repeating Event',start: new Date(),allDay: false}
    ];
    $scope.eventSources = [
      $scope.events
    ];
}]);


text:
package org.moe.gradle.tasks;

import org.gradle.api.GradleException;
import org.gradle.api.logging.LogLevel;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputDirectory;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.Optional;
import org.gradle.api.tasks.OutputFile;
import org.gradle.api.tasks.SourceSet;
import org.moe.document.pbxproj.*;
import org.moe.document.pbxproj.nextstep.NextStep;
import org.moe.document.pbxproj.nextstep.Value;
import org.moe.gradle.MoeExtension;
import org.moe.gradle.MoePlugin;
import org.moe.gradle.anns.IgnoreUnused;
import org.moe.gradle.anns.NotNull;
import org.moe.gradle.anns.Nullable;
import org.moe.gradle.remote.Server;
import org.moe.gradle.remote.file.FileList;
import org.moe.gradle.utils.Arch;
import org.moe.gradle.utils.ExportOptionsPlistManager;
import org.moe.gradle.utils.Mode;
import org.moe.gradle.utils.Require;
import org.moe.gradle.utils.TaskUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

public class IpaBuild extends AbstractBaseTask {

    private static final Logger LOG = Logging.getLogger(IpaBuild.class);

    private static final String CONVENTION_INPUT_APP = "inputApp";
    private static final String CONVENTION_OUTPUT_IPA = "outputIpa";
    private static final String CONVENTION_TARGET = "target";
    private static final String CONVENTION_SCHEME = "scheme";
    private static final String CONVENTION_XCODE_PROJECT_FILE = "xcodeProjectFile";
    private static final String CONVENTION_XCODE_WORKSPACE_FILE = "xcodeWorkspaceFile";
    private static final String CONVENTION_EXPORT_METHOD = "exportMethod";
    private static final String CONVENTION_CONFIGURATION = "configuration";
    private static final String CONVENTION_OUTPUT_ARCHIVE = "outputArchive";
    private static final String CONVENTION_DEVELOPMENT_TEAM = "developmentTeam";
    private static final String CONVENTION_ADDITIONAL_PARAMETERS = "additionalParameters";
    private static final String CONVENTION_EXPORT_INFO_PLIST = "exportInfoPlist";
    private static final String CONVENTION_EXPORT_UPLOAD_SYMBOLS = "exportUploadSymbols";
    private static final String CONVENTION_EXPORT_UPLOAD_BITCODE = "exportUploadBitcode";
    private static final String CONVENTION_EXPORT_COMPILE_BITCODE = "exportCompileBitcode";
    private static final String CONVENTION_EXPORT_ICLOUD = "iCloudContainerEnvironment";
    private static final String CONVENTION_EXPORT_DEMAND_RESOURCES_BASE_URL = "onDemandResourcesAssetPacksBaseURL";
    private static final String CONVENTION_EXPORT_DEMAND_RESOURCES_IN_BUNDLE = "embedOnDemandResourcesAssetPacksInBundle";
    private static final String CONVENTION_THINNING = "thinning";
    private static final String CONVENTION_APP_URL = "appURL";
    private static final String CONVENTION_DISPLAY_IMAGE_URL = "displayImageURL";
    private static final String CONVENTION_FULL_SIZE_IMAGE_URL = "fullSizeImageURL";
    private static final String CONVENTION_USER_PLIST_FILE = "userPlistFile";
    private static final String CONVENTION_USER_EXPORT_PLIST = "userExportPlist";
    private static final String CONVENTION_BUNDLE_IDENTIFIER = "bundleIdentifier";
    private static final String CONVENTION_PROVISIONING_PROFILE_SPECIFIER = "provisioningProfileSpecifier";
    private static final String CONVENTION_PROVISIONING_PROFILE = "provisioningProfile";
    private static final String CONVENTION_SIGNING_IDENTITY = "signingIdentity";

    public static final String BUNDLE_IDENTIFIER_KEY = "PRODUCT_BUNDLE_IDENTIFIER";

    @Nullable
    private Object inputApp;

    @InputDirectory
    @Optional
    @Nullable
    public File getInputApp() {
        final Object inputApp = nullableGetOrConvention(this.inputApp, CONVENTION_INPUT_APP);
        if (inputApp == null) {
            return null;
        }
        return getProject().file(inputApp);
    }

    @IgnoreUnused
    public void setInputApp(@Nullable Object inputApp) {
        this.inputApp = inputApp;
    }

    @Nullable
    private Object outputIpa;

    @OutputFile
    @NotNull
    public File getOutputIpa() {
        return getProject().file(getOrConvention(outputIpa, CONVENTION_OUTPUT_IPA));
    }

    @IgnoreUnused
    public void setOutputIpa(@Nullable Object outputIpa) {
        this.outputIpa = outputIpa;
    }

    @NotNull
    private final String ipaBuildTaskDate = new Date().toString();

    @Input
    @NotNull
    @IgnoreUnused
    public String getIpaBuildTaskDate() {
        // NOTE: never allow Gradle to skip this task due to incremental build!!!
        return ipaBuildTaskDate;
    }

    @Nullable
    private String bundleIdentifier;

    @Input
    @NotNull
    public String getBundleIdentifier() {
        return nullableGetOrConvention(bundleIdentifier, CONVENTION_BUNDLE_IDENTIFIER);
    }

    @IgnoreUnused
    public void setBundleIdentifier(@Nullable String bundleIdentifier) {
        this.bundleIdentifier = bundleIdentifier;
    }

    @Nullable
    private String scheme;

    @Input
    @Optional
    @Nullable
    public String getScheme() {
        return nullableGetOrConvention(scheme, CONVENTION_SCHEME);
    }

    @IgnoreUnused
    public void setScheme(@Nullable String scheme) {
        this.scheme = scheme;
    }

    @Nullable
    private Object xcodeProjectFile;

    @InputDirectory
    @NotNull
    public File getXcodeProjectFile() {
        return getProject().file(getOrConvention(xcodeProjectFile, CONVENTION_XCODE_PROJECT_FILE));
    }

    @IgnoreUnused
    public void setXcodeProjectFile(@Nullable Object xcodeProjectFile) {
        this.xcodeProjectFile = xcodeProjectFile;
    }

    @Nullable
    private Object xcodeWorkspaceFile;

    @InputDirectory
    @Optional
    @Nullable
    public File getXcodeWorkspaceFile() {
        final Object object = nullableGetOrConvention(xcodeWorkspaceFile, CONVENTION_XCODE_WORKSPACE_FILE);
        if (object == null) {
            return null;
        }
        return getProject().file(object);
    }

    @IgnoreUnused
    public void setXcodeWorkspaceFile(@Nullable Object xcodeWorkspaceFile) {
        this.xcodeWorkspaceFile = xcodeWorkspaceFile;
    }

    @Nullable
    private String exportMethod;

    @Input
    @Optional
    @Nullable
    public String getExportMethod() {
        return nullableGetOrConvention(exportMethod, CONVENTION_EXPORT_METHOD);
    }

    @IgnoreUnused
    public void setExportMethod(@Nullable String exportMethod) {
        this.exportMethod = exportMethod;
    }

    @Nullable
    private String configuration;

    @Input
    @NotNull
    public String getConfiguration() {
        return getOrConvention(configuration, CONVENTION_CONFIGURATION);
    }

    @IgnoreUnused
    public void setConfiguration(@Nullable String configuration) {
        this.configuration = configuration;
    }

    @Nullable
    private Object outputArchive;

    @OutputFile
    @NotNull
    public File getOutputArchive() {
        return getProject().file(getOrConvention(outputArchive, CONVENTION_OUTPUT_ARCHIVE));
    }

    @IgnoreUnused
    public void setOutputArchive(@Nullable Object outputArchive) {
        this.outputArchive = outputArchive;
    }

    @Nullable
    private String developmentTeam;

    @Input
    @Optional
    @Nullable
    public String getDevelopmentTeam() {
        return nullableGetOrConvention(developmentTeam, CONVENTION_DEVELOPMENT_TEAM);
    }

    @IgnoreUnused
    public void setDevelopmentTeam(@Nullable String developmentTeam) {
        this.developmentTeam = developmentTeam;
    }

    @Nullable
    private List<String> additionalParameters;

    @Input
    @NotNull
    public List<String> getAdditionalParameters() {
        return getOrConvention(additionalParameters, CONVENTION_ADDITIONAL_PARAMETERS);
    }

    @IgnoreUnused
    public void setAdditionalParameters(@NotNull List<String> additionalParameters) {
        this.additionalParameters = additionalParameters == null ? null : new ArrayList<>(additionalParameters);
    }

    @Nullable
    private Object exportOptionsPlist;

    @OutputFile
    @NotNull
    public File getExportOptionsPlist() {
        return getProject().file(getOrConvention(exportOptionsPlist, CONVENTION_EXPORT_INFO_PLIST));
    }

    @IgnoreUnused
    public void setExportOptionsPlist(@Nullable Object exportOptionsPlist) {
        this.exportOptionsPlist = exportOptionsPlist;
    }

    @NotNull
    private boolean userExportPlist;

    @Input
    @NotNull
    public boolean isUserExportPlist() {
        return getOrConvention(userExportPlist, CONVENTION_USER_PLIST_FILE);
    }

    @IgnoreUnused
    public void setUserExportPlist(@Nullable boolean userExportPlist) {
        this.userExportPlist = userExportPlist;
    }

    @NotNull
    private boolean uploadBitcode;

    @Input
    @NotNull
    public boolean getUploadBitcode() {
        return getOrConvention(uploadBitcode, CONVENTION_EXPORT_UPLOAD_BITCODE);
    }

    @IgnoreUnused
    public void setUploadBitcode(@Nullable boolean uploadBitcode) {
        this.uploadBitcode = uploadBitcode;
    }

    @NotNull
    private boolean compileBitCode;

    @Input
    @NotNull
    public boolean getCompileBitcode() {
        return getOrConvention(compileBitCode, CONVENTION_EXPORT_COMPILE_BITCODE);
    }

    @IgnoreUnused
    public void setCompileBitCode(@Nullable boolean compileBitCode) {
        this.compileBitCode = compileBitCode;
    }

    @NotNull
    private boolean embedOnDemandResourcesAssetPacksInBundle;

    @Input
    @NotNull
    public boolean getEmbedOnDemandResourcesAssetPacksInBundle() {
        return nullableGetOrConvention(embedOnDemandResourcesAssetPacksInBundle, CONVENTION_EXPORT_DEMAND_RESOURCES_IN_BUNDLE);
    }

    @IgnoreUnused
    public void setEmbedOnDemandResourcesAssetPacksInBundle(boolean embedOnDemandResourcesAssetPacksInBundle) {
        this.embedOnDemandResourcesAssetPacksInBundle = embedOnDemandResourcesAssetPacksInBundle;
    }

    @Nullable
    private String iCloudContainerEnvironment;

    @Nullable
    @Input
    @Optional
    public String getICloudContainerEnvironment() {
        return nullableGetOrConvention(iCloudContainerEnvironment, CONVENTION_EXPORT_ICLOUD);
    }

    @IgnoreUnused
    public void setICloudContainerEnvironment(String iCloudContainerEnvironment) {
        this.iCloudContainerEnvironment = iCloudContainerEnvironment;
    }

    @Nullable
    private String onDemandResourcesAssetPacksBaseURL;

    @Input
    @Optional
    @Nullable
    public String getOnDemandResourcesAssetPacksBaseURL() {
        return nullableGetOrConvention(onDemandResourcesAssetPacksBaseURL, CONVENTION_EXPORT_DEMAND_RESOURCES_BASE_URL);
    }

    @IgnoreUnused
    public void setOnDemandResourcesAssetPacksBaseURL(String onDemandResourcesAssetPacksBaseURL) {
        this.onDemandResourcesAssetPacksBaseURL = onDemandResourcesAssetPacksBaseURL;
    }

    @Nullable
    private String thinning;

    @Input
    @Optional
    @Nullable
    public String getThinning() {
        return nullableGetOrConvention(thinning, CONVENTION_THINNING);
    }

    @IgnoreUnused
    public void setThinning(String thinning) {
        this.thinning = thinning;
    }

    @Nullable
    private String appURL;

    @Input
    @Optional
    public String getAppURL() {
        return nullableGetOrConvention(appURL, CONVENTION_APP_URL);
    }

    @IgnoreUnused
    public void setAppURL(String appURL) {
        this.appURL = appURL;
    }

    @Nullable
    private String displayImageURL;

    @Input
    @Optional
    @Nullable
    public String getDisplayImageURL() {
        return nullableGetOrConvention(displayImageURL, CONVENTION_DISPLAY_IMAGE_URL);
    }

    @IgnoreUnused
    public void setDisplayImageURL(String displayImageURL) {
        this.displayImageURL = displayImageURL;
    }

    @Nullable
    private String fullSizeImageURL;

    @Input
    @Optional
    @Nullable
    public String getFullSizeImageURL() {
        return nullableGetOrConvention(fullSizeImageURL, CONVENTION_FULL_SIZE_IMAGE_URL);
    }

    @IgnoreUnused
    public void setFullSizeImageURL(String fullSizeImageURL) {
        this.fullSizeImageURL = fullSizeImageURL;
    }

    @Nullable
    private String plistFile;

    @Input
    @Optional
    @Nullable
    public String getPlistFile() {
        return nullableGetOrConvention(plistFile, CONVENTION_USER_PLIST_FILE);
    }

    @IgnoreUnused
    public void setPlistFile(String plistFile) {
        this.plistFile = plistFile;
    }

    @NotNull
    private boolean uploadSymbols;

    @Input
    @NotNull
    public boolean getUploadSymbols() {
        return getOrConvention(uploadSymbols, CONVENTION_EXPORT_UPLOAD_SYMBOLS);
    }

    @IgnoreUnused
    public void setUploadSymbols(@Nullable boolean uploadSymbols) {
        this.uploadSymbols = uploadSymbols;
    }

    @Nullable
    private String provisioningProfileSpecifier;

    @Input
    @Optional
    public String getProvisioningProfileSpecifier() {
        return nullableGetOrConvention(provisioningProfileSpecifier, CONVENTION_PROVISIONING_PROFILE_SPECIFIER);
    }

    @IgnoreUnused
    public void setProvisioningProfileSpecifier(@Nullable String provisioningProfileSpecifier) {
        this.provisioningProfileSpecifier = provisioningProfileSpecifier;
    }

    @Nullable
    private String provisioningProfile;

    @Input
    @Optional
    public String getProvisioningProfile() {
        return nullableGetOrConvention(provisioningProfile, CONVENTION_PROVISIONING_PROFILE);
    }

    @IgnoreUnused
    public void setProvisioningProfile(@Nullable String provisioningProfile) {
        this.provisioningProfileSpecifier = provisioningProfile;
    }

    @Nullable
    private String signingIdentity;

    @Input
    @Optional
    @Nullable
    public String getSigningIdentity() {
        return nullableGetOrConvention(signingIdentity, CONVENTION_SIGNING_IDENTITY);
    }

    @IgnoreUnused
    public void setSigningIdentity(@Nullable String signingIdentity) {
        this.signingIdentity = signingIdentity;
    }

    @Nullable
    private String target;

    @Input
    @NotNull
    public String getTarget() {
        return getOrConvention(target, CONVENTION_TARGET);
    }

    @IgnoreUnused
    public void setTarget(@Nullable String target) {
        this.target = target;
    }

    @Override
    protected void run() {
        getMoePlugin().requireMacHostOrRemoteServerConfig(this);

        if (getScheme() == null) {
            throw new GradleException("IPA build requires schemes! Please set the "
                    + "moe.xcode.mainScheme property");
        }

        if (getDevelopmentTeam() == null) {
            throw new GradleException("IPA build requires signing developmentTeam! Please set the "
                    + "moe.signing.developmentTeam property");
        }

        final Server remoteServer = getMoePlugin().getRemoteServer();
        final File inputApp = Require.nonNull(getInputApp());

        if (!isUserExportPlist()) {
            generateExportOptionsPlist();
        } else {
            LOG.warn("Ipa export option plist is defined, ignore all other settings");
        }

        if (remoteServer != null) {
            final Path ipaRel;
            try {
                ipaRel = getInnerProjectRelativePath(getOutputIpa());
            } catch (IOException e) {
                throw new GradleException("Unsupported configuration", e);
            }
            final String remoteIpa = remoteServer.getRemotePath(ipaRel);

            // Upload ipa export options
            final FileList list = new FileList(getProject().getProjectDir(), remoteServer.getBuildDir());
            list.add(getExportOptionsPlist());

            remoteServer.upload("Upload export options", list);

            remoteServer.exec("remove previous ipa", "rm -rf " + remoteIpa);

            remoteServer.exec("archive", "xcrun xcodebuild " +
                    calculateArchiveArgs().stream().collect(Collectors.joining(" ")));

            remoteServer.exec("export archive", "xcrun xcodebuild " +
                    calculateExportArchiveArgs().stream().collect(Collectors.joining(" ")));

            remoteServer.downloadFile("ipa file", remoteIpa, getOutputIpa().getParentFile());

        } else {
            exec(spec -> {
                // Set executable
                spec.setExecutable("xcrun");
                spec.args("xcodebuild");
                spec.args(calculateArchiveArgs());

            });

            exec(spec -> {
                // Set executable
                spec.setExecutable("xcrun");
                spec.args("xcodebuild");
                spec.args(calculateExportArchiveArgs());
            });
        }
    }

    private XcodeBuild xcodeBuildTaskDep;

    @NotNull
    @IgnoreUnused
    @Internal
    public XcodeBuild getXcodeBuildTaskDep() {
        return Require.nonNull(xcodeBuildTaskDep);
    }

    protected final void setupMoeTask() {
        setSupportsRemoteBuild(true);

        final MoeExtension ext = getMoeExtension();

        // Construct default output path
        final Path out = Paths.get(MoePlugin.MOE);

        setDescription("Builds .ipa file.");

        // Add dependencies
        final XcodeBuild xcodeBuildTask = getMoePlugin().getTaskBy(XcodeBuild.class,
                TaskUtils.getSourceSet(getMoePlugin(), SourceSet.MAIN_SOURCE_SET_NAME),
                Mode.RELEASE,
                ext.getPlatformType());
        xcodeBuildTaskDep = xcodeBuildTask;
        dependsOn(xcodeBuildTask);

        // Update convention mapping
        addConvention(CONVENTION_INPUT_APP, () -> {
            final Map<String, String> buildSettings = xcodeBuildTask.getNullableXcodeBuildSettings();
            if (buildSettings == null) {
                return null;
            }
            final String sym = xcodeBuildTask.getConfigurationBuildDir().getAbsolutePath();
            final String productName = buildSettings.get("PRODUCT_NAME");
            return Paths.get(sym, productName + ".app").toFile();
        });
        addConvention(CONVENTION_OUTPUT_IPA, () -> {
            final Map<String, String> buildSettings = xcodeBuildTask.getXcodeBuildSettings();
            final String productName = buildSettings.get("PRODUCT_NAME");
            return resolvePathInBuildDir(productName + ".ipa");
        });
        // Update convention mapping
        addConvention(CONVENTION_TARGET, () -> {
            return ext.xcode.getMainTarget();
        });
        addConvention(CONVENTION_SCHEME, () -> {
            return ext.xcode.getMainScheme();
        });
        addConvention(CONVENTION_XCODE_PROJECT_FILE, () ->
                resolvePathRelativeToRoot(getProject().file(ext.xcode.getProject())));
        addConvention(CONVENTION_XCODE_WORKSPACE_FILE, () -> {
            final Object workspace = ext.xcode.getWorkspace();
            if (workspace == null) {
                return null;
            }
            return resolvePathRelativeToRoot(getProject().file(workspace));
        });
        addConvention(CONVENTION_BUNDLE_IDENTIFIER, () -> {
            final Map<String, String> buildSettings = xcodeBuildTask.getNullableXcodeBuildSettings();
            if (buildSettings == null) {
                return null;
            }
            final String bundleIdentifier = buildSettings.get(BUNDLE_IDENTIFIER_KEY);
            return bundleIdentifier;
        });

        addConvention(CONVENTION_EXPORT_METHOD, ext.ipaExport::getMethod);
        setUploadBitcode(ext.ipaExport.getUploadBitcode());
        setUploadSymbols(ext.ipaExport.getUploadSymbols());
        setCompileBitCode(ext.ipaExport.getCompileBitcode());
        setEmbedOnDemandResourcesAssetPacksInBundle(ext.ipaExport.getEmbedOnDemandResourcesAssetPacksInBundle());
        addConvention(CONVENTION_EXPORT_ICLOUD, ext.ipaExport::getICloudContainerEnvironment);
        addConvention(CONVENTION_EXPORT_DEMAND_RESOURCES_BASE_URL, ext.ipaExport::getOnDemandResourcesAssetPacksBaseURL);
        addConvention(CONVENTION_EXPORT_DEMAND_RESOURCES_IN_BUNDLE, ext.ipaExport::getEmbedOnDemandResourcesAssetPacksInBundle);
        addConvention(CONVENTION_THINNING, ext.ipaExport::getThinning);
        addConvention(CONVENTION_APP_URL, ext.ipaExport::getAppURL);
        addConvention(CONVENTION_DISPLAY_IMAGE_URL, ext.ipaExport::getDisplayImageURL);
        addConvention(CONVENTION_FULL_SIZE_IMAGE_URL, ext.ipaExport::getFullSizeImageURL);
        addConvention(CONVENTION_USER_PLIST_FILE, ext.ipaExport::getPlistFile);
        if (!ext.ipaExport.isUserDefinedExportPlist()) {
            setUserExportPlist(false);
            addConvention(CONVENTION_EXPORT_INFO_PLIST, () -> resolvePathInBuildDir(out, "export_options.plist"));
        } else {
            setUserExportPlist(true);
            addConvention(CONVENTION_EXPORT_INFO_PLIST, () -> resolvePathInProjectDir(ext.ipaExport.getPlistFile()));
        }

        addConvention(CONVENTION_CONFIGURATION, Mode.RELEASE::getXcodeCompatibleName);
        addConvention(CONVENTION_OUTPUT_ARCHIVE, () -> {
            return resolvePathInBuildDir("archive");
        });
        addConvention(CONVENTION_DEVELOPMENT_TEAM, () -> {
            String xcodeprojDevelopmentTeam = getXcodeprojDevelopmentTeam();
            if (!ext.signing.usesDefaultDevelopmentTeam()) {
                return ext.signing.getDevelopmentTeam();
            } else if (ext.signing.getDevelopmentTeam() != null) {
                return ext.signing.getDevelopmentTeam();
            } else {
                return xcodeprojDevelopmentTeam;
            }
        });
        addConvention(CONVENTION_ADDITIONAL_PARAMETERS, () ->
                new ArrayList<>(Arrays.asList("MOE_GRADLE_EXTERNAL_BUILD=YES", "ONLY_ACTIVE_ARCH=NO")));
        addConvention(CONVENTION_PROVISIONING_PROFILE, ext.signing::getProvisioningProfile);
        addConvention(CONVENTION_PROVISIONING_PROFILE_SPECIFIER, ext.signing::getProvisioningProfileSpecifier);
        addConvention(CONVENTION_SIGNING_IDENTITY, ext.signing::getSigningIdentity);
        addConvention(CONVENTION_LOG_FILE, () -> resolvePathInBuildDir(out, "IpaBuild.log"));
    }

    private List<String> calculateArchiveArgs() {
        final List<String> args = new ArrayList<>();
        final Server remoteServer = getMoePlugin().getRemoteServer();

        args.add("archive");

        final String _xcodeProjectFile;
        final String _xcodeWorkspaceFile;
        final String _archiveFile;

        if (remoteServer != null) {
            final Path xcodeProjectFileRel;
            final Path xcodeWorkspaceFileRel;
            final Path archiveFileRel;
            try {
                xcodeProjectFileRel = getInnerProjectRelativePath(getXcodeProjectFile());
                if (getXcodeWorkspaceFile() != null) {
                    xcodeWorkspaceFileRel = getInnerProjectRelativePath(getXcodeWorkspaceFile());
                } else {
                    xcodeWorkspaceFileRel = null;
                }
                archiveFileRel = getInnerProjectRelativePath(getOutputArchive());
            } catch (IOException e) {
                throw new GradleException("Unsupported configuration", e);
            }
            _xcodeProjectFile = remoteServer.getRemotePath(xcodeProjectFileRel);
            if (xcodeWorkspaceFileRel != null) {
                _xcodeWorkspaceFile = remoteServer.getRemotePath(xcodeWorkspaceFileRel);
            } else {
                _xcodeWorkspaceFile = null;
            }
            _archiveFile = remoteServer.getRemotePath(archiveFileRel);

        } else {
            _xcodeProjectFile = getXcodeProjectFile().getAbsolutePath();
            if (getXcodeWorkspaceFile() != null) {
                _xcodeWorkspaceFile = getXcodeWorkspaceFile().getAbsolutePath();
            } else {
                _xcodeWorkspaceFile = null;
            }
            _archiveFile = getOutputArchive().getAbsolutePath();
        }

        if (_xcodeWorkspaceFile != null) {
            args.add("-workspace");
            args.add(_xcodeWorkspaceFile);

            args.add("-scheme");
            args.add(getScheme());
        } else {
            args.add("-project");
            args.add(_xcodeProjectFile);

            final String scheme = getScheme();
            if (scheme != null) {
                args.add("-scheme");
                args.add(scheme);
            } else {
                args.add("-target");
                args.add(getTarget());
            }
        }

        args.addAll(getAdditionalParameters());

        Set<Arch> archs = getXcodeBuildTaskDep().getArchs();
        if (archs != null) {
            args.add("ARCHS=" + archs.stream().map(it -> it.name).collect(Collectors.joining(" ")));
        }

        args.add("DEVELOPMENT_TEAM=" + getDevelopmentTeam());

        args.add("-configuration");
        args.add(getConfiguration());

        args.add("-archivePath");
        args.add(_archiveFile);

        String provProf = getProvisioningProfile();
        if (provProf != null && !provProf.isEmpty()) {
            args.add("PROVISIONING_PROFILE=" + provProf);
        }

        String signingId = getSigningIdentity();
        if(signingId != null && !signingId.isEmpty()) {
            args.add("CODE_SIGN_IDENTITY=" + signingId);
        }

        return args;
    }

    private List<String> calculateExportArchiveArgs() {
        final List<String> args = new ArrayList<>();
        final Server remoteServer = getMoePlugin().getRemoteServer();

        final String _archiveFile;
        final String _ipaFile;
        final String _optionsPlistFile;

        if (remoteServer != null) {
            final Path archiveFileRel;
            final Path ipaFileRel;
            final Path optionsPlistFileRel;
            try {
                ipaFileRel = getInnerProjectRelativePath(getOutputIpa().getParentFile());
                archiveFileRel = getInnerProjectRelativePath(resolvePathInBuildDir("archive.xcarchive"));
                optionsPlistFileRel = getInnerProjectRelativePath(getExportOptionsPlist());
            } catch (IOException e) {
                throw new GradleException("Unsupported configuration", e);
            }
            _ipaFile = remoteServer.getRemotePath(ipaFileRel);
            _archiveFile = remoteServer.getRemotePath(archiveFileRel);
            _optionsPlistFile = remoteServer.getRemotePath(optionsPlistFileRel);
        } else {
            _ipaFile = getOutputIpa().getParent();
            _archiveFile = resolvePathInBuildDir("archive.xcarchive").getAbsolutePath();
            _optionsPlistFile = getExportOptionsPlist().getAbsolutePath();
        }

        args.add("-exportArchive");
        args.add("-archivePath");
        args.add(_archiveFile);
        args.add("-exportPath");
        args.add(_ipaFile);
        args.add("-exportOptionsPlist");
        args.add(_optionsPlistFile);

        return args;
    }

    private String getXcodeprojDevelopmentTeam() {
        try {
            // Open Xcode project
            final File xcodeproj = Require.nonNull(getXcodeProjectFile());
            final ProjectFile project = new ProjectFile(xcodeproj);
            final String target = Require.nonNull(getTarget());

            // Search for target with name
            final java.util.Optional<Map.Entry<PBXObjectRef<? extends PBXObject>, PBXObject>> optional = project.getRoot()
                    .getObjects().entrySet().stream()
                    .filter(field -> field.getValue() instanceof PBXNativeTarget && ((PBXNativeTarget)field.getKey()
                            .getReferenced()).getName().equals(target)).findFirst();
            Require.TRUE(optional.isPresent(),
                    "Target with name '" + target + "' doesn't exist in Xcode project at " + xcodeproj
                            .getAbsolutePath());
            PBXNativeTarget nTarget = (PBXNativeTarget)optional.get().getValue();

            // Search for build configuration with name
            XCConfigurationList xcConfigurationList = nTarget.getBuildConfigurationList().getReferenced();
            for (PBXObjectRef<XCBuildConfiguration> ref : xcConfigurationList.getOrCreateBuildConfigurations()) {
                XCBuildConfiguration xcBuildConfiguration = ref.getReferenced();
                if (xcBuildConfiguration.getName().equals(Mode.RELEASE.getXcodeCompatibleName())) {
                    final NextStep developmentTeam = xcBuildConfiguration.getOrCreateBuildSettings().get("DEVELOPMENT_TEAM");
                    if (developmentTeam != null && ((Value)developmentTeam).value.length() != 0) {
                        return ((Value) developmentTeam).value;
                    }
                }
            }

            xcConfigurationList = project.getRoot().getRootObject().getReferenced().getBuildConfigurationList()
                    .getReferenced();
            for (PBXObjectRef<XCBuildConfiguration> ref : xcConfigurationList.getOrCreateBuildConfigurations()) {
                XCBuildConfiguration xcBuildConfiguration = ref.getReferenced();
                if (xcBuildConfiguration.getName().equals(Mode.RELEASE.getXcodeCompatibleName())) {
                    final NextStep developmentTeam = xcBuildConfiguration.getOrCreateBuildSettings().get("DEVELOPMENT_TEAM");
                    if (developmentTeam != null && ((Value)developmentTeam).value.length() != 0) {
                        return ((Value) developmentTeam).value;
                    }
                }
            }
        } catch (Throwable t) {
            getProject().getLogger().log(LogLevel.ERROR, "Failed to read Xcode project file", t);
            return null;
        }
        return null;
    }

    private void generateExportOptionsPlist() {

        // Generate options file
        File exportOptionsPlist = getExportOptionsPlist();

        LOG.quiet("Generate export_options.plist");

        try {
            if (!exportOptionsPlist.exists()) {
                String template;
                {
                    StringBuilder builder = new StringBuilder();
                    InputStream stream = getClass().getResourceAsStream("export_options_template.txt");
                    byte buff[] = new byte[1024];
                    int len;
                    while ((len = stream.read(buff)) > 0) {
                        builder.append(new String(buff, 0, len, StandardCharsets.UTF_8));
                    }
                    template = builder.toString();
                }

                PrintWriter writer = new PrintWriter(exportOptionsPlist);
                writer.print(template);
                writer.close();
            }

            ExportOptionsPlistManager manager = new ExportOptionsPlistManager(exportOptionsPlist);
            manager.clean();

            String method = getExportMethod();
            if (method != null && !method.isEmpty()) {
                manager.setMethod(method);
            }
            manager.setTeamId(getDevelopmentTeam());
            manager.setCompileBitcode(getCompileBitcode());
            manager.setUploadBitcode(getUploadBitcode());
            manager.setUploadSymbols(getUploadSymbols());
            manager.setEmbedOnDemandResourcesAssetPacksInBundle(getEmbedOnDemandResourcesAssetPacksInBundle());
            String iCloudContainerEnvironment = getICloudContainerEnvironment();
            if (iCloudContainerEnvironment != null && !iCloudContainerEnvironment.isEmpty()) {
                manager.setICloudContainerEnvironment(iCloudContainerEnvironment);
            }
            String thinning = getThinning();
            if (thinning != null && !thinning.isEmpty()) {
                manager.setThinning(thinning);
            }
            String appUrl = getAppURL();
            if (appUrl != null && !appUrl.isEmpty()) {
                manager.setAppURL(appUrl);
            }
            String displayImageURL = getDisplayImageURL();
            if (displayImageURL != null && !displayImageURL.isEmpty()) {
                manager.setDisplayImageURL(displayImageURL);
            }
            String fullSizeImageURL = getFullSizeImageURL();
            if (fullSizeImageURL != null && !fullSizeImageURL.isEmpty()) {
                manager.setFullSizeImageURL(fullSizeImageURL);
            }

            String bundleId = getBundleIdentifier();
            String provisioningProf = getProvisioningProfileSpecifier();

            if (bundleId != null && !bundleId.isEmpty() && provisioningProf != null && !provisioningProf.isEmpty()) {
                manager.setProvisioningProfiles(bundleId, provisioningProf);
            }

            String signingId = getSigningIdentity();
            if (signingId != null && !signingId.isEmpty()) {
                manager.setSigningCertificate(signingId);
            }

            manager.save();

        } catch (Throwable t) {
            throw new GradleException("Could not generate export_options.plist", t);
        }

    }
}


text:
<?php

namespace Gone\APIBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gone\APIBundle\Model\ImageInterface;

/**
 * ProductImages
 *
 * @ORM\Table(name="Product_images", indexes={@ORM\Index(name="product_id", columns={"product_id"})})
 * @ORM\Entity
 */
class Image implements ImageInterface
{
    /**
     * @var \DateTime
     *
     * @ORM\Column(name="added_date", type="datetime", nullable=false)
     */
    private $addedDate;

    /**
     * @var string
     *
     * @ORM\Column(name="url", type="string", length=250, nullable=false)
     */
    private $url;

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var \Gone\APIBundle\Entity\Product
     *
     * @ORM\ManyToOne(targetEntity="Gone\APIBundle\Entity\Product")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="product_id", referencedColumnName="id")
     * })
     */
    private $product;

    /**
     * Set addedDate
     *
     * @param \DateTime $addedDate
     * @return ProductImages
     */
    public function setAddedDate($addedDate)
    {
        $this->addedDate = $addedDate;

        return $this;
    }

    /**
     * Get addedDate
     *
     * @return \DateTime
     */
    public function getAddedDate()
    {
        return $this->addedDate;
    }

    /**
     * Set url
     *
     * @param string $url
     * @return ProductImages
     */
    public function setUrl($url)
    {
        $this->url = $url;

        return $this;
    }

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

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

    /**
     * Set product
     *
     * @param \Gone\APIBundle\Entity\Product $product
     * @return ProductImages
     */
    public function setProduct(\Gone\APIBundle\Entity\Product $product = null)
    {
        $this->product = $product;

        return $this;
    }

    /**
     * Get product
     *
     * @return \Gone\APIBundle\Entity\Product
     */
    public function getProduct()
    {
        return $this->product;
    }
}


text:
package com.dushantsw.integration.managers;

import com.dushantsw.integration.entities.About;
import com.dushantsw.integration.managers.exceptions.AboutRetrievingException;

/**
 * Provides access to the Wikipedia.
 *
 * @author dushantsw
 */
public interface WikipediaClient {

    /**
     * Sends an asynchronous request to Wikipedia API to get images for the
     * given {@code name}
     *
     * @param name     of the page.
     */
    About getWikiPageOfArtistByName(final String name) throws AboutRetrievingException;
}


text:
#ifndef INC_CharBuffer_hpp__
#define INC_CharBuffer_hpp__

/*
 * SOFTWARE RIGHTS
 *

 * ANTLR 2.7.1 MageLang Insitute, 1999, 2000, 2001
 *

 * We reserve no legal rights to the ANTLR--it is fully in the
 * public domain. An individual or company may do whatever
 * they wish with source code distributed with ANTLR or the
 * code generated by ANTLR, including the incorporation of
 * ANTLR, or its output, into commercial software.
 *

 * We encourage users to develop software with ANTLR. However,
 * we do ask that credit is given to us for developing
 * ANTLR. By "credit", we mean that if you use ANTLR or
 * incorporate any source code into one of your programs
 * (commercial product, research project, or otherwise) that
 * you acknowledge this fact somewhere in the documentation,
 * research report, etc... If you like ANTLR and have
 * developed a nice tool with the output, please mention that
 * you developed it using ANTLR. In addition, we ask that the
 * headers remain intact in our source code. As long as these
 * guidelines are kept, we expect to continue enhancing this
 * system and expect to make other tools available as they are
 * completed.
 *

 * The ANTLR gang:
 * @version ANTLR 2.7.1 MageLang Insitute, 1999, 2000, 2001
 * @author Terence Parr, MageLang Institute
 * @author
John Lilley, Empathy Software
 * @author
Pete Wells
 */

#include <antlr/config.hpp>
#include <antlr/InputBuffer.hpp>

#ifdef ANTLR_CXX_SUPPORTS_NAMESPACE
namespace antlr {
#endif

/**A Stream of characters fed to the lexer from a InputStream that can
 * be rewound via mark()/rewind() methods.
 *

 * A dynamic array is used to buffer up all the input characters.  Normally,
 * "k" characters are stored in the buffer.  More characters may be stored
 * during guess mode (testing syntactic predicate), or when LT(i>k) is
 * referenced.
 * Consumption of characters is deferred.  In other words, reading the next
 * character is not done by consume(), but deferred until needed by LA or LT.
 *

 *
 * @see antlr.CharQueue
 */

class ANTLR_API CharBuffer : public InputBuffer {
private:
	// character source
	ANTLR_USE_NAMESPACE(std)istream& input;

public:
	/// Create a character buffer
	CharBuffer(ANTLR_USE_NAMESPACE(std)istream& input_);
	/// Get the next character from the stream
	int getChar();
private:
	// NOTE: Unimplemented
	CharBuffer(const CharBuffer& other);
	CharBuffer& operator=(const CharBuffer& other);
};

#ifdef ANTLR_CXX_SUPPORTS_NAMESPACE
}
#endif

#endif //INC_CharBuffer_hpp__


text:
from .base import BaseDiscoverer

class Discoverer(BaseDiscoverer):
    '''Looks for RSS autodiscovery tags. Reference:

    * http://www.rssboard.org/rss-autodiscovery
    '''

    xpath = '/html:html/html:head/html:link' \
            '[@type=\'application/rss+xml\']' \
            '[@rel=\'alternate\'][@href]'


text:
package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"sort"
	"strings"
	"sync"
	"text/template"
	"time"

	"github.com/facebookgo/grace/gracehttp"
	"github.com/maruel/circular"
	"github.com/maruel/interrupt"
)

var footerTmpl = template.Must(template.New("name").Parse(``))

// TODO(maruel): Split the model-view.
type repositories struct {
	root   string
	delay  time.Duration
	footer string // HTML safe pre-generated footer.

	wg       sync.WaitGroup
	readLock sync.Mutex
	addLock  sync.Mutex
	repos    map[string]*git
}

func (r *repositories) init() error {
	// Find all the repositories, sync them all.
	var wg sync.WaitGroup
	err := filepath.Walk(r.root, func(path string, info os.FileInfo, err error) error {
		if strings.HasSuffix(path, "/config") {
			wg.Add(1)
			go func() {
				defer wg.Done()
				path = path[:len(path)-7]
				name := path[len(r.root)+1:]
				g := &git{
					root:    path,
					name:    name,
					delay:   r.delay,
					footer:  r.footer,
					revList: map[string][]string{},
				}
				r.repos[name] = g
				// TODO(maruel): Do this asynchronously.
				if err := g.updateBranches(false); err != nil {
					log.Fatal(err)
				}
				r.wg.Add(1)
				go func() {
					defer r.wg.Done()
					g.scanLoop()
				}()
			}()
			return filepath.SkipDir
		}
		return nil
	})
	wg.Wait()
	return err
}

func (r *repositories) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	if req.URL.Path == "/" {
		r.rootHandler(w, req)
	} else {
		r.flowHandler(w, req)
	}
}

var repoRootTmpl = template.Must(template.New("name").Parse(`

Repositories

{{range .Items}}
{{.}}

{{end}}

{{.Footer}}`))

func (r *repositories) rootHandler(w http.ResponseWriter, req *http.Request) {
	if req.Method != "GET" {
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		http.Error(w, "Invalid Method", http.StatusMethodNotAllowed)
		return
	}
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	r.readLock.Lock()
	defer r.readLock.Unlock()
	list := make([]string, 0, len(r.repos))
	for k := range r.repos {
		list = append(list, k)
	}
	sort.Strings(list)
	t := &struct {
		Items  []string
		Footer string
	}{
		list,
		r.footer,
	}
	if err := repoRootTmpl.Execute(w, t); err != nil {
		log.Fatal(err)
	}
}

var (
	repoReStr = "^[a-z0-9./\\-]+$"
	repoRe    = regexp.MustCompile(repoReStr)
)

func (r *repositories) flowHandler(w http.ResponseWriter, req *http.Request) {
	// TODO(maruel): Rewrite this code.
	// The first part is the git URL.
	i := strings.Index(req.URL.Path, ".git")
	if i < 5 || i == -1 || (len(req.URL.Path) > i+4 && req.URL.Path[i+4] != '/') {
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		http.Error(w, "Use .git to specify the git repository", 400)
		return
	}
	repo := req.URL.Path[1:i]
	req.URL.Path = req.URL.Path[i+4:]

	// Whitelist the characters allowed in repo URL section.
	if !repoRe.MatchString(repo) {
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		http.Error(w, fmt.Sprintf("Repository URL %s must match \"%s\".", repo, repoReStr), 400)
		return
	}

	r.readLock.Lock()
	g, ok := r.repos[repo]
	r.readLock.Unlock()
	if !ok {
		// init is the special case to create one.
		if req.URL.Path != "/init" {
			u := "http://" + req.Host + "/" + repo + ".git/init"
			http.Error(w, fmt.Sprintf("Visit %s to initialize the repository.", u), 400)
		} else {
			// TODO(maruel): Enforce POST.
			r.addLock.Lock()
			defer r.addLock.Unlock()
			g := &git{
				root:    filepath.Join(r.root, repo),
				name:    repo,
				delay:   r.delay,
				footer:  r.footer,
				revList: map[string][]string{},
			}
			if err := g.initialClone(w); err != nil {
				w.Header().Set("Content-Type", "text/plain; charset=utf-8")
				http.Error(w, "Use .git to specify the git repository", 400)
				return
			}
			r.repos[repo] = g
			r.wg.Add(1)
			go func() {
				defer r.wg.Done()
				g.scanLoop()
			}()
		}
	} else {
		if req.URL.Path == "/init" {
			// Discard redondant init.
			req.URL.Path = "/"
		}
		if req.URL.Path == "" {
			req.URL.Path = "/"
		}
		g.ServeHTTP(w, req)
	}
}

// TODO(maruel): Split the model-view.
type git struct {
	root   string
	name   string
	delay  time.Duration
	footer string // HTML safe pre-generated footer.

	lock     sync.RWMutex
	branches map[string]string
	revList  map[string][]string
}

func (g *git) initialClone(w http.ResponseWriter) error {
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	start := time.Now()
	repo := "https://" + g.name
	log.Printf("%s: git cloning %s", g.root, repo)
	cmd := exec.Command("git", "clone", "--mirror", "--progress", "--verbose", repo, g.root)
	w.WriteHeader(http.StatusOK)
	f := circular.AutoFlush(w, 500*time.Millisecond)
	cmd.Stdout = f
	cmd.Stderr = f
	if err := cmd.Run(); err != nil {
		log.Printf("%s: git clone failed: %s in %s", g.root, err, time.Since(start))
		return fmt.Errorf("git clone %s failed", repo)
	}
	log.Printf("%s: git clone in %s", g.root, time.Since(start))
	return g.updateBranches(true)
}

func (g *git) scanLoop() {
	for {
		select {
		case <-interrupt.Channel:
			return
		case <-time.After(g.delay):
			if err := g.fetch(); err != nil {
				log.Fatal(err)
			}
		}
	}
}

func (g *git) fetch() error {
	log.Printf("%s: Fetching", g.root)
	cmd := exec.Command("git", "fetch", "origin", "--prune", "--quiet")
	cmd.Dir = g.root
	start := time.Now()
	if err := cmd.Run(); err != nil {
		log.Printf("%s: fetch() failed: %s", g.root, err)
		return fmt.Errorf("git fetch %s failed", g.name)
	}
	log.Printf("%s: fetch() in %s", g.root, time.Since(start))
	return g.updateBranches(false)
}

func (g *git) updateBranches(locked bool) error {
	newRefs, err := getRefs(g.root)
	if err != nil {
		log.Printf("%s: getRefs() failed: %s", g.root, err)
		return fmt.Errorf("getting branches for %s failed", g.name)
	}
	// Rescan only if fetched something.
	if !eqMap(newRefs, g.branches) {
		log.Printf("%s: %d branches found", g.root, len(newRefs))
		start := time.Now()
		revList, err := scanParentHood(g.root, newRefs)
		if err != nil {
			log.Printf("%s: scanParentHood() failed: %s", g.root, err)
			return fmt.Errorf("scanning rev-list for %s failed", g.name)
		}
		log.Printf("%s: scanParentHood() found %d commits in %s", g.root, len(revList), time.Since(start))
		if !locked {
			g.lock.Lock()
			defer g.lock.Unlock()
		}
		g.branches = newRefs
		g.revList = revList
	}
	return nil
}

func (g *git) isChild(parent, child string) bool {
	for _, c := range g.revList[parent] {
		if c == child {
			return true
		}
		if g.isChild(c, child) {
			return true
		}
	}
	return false
}

func (g *git) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" {
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		http.Error(w, "Invalid Method", http.StatusMethodNotAllowed)
		return
	}
	if r.URL.Path == "/" {
		g.rootHandler(w, r)
		return
	}
	if strings.HasPrefix(r.URL.Path, "/compare/") {
		g.compareHandler(w, r)
		return
	}
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	http.Error(w, "Unknown URL", 404)
	return
}

func (g *git) compareHandler(w http.ResponseWriter, r *http.Request) {
	parts := strings.Split(r.URL.Path[9:], "/")
	if len(parts) != 2 {
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		http.Error(w, "Use /compare/ref1/ref2", 400)
		return
	}
	p, _ := g.compare(parts[0], parts[1])
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	if err := json.NewEncoder(w).Encode(&p); err != nil {
		log.Fatal(err)
	}
}

type parentHood struct {
	ParentValid bool
	ChildValid  bool
	Ancestor    bool
}

func (g *git) compare(parent, child string) (*parentHood, error) {
	p := &parentHood{}
	parent = strings.ToLower(parent)
	child = strings.ToLower(child)
	if !isHashValid(parent) || !isHashValid(child) {
		return p, errors.New("use valid commit digests")
	}
	g.lock.RLock()
	defer g.lock.RUnlock()
	_, p.ParentValid = g.revList[parent]
	_, p.ParentValid = g.revList[child]
	p.Ancestor = g.isChild(parent, child)
	return p, nil
}

var gitRootTmpl = template.Must(template.New("name").Parse(`

{{.Name}}

{{range $index, $key := .Keys}}
{{$key}}: {{index $.Map $key}}

{{end}}

<form method="GET" action="">

			Parent:
			<input type="text" name="parent" maxlen=40 size=42 value="{{.Parent}}"></input>

			Child:
			<input type="text" name="child" maxlen=40 size=42 value="{{.Child}}"></input>

			<input type="submit" value="Check"></input>

</form>
{{.Extra}}

ps: there's a JSON API
{{.Footer}}`))

func (g *git) rootHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")

	values := r.URL.Query()
	parent := values.Get("parent")
	child := values.Get("child")
	p, err := g.compare(parent, child)
	extra := ""
	if err == nil {
		extra = fmt.Sprintf("Ancestor: %t", p.Ancestor)
	}
	g.lock.RLock()
	defer g.lock.RUnlock()
	list := make([]string, 0, len(g.branches))
	for k := range g.branches {
		list = append(list, k)
	}
	sort.Strings(list)
	t := &struct {
		Name   string
		Keys   []string
		Map    map[string]string
		Parent string
		Child  string
		Extra  string
		Footer string
	}{
		g.name,
		list,
		g.branches,
		parent,
		child,
		extra,
		g.footer,
	}
	if err := gitRootTmpl.Execute(w, t); err != nil {
		log.Fatal(err)
	}
}

// Preload the footer.
type config struct {
	UA string
}

func loadConfig() *config {
	// TODO(maruel): Very barebone.
	f, err := os.Open("git-scan.json")
	if err != nil {
		return nil
	}
	defer f.Close()
	c := &config{}
	if err := json.NewDecoder(f).Decode(c); err != nil {
		return nil
	}
	return c
}

func mainImpl() error {
	port := flag.Int("port", 8010, "port number")
	notLocal := flag.Bool("all", false, "listen on all IPs, not just localhost")
	cwd, _ := os.Getwd()
	root := flag.String("root", filepath.Join(cwd, "repos"), "checkout root dir")
	flag.Parse()
	log.SetFlags(log.Ldate | log.Lmicroseconds | log.LUTC)

	if err := os.MkdirAll(*root, 0700); err != nil {
		return err
	}

	footer := ""
	if c := loadConfig(); c != nil {
		b := &bytes.Buffer{}
		if err := footerTmpl.Execute(b, c); err != nil {
			return err
		}
		footer = b.String()
	}
	repos := &repositories{
		root:   *root,
		delay:  60 * time.Second,
		repos:  map[string]*git{},
		footer: footer,
	}

	// TODO(maruel): This is a race condition with the parent process.
	if err := repos.init(); err != nil {
		return err
	}

	var addr string
	if *notLocal {
		addr = fmt.Sprintf(":%d", *port)
	} else {
		addr = fmt.Sprintf("localhost:%d", *port)
	}

	mux := http.NewServeMux()
	mux.Handle("/favicon.ico", restrictFunc(func(w http.ResponseWriter, r *http.Request) {
		// TODO(maruel): Eh.
		http.Redirect(w, r, "https://git-scm.com/images/logos/downloads/Git-Icon-1788C.png", http.StatusFound)
	}, "GET"))
	mux.Handle("/", repos)

	s := &http.Server{
		Addr:    addr,
		Handler: exitOnPanic{&loggingHandler{mux, nil}},
	}

	// TODO(maruel): Handle Ctrl-C to quick shutdown but wait for git operations.
	err := gracehttp.Serve(s)
	interrupt.Set()
	repos.wg.Wait()
	return err
}

func main() {
	if err := mainImpl(); err != nil {
		fmt.Fprintf(os.Stderr, "Failed: %s\n", err)
		os.Exit(1)
	}
}


text:
layout: page
title: Silicon Ranger Air Conference
date: 2016-05-24
author: Matthew Sheppard
tags: weekly links, java
status: published
summary: Quisque quis molestie erat, ac blandit velit.
banner: images/banner/leisure-02.jpg
booking:
  startDate: 08/14/2017
  endDate: 08/15/2017
  ctyhocn: RPTTXHX
  groupCode: SRAC
published: true
---
Fusce leo nisl, finibus tincidunt consectetur eu, facilisis ut lacus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec sed imperdiet nibh, ut vestibulum sapien. Proin vehicula dui ut eleifend tincidunt. Etiam cursus turpis ante, ut tristique tellus molestie nec. Cras facilisis odio sit amet erat mattis dapibus. Donec rutrum magna in justo commodo dapibus. Curabitur eu odio non sem egestas consequat.

* Nunc sed diam sit amet ipsum facilisis efficitur
* Curabitur in ex sed purus molestie sagittis
* In fringilla dolor id ipsum consequat venenatis.

Etiam bibendum sapien a sollicitudin fermentum. Curabitur malesuada sagittis est non aliquam. Suspendisse facilisis libero velit, interdum scelerisque ipsum vulputate eu. Curabitur euismod efficitur arcu et luctus. Nam nunc arcu, condimentum sit amet malesuada sed, viverra sit amet leo. Aliquam dictum lorem erat, vitae varius neque pellentesque et. Aliquam fermentum consectetur lectus, non aliquet orci sagittis vel. Nam nec quam et eros iaculis faucibus. Duis ut elementum nulla. Proin id libero placerat, rutrum massa vel, ornare diam.


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

angular.module('mm.addons.grades')

/**
 * Grades handlers factory.
 *
 * @module mm.addons.grades
 * @ngdoc service
 * @name $mmaGradesHandlers
 */
.factory('$mmaGradesHandlers', function($mmGrades, $mmaCoursesGrades, $state, $mmContentLinksHelper, $mmContentLinkHandlerFactory,
            mmCoursesAccessMethods, mmUserProfileHandlersTypeNewPage) {

    var self = {},
        viewGradesEnabledCache = {}; // We use a "cache" to decrease network usage.

    /**
     * Get a cache key to identify a course and a user.
     *
     * @param  {Number} courseId Course ID.
     * @param  {Number} userId   User ID.
     * @return {String}          Cache key.
     */
    function getCacheKey(courseId, userId) {
        return courseId + '#' + userId;
    }

    /**
     * Clear view grades cache.
     * If a courseId and userId are specified, it will only delete the entry for that user and course.
     *
     * @module mm.addons.grades
     * @ngdoc method
     * @name $mmaGradesHandlers#clearViewGradesCache
     * @param  {Number} [courseId] Course ID.
     * @param  {Number} [userId]   User ID.
     */
    self.clearViewGradesCache = function(courseId, userId) {
        if (courseId && userId) {
            delete viewGradesEnabledCache[getCacheKey(courseId, userId)];
        } else {
            viewGradesEnabledCache = {};
        }
    };

    /**
     * Course nav handler.
     *
     * @module mm.addons.grades
     * @ngdoc method
     * @name $mmaGradesHandlers#coursesNav
     */
    self.coursesNav = function() {

        var self = {};

        /**
         * Check if handler is enabled.
         *
         * @return {Promise} Promise resolved with true if handler is enabled, false otherwise.
         */
        self.isEnabled = function() {
            return $mmGrades.isPluginEnabled();
        };

        /**
         * Check if handler is enabled for this course.
         *
         * @param  {Number} courseId     Course ID.
         * @param  {Object} accessData   Type of access to the course: default, guest, ...
         * @param  {Object} [navOptions] Course navigation options for current user. See $mmCourses#getUserNavigationOptions.
         * @param  {Object} [admOptions] Course admin options for current user. See $mmCourses#getUserAdministrationOptions.
         * @return {Boolean}             True if handler is enabled, false otherwise.
         */
        self.isEnabledForCourse = function(courseId, accessData, navOptions, admOptions) {
            if (accessData && accessData.type == mmCoursesAccessMethods.guest) {
                return false; // Not enabled for guests.
            }

            if (navOptions && typeof navOptions.grades != 'undefined') {
                return navOptions.grades;
            }

            return $mmGrades.isPluginEnabledForCourse(courseId);
        };

        /**
         * Get the controller.
         *
         * @param {Number} courseId Course ID.
         * @return {Object}         Controller.
         */
        self.getController = function() {

            /**
             * Courses nav handler controller.
             *
             * @module mm.addons.grades
             * @ngdoc controller
             * @name $mmaGradesHandlers#coursesNav:controller
             */
            return function($scope, $state) {
                $scope.icon = 'ion-stats-bars';
                $scope.title = 'mm.grades.grades';
                $scope.class = 'mma-grades-mine-handler';
                $scope.action = function($event, course) {
                    $event.preventDefault();
                    $event.stopPropagation();
                    $state.go('site.grades', {
                        course: course
                    });
                };
            };
        };

        return self;
    };

    /**
     * View grades handler.
     *
     * @module mm.addons.grades
     * @ngdoc method
     * @name $mmaGradesHandlers#viewGrades
     */
    self.viewGrades = function() {

        var self = {
            type: mmUserProfileHandlersTypeNewPage
        };

        /**
         * Check if handler is enabled.
         *
         * @return {Promise} Promise resolved with true if handler is enabled, false otherwise.
         */
        self.isEnabled = function() {
            return $mmGrades.isPluginEnabled();
        };

        /**
         * Check if handler is enabled for this user in this context.
         *
         * @param {Object} user     User to check.
         * @param {Number} courseId Course ID.
         * @param  {Object} [navOptions] Course navigation options for current user. See $mmCourses#getUserNavigationOptions.
         * @param  {Object} [admOptions] Course admin options for current user. See $mmCourses#getUserAdministrationOptions.
         * @return {Promise}        Promise resolved with true if plugin is enabled, rejected or resolved with false otherwise.
         */
        self.isEnabledForUser = function(user, courseId, navOptions, admOptions) {
            return $mmGrades.isPluginEnabledForCourse(courseId).then(function() {
                var cacheKey = getCacheKey(courseId, user.id);
                if (typeof viewGradesEnabledCache[cacheKey] != 'undefined') {
                    return viewGradesEnabledCache[cacheKey];
                }
                return $mmGrades.isPluginEnabledForUser(courseId, user.id).then(function(enabled) {
                    viewGradesEnabledCache[cacheKey] = enabled;
                    return enabled;
                });
            });
        };

        /**
         * Check if handler is enabled for this user in this context.
         *
         * @param {Object} user     User.
         * @param {Number} courseId Course ID.
         * @return {Object}         Controller.
         */
        self.getController = function(user, courseId) {

            /**
             * View grades handler controller.
             *
             * @module mm.addons.grades
             * @ngdoc controller
             * @name $mmaGradesHandlers#viewGrades:controller
             */
            return function($scope) {
                $scope.title = 'mm.grades.grades';
                $scope.class = 'mma-grades-user-handler';
                $scope.icon = 'ion-stats-bars';

                $scope.action = function($event) {
                    $event.preventDefault();
                    $event.stopPropagation();
                    $state.go('site.grades', {
                        userid: user.id,
                        course: {id: courseId}
                    });
                };
            };

        };

        return self;
    };

    /**
     * Content links handler for view user grades (can be current user).
     *
     * @module mm.addons.grades
     * @ngdoc method
     * @name $mmaGradesHandlers#userLinksHandler
     */
    self.userLinksHandler = $mmContentLinkHandlerFactory.createChild(
                '/grade/report/user/index.php', '$mmUserDelegate_mmaGrades:viewGrades');

    // Check if the handler is enabled for a certain site. See $mmContentLinkHandlerFactory#isEnabled.
    self.userLinksHandler.isEnabled = function(siteId, url, params, courseId) {
        courseId = parseInt(params.id, 10) || courseId;
        if (!courseId) {
            return false;
        }

        return $mmGrades.isPluginEnabled(siteId).then(function(enabled) {
            if (!enabled) {
                return false;
            }

            return $mmGrades.isPluginEnabledForCourse(courseId, siteId);
        });
    };

    // Get actions to perform with the link. See $mmContentLinkHandlerFactory#getActions.
    self.userLinksHandler.getActions = function(siteIds, url, params, courseId) {
        courseId = parseInt(params.id, 10) || courseId;

        return [{
            action: function(siteId) {
                var stateParams = {
                    course: {id: courseId},
                    userid: params.userid ? parseInt(params.userid, 10) : false,
                    courseid: courseId,
                    forcephoneview: false
                };
                $mmContentLinksHelper.goInSite('site.grades', stateParams, siteId);
            }
        }];
    };

    /**
     * Content links handler for overview courses grades.
     *
     * @module mm.addons.grades
     * @ngdoc method
     * @name $mmaGradesHandlers#overviewLinksHandler
     */
    self.overviewLinksHandler = $mmContentLinkHandlerFactory.createChild(
                '/grade/report/overview/index.php', '$mmSideMenuDelegate_mmaGrades');

    // Check if the handler is enabled for a certain site. See $mmContentLinkHandlerFactory#isEnabled.
    self.overviewLinksHandler.isEnabled = $mmaCoursesGrades.isPluginEnabled;

    // Get actions to perform with the link. See $mmContentLinkHandlerFactory#getActions.
    self.overviewLinksHandler.getActions = function(siteIds, url, params, courseId) {
        return [{
            action: function(siteId) {
                // Always use redirect to make it the new history root (to avoid "loops" in history).
                $state.go('redirect', {
                    siteid: siteId,
                    state: 'site.coursesgrades',
                    params: {}
                });
            }
        }];
    };

    /**
     * Side menu nav handler.
     *
     * @module mm.addons.grades
     * @ngdoc method
     * @name $mmaGradesHandlers#sideMenuNav
     */
    self.sideMenuNav = function() {

        var self = {};

        /**
         * Check if handler is enabled.
         *
         * @return {Promise|Boolean} If handler is enabled returns a resolved promise. If it's not it can return a
         *                           rejected promise or false.
         */
        self.isEnabled = function() {
            return $mmaCoursesGrades.isPluginEnabled();
        };

        /**
         * Get the controller.
         *
         * @return {Object} Controller.
         */
        self.getController = function() {

            /**
             * Side menu nav handler controller.
             *
             * @module mm.addons.grades
             * @ngdoc controller
             * @name $mmaGradesHandlers#sideMenuNav:controller
             */
            return function($scope) {
                $scope.icon = 'ion-stats-bars';
                $scope.title = 'mm.grades.grades';
                $scope.state = 'site.coursesgrades';
                $scope.class = 'mma-grades-coursesgrades';
            };
        };

        return self;
    };

    return self;
})

.run(function($mmaGradesHandlers, $mmEvents, mmCoreEventLogout, mmUserEventProfileRefreshed) {
    $mmEvents.on(mmCoreEventLogout, $mmaGradesHandlers.clearViewGradesCache);
    $mmEvents.on(mmUserEventProfileRefreshed, function(data) {
        if (data) {
            $mmaGradesHandlers.clearViewGradesCache(data.courseid, data.userid);
        }
    });
});