text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Text;

namespace Roslyn.Diagnostics.Analyzers.ApiDesign
{
    [ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = "DeclarePublicAPIFix"), Shared]
    public class DeclarePublicAPIFix : CodeFixProvider
    {
        public sealed override ImmutableArray<string> FixableDiagnosticIds
        {
            get { return ImmutableArray.Create(RoslynDiagnosticIds.DeclarePublicApiRuleId); }
        }

        public sealed override FixAllProvider GetFixAllProvider()
        {
            return new PublicSurfaceAreaFixAllProvider();
        }

        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var project = context.Document.Project;
            TextDocument publicSurfaceAreaDocument = GetPublicSurfaceAreaDocument(project);
            if (publicSurfaceAreaDocument == null)
            {
                return;
            }

            var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
            var semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);
            foreach (var diagnostic in context.Diagnostics)
            {
                var location = diagnostic.Location;

                var symbol = FindDeclaration(root, location, semanticModel, context.CancellationToken);

                if (symbol != null)
                {
                    var minimalSymbolName = symbol.ToMinimalDisplayString(semanticModel, location.SourceSpan.Start, DeclarePublicAPIAnalyzer.ShortSymbolNameFormat);
                    var publicSurfaceAreaSymbolName = symbol.ToDisplayString(DeclarePublicAPIAnalyzer.PublicApiFormat);

                    context.RegisterCodeFix(
                            new AdditionalDocumentChangeAction(
                                $"Add {minimalSymbolName} to public API",
                                c => GetFix(publicSurfaceAreaDocument, publicSurfaceAreaSymbolName, c)),
                            diagnostic);
                }
            }
        }

        private static TextDocument GetPublicSurfaceAreaDocument(Project project)
        {
            return project.AdditionalDocuments.FirstOrDefault(doc => doc.Name.Equals(DeclarePublicAPIAnalyzer.PublicApiFileName, StringComparison.OrdinalIgnoreCase));
        }

        private async Task<Solution> GetFix(TextDocument publicSurfaceAreaDocument, string newSymbolName, CancellationToken cancellationToken)
        {
            var sourceText = await publicSurfaceAreaDocument.GetTextAsync(cancellationToken).ConfigureAwait(false);
            var newSourceText = AddSymbolNamesToSourceText(sourceText, new[] { newSymbolName });

            return publicSurfaceAreaDocument.Project.Solution.WithAdditionalDocumentText(publicSurfaceAreaDocument.Id, newSourceText);
        }

        private static SourceText AddSymbolNamesToSourceText(SourceText sourceText, IEnumerable<string> newSymbolNames)
        {
            HashSet<string> lines = GetLinesFromSourceText(sourceText);

            foreach (var name in newSymbolNames)
            {
                lines.Add(name);
            }

            var sortedLines = lines.OrderBy(s => s, StringComparer.Ordinal);

            var newSourceText = sourceText.Replace(new TextSpan(0, sourceText.Length), string.Join(Environment.NewLine, sortedLines));
            return newSourceText;
        }

        private static HashSet<string> GetLinesFromSourceText(SourceText sourceText)
        {
            var lines = new HashSet<string>();

            foreach (var textLine in sourceText.Lines)
            {
                var text = textLine.ToString();
                if (!string.IsNullOrWhiteSpace(text))
                {
                    lines.Add(text);
                }
            }

            return lines;
        }

        private static ISymbol FindDeclaration(SyntaxNode root, Location location, SemanticModel semanticModel, CancellationToken cancellationToken)
        {
            var node = root.FindNode(location.SourceSpan);
            ISymbol symbol = null;
            while (node != null)
            {
                symbol = semanticModel.GetDeclaredSymbol(node, cancellationToken);
                if (symbol != null)
                {
                    break;
                }

                node = node.Parent;
            }

            return symbol;
        }

        private class AdditionalDocumentChangeAction : CodeAction
        {
            private readonly Func<CancellationToken, Task<Solution>> _createChangedAdditionalDocument;

            public AdditionalDocumentChangeAction(string title, Func<CancellationToken, Task<Solution>> createChangedAdditionalDocument)
            {
                this.Title = title;
                _createChangedAdditionalDocument = createChangedAdditionalDocument;
            }

            public override string Title { get; }

            protected override Task<Solution> GetChangedSolutionAsync(CancellationToken cancellationToken)
            {
                return _createChangedAdditionalDocument(cancellationToken);
            }
        }

        private class FixAllAdditionalDocumentChangeAction : CodeAction
        {
            private readonly List<KeyValuePair<Project, ImmutableArray<Diagnostic>>> _diagnosticsToFix;
            private readonly Solution _solution;

            public FixAllAdditionalDocumentChangeAction(string title, Solution solution, List<KeyValuePair<Project, ImmutableArray<Diagnostic>>> diagnosticsToFix)
            {
                this.Title = title;
                _solution = solution;
                _diagnosticsToFix = diagnosticsToFix;
            }

            public override string Title { get; }

            protected override async Task<Solution> GetChangedSolutionAsync(CancellationToken cancellationToken)
            {
                var updatedPublicSurfaceAreaText = new List<KeyValuePair<DocumentId, SourceText>>();

                foreach (var pair in _diagnosticsToFix)
                {
                    var project = pair.Key;
                    var diagnostics = pair.Value;

                    var publicSurfaceAreaAdditionalDocument = GetPublicSurfaceAreaDocument(project);

                    if (publicSurfaceAreaAdditionalDocument == null)
                    {
                        continue;
                    }

                    var sourceText = await publicSurfaceAreaAdditionalDocument.GetTextAsync(cancellationToken).ConfigureAwait(false);

                    var groupedDiagnostics =
                        diagnostics
                            .Where(d => d.Location.IsInSource)
                            .GroupBy(d => d.Location.SourceTree);

                    var newSymbolNames = new List<string>();

                    foreach (var grouping in groupedDiagnostics)
                    {
                        var document = project.GetDocument(grouping.Key);

                        if (document == null)
                        {
                            continue;
                        }

                        var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
                        var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

                        foreach (var diagnostic in grouping)
                        {
                            var location = diagnostic.Location;
                            var symbol = FindDeclaration(root, location, semanticModel, cancellationToken);

                            if (symbol != null)
                            {
                                var publicSurfaceAreaSymbolName = symbol.ToDisplayString(DeclarePublicAPIAnalyzer.PublicApiFormat);

                                if (symbol != null)
                                {
                                    newSymbolNames.Add(publicSurfaceAreaSymbolName);
                                }
                            }
                        }
                    }

                    var newSourceText = AddSymbolNamesToSourceText(sourceText, newSymbolNames);

                    updatedPublicSurfaceAreaText.Add(new KeyValuePair<DocumentId, SourceText>(publicSurfaceAreaAdditionalDocument.Id, newSourceText));
                }

                var newSolution = _solution;

                foreach (var pair in updatedPublicSurfaceAreaText)
                {
                    newSolution = newSolution.WithAdditionalDocumentText(pair.Key, pair.Value);
                }

                return newSolution;
            }
        }

        private class PublicSurfaceAreaFixAllProvider : FixAllProvider
        {
            public override async Task<CodeAction> GetFixAsync(FixAllContext fixAllContext)
            {
                var diagnosticsToFix = new List<KeyValuePair<Project, ImmutableArray<Diagnostic>>>();
                string titleFormat = "Add all items in {0} {1} to the public API";
                string title = null;

                switch (fixAllContext.Scope)
                {
                    case FixAllScope.Document:
                        {
                            var diagnostics = await fixAllContext.GetDocumentDiagnosticsAsync(fixAllContext.Document).ConfigureAwait(false);
                            diagnosticsToFix.Add(new KeyValuePair<Project, ImmutableArray<Diagnostic>>(fixAllContext.Project, diagnostics));
                            title = string.Format(titleFormat, "document", fixAllContext.Document.Name);
                            break;
                        }

                    case FixAllScope.Project:
                        {
                            var project = fixAllContext.Project;
                            ImmutableArray<Diagnostic> diagnostics = await fixAllContext.GetAllDiagnosticsAsync(project).ConfigureAwait(false);
                            diagnosticsToFix.Add(new KeyValuePair<Project, ImmutableArray<Diagnostic>>(fixAllContext.Project, diagnostics));
                            title = string.Format(titleFormat, "project", fixAllContext.Project.Name);
                            break;
                        }

                    case FixAllScope.Solution:
                        {
                            foreach (var project in fixAllContext.Solution.Projects)
                            {
                                ImmutableArray<Diagnostic> diagnostics = await fixAllContext.GetAllDiagnosticsAsync(project).ConfigureAwait(false);
                                diagnosticsToFix.Add(new KeyValuePair<Project, ImmutableArray<Diagnostic>>(project, diagnostics));
                            }

                            title = "Add all items in the solution to the public API";
                            break;
                        }

                    case FixAllScope.Custom:
                        return null;
                    default:
                        break;
                }

                return new FixAllAdditionalDocumentChangeAction(title, fixAllContext.Solution, diagnosticsToFix);
            }
        }
    }
}


text:
#include "tsystem.h"

using namespace std;

#include <set>
#include "tfilepath_io.h"
#include "tconvert.h"

#ifndef TNZCORE_LIGHT

#include <QDateTime>
#include <QStringList>
#include <QProcess>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QSettings>
#include <QVariant>
#include <QThread>
#include <QUrl>
#include <QCoreApplication>
#include <QUuid>

#include <QDesktopServices>
#include <QHostInfo>

#ifdef _WIN32
#include <shlobj.h>
#include <shellapi.h>
#include <winnt.h>
#endif

#include <QStringList>

namespace {

inline QString toQString(const TFilePath &path) {
  return QString::fromStdWString(path.getWideString());
}

int HasMainLoop = -1;

}  // namespace
//-----------------------------------------------------------------------------------

TFileStatus::TFileStatus(const TFilePath &path) {
  m_fileInfo = QFileInfo(QString::fromStdWString(path.getWideString()));
  m_exist    = m_fileInfo.exists();
}

//-----------------------------------------------------------------------------------

QString TFileStatus::getGroup() const {
  if (!m_exist) return QString();
  return m_fileInfo.group();
}

//-----------------------------------------------------------------------------------

QString TFileStatus::getUser() const {
  if (!m_exist) return QString();
  return m_fileInfo.owner();
}

//-----------------------------------------------------------------------------------

TINT64 TFileStatus::getSize() const {
  if (!m_exist) return 0;
  return m_fileInfo.size();
}

//-----------------------------------------------------------------------------------

QDateTime TFileStatus::getLastAccessTime() const {
  if (!m_exist) return QDateTime();
  return m_fileInfo.lastRead();
}

//-----------------------------------------------------------------------------------

QDateTime TFileStatus::getLastModificationTime() const {
  if (!m_exist) return QDateTime();
  return m_fileInfo.lastModified();
}

//-----------------------------------------------------------------------------------

QDateTime TFileStatus::getCreationTime() const {
  if (!m_exist) return QDateTime();
  return m_fileInfo.created();
}

//-----------------------------------------------------------------------------------

QFile::Permissions TFileStatus::getPermissions() const {
  if (!m_exist) return 0;
  return m_fileInfo.permissions();
}

//-----------------------------------------------------------------------------------

bool TFileStatus::isDirectory() const {
  if (!m_exist) return 0;
  return m_fileInfo.isDir();
}

//-----------------------------------------------------------------------------------

bool TFileStatus::isLink() const { return m_fileInfo.isSymLink(); }

//-----------------------------------------------------------------------------------

bool TSystem::doHaveMainLoop() {
  if (HasMainLoop == -1)
    assert(!"you MUST call the TSystem::hasMainLoop function in the main of the program!");
  return HasMainLoop == 1;
}

//-----------------------------------------------------------------------------------

void TSystem::hasMainLoop(bool state) {
  assert(HasMainLoop == -1);
  HasMainLoop = state ? 1 : 0;
}

//-----------------------------------------------------------------------------------

QString TSystem::getHostName() { return QHostInfo::localHostName(); }

//------------------------------------------------------------

QString TSystem::getUserName() {
  QStringList list = QProcess::systemEnvironment();
  int j;
  for (j = 0; j < list.size(); j++) {
    QString value = list.at(j);
    QString user;
#ifdef _WIN32
    if (value.startsWith("USERNAME=")) user = value.right(value.size() - 9);
#else
    if (value.startsWith("USER=")) user = value.right(value.size() - 5);
#endif
    if (!user.isEmpty()) return user;
  }
  return QString("none");
}

//------------------------------------------------------------

TFilePath TSystem::getTempDir() {
  return TFilePath(QDir::tempPath().toStdString());
}

//------------------------------------------------------------

TFilePath TSystem::getTestDir(string name) {
  return TFilePath("C:") + TFilePath(name);
}

//------------------------------------------------------------

QString TSystem::getSystemValue(const TFilePath &name) {
  QStringList strlist = toQString(name).split("\\", QString::SkipEmptyParts);

  assert(strlist.size() > 3);
  assert(strlist.at(0) == "SOFTWARE");

  QSettings qs(QSettings::SystemScope, strlist.at(1), strlist.at(2));

  int i;
  QString varName;

  for (i = 3; i < strlist.size(); i++) {
    varName += strlist.at(i);
    if (i < strlist.size() - 1) varName += "//";
  }

  return qs.value(varName).toString();
}

//------------------------------------------------------------

TFilePath TSystem::getBinDir() {
  TFilePath fp =
      TFilePath(QCoreApplication::applicationFilePath().toStdString());
  return fp.getParentDir();
}

//------------------------------------------------------------

TFilePath TSystem::getDllDir() { return getBinDir(); }
//------------------------------------------------------------

TFilePath TSystem::getUniqueFile(QString field) {
  QString uuid = QUuid::createUuid()
                     .toString()
                     .replace("-", "")
                     .replace("{", "")
                     .replace("}", "")
                     .toLatin1()
                     .data();

  QString path = QDir::tempPath() + QString("\\") + field + uuid;

  return TFilePath(path.toStdString());
}

//------------------------------------------------------------

namespace {
TFilePathSet getPathsToCreate(const TFilePath &path) {
  TFilePathSet pathList;
  if (path.isEmpty()) return pathList;
  TFilePath parentDir = path;
  while (!TFileStatus(parentDir).doesExist()) {
    if (parentDir == parentDir.getParentDir()) return TFilePathSet();
    pathList.push_back(parentDir);
    parentDir = parentDir.getParentDir();
  }
  return pathList;
}

void setPathsPermissions(const TFilePathSet &pathSet,
                         QFile::Permissions permissions) {
  TFilePathSet::const_iterator it;
  for (it = pathSet.begin(); it != pathSet.end(); it++) {
    QFile f(toQString(*it));
    f.setPermissions(permissions);
  }
}
}

// gestire exception
void TSystem::mkDir(const TFilePath &path) {
  TFilePathSet pathSet = getPathsToCreate(path);
  QString qPath        = toQString(path);
  assert(!qPath.contains("+"));
  if (!QDir::current().mkpath(qPath))
    throw TSystemException(path, "can't create folder!");

  setPathsPermissions(
      pathSet, QFile::ReadUser | QFile::WriteUser | QFile::ExeUser |
                   QFile::ReadGroup | QFile::WriteGroup | QFile::ExeGroup |
                   QFile::ReadOther | QFile::WriteOther | QFile::ExeOther);
}

//------------------------------------------------------------
// gestire exception
void TSystem::rmDir(const TFilePath &path) {
  if (!QDir(toQString(path.getParentDir()))
           .rmdir(QString::fromStdString(path.getName())))
    throw TSystemException(path, "can't remove folder!");
}

// vinz

//------------------------------------------------------------

namespace {
void rmDirTree(const QString &path) {
  int i;
  QFileInfoList fil = QDir(path).entryInfoList();
  for (i = 0; i < fil.size(); i++) {
    QFileInfo fi = fil.at(i);
    if (fi.fileName() == QString(".") || fi.fileName() == QString(".."))
      continue;
    QString son = fi.absoluteFilePath();
    if (QFileInfo(son).isDir())
      rmDirTree(son);
    else if (QFileInfo(son).isFile())
      if (!QFile::remove(son))
        throw TSystemException("can't remove file" + son.toStdString());
  }
  if (!QDir::current().rmdir(path))
    throw TSystemException("can't remove path!");
}

}  // namespace

//------------------------------------------------------------

void TSystem::rmDirTree(const TFilePath &path) { ::rmDirTree(toQString(path)); }

//------------------------------------------------------------

void TSystem::copyDir(const TFilePath &dst, const TFilePath &src) {
  QFileInfoList fil = QDir(toQString(src)).entryInfoList();

  QDir::current().mkdir(toQString(dst));

  int i;
  for (i = 0; i < fil.size(); i++) {
    QFileInfo fi = fil.at(i);
    if (fi.fileName() == QString(".") || fi.fileName() == QString(".."))
      continue;
    if (fi.isDir()) {
      TFilePath srcDir = TFilePath(fi.filePath().toStdString());
      TFilePath dstDir = dst + srcDir.getName();
      copyDir(dstDir, srcDir);
    } else
      QFile::copy(fi.filePath(),
                  toQString(dst) + QString("\\") + fi.fileName());
  }
}

//------------------------------------------------------------
/*
void TSystem::touchFile(const TFilePath &path)
{
QFile f(toQString(path));

if (!f.open(QIODevice::ReadWrite))
  throw TSystemException(path, "can't touch file!");
else
  f.close();
}
*/
//------------------------------------------------------------
/*
#ifdef _WIN32

wstring getFormattedMessage(DWORD lastError)
{
LPVOID lpMsgBuf;
FormatMessage(
    FORMAT_MESSAGE_ALLOCATE_BUFFER |
    FORMAT_MESSAGE_FROM_SYSTEM |
    FORMAT_MESSAGE_IGNORE_INSERTS,
    NULL,
    lastError,
    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
    (LPTSTR) &lpMsgBuf,
    0,
    NULL
);

int wSize = MultiByteToWideChar(0,0,(char*)lpMsgBuf,-1,0,0);
if(!wSize)
  return wstring();

wchar_t* wBuffer = new wchar_t [wSize+1];
MultiByteToWideChar(0,0,(char*)lpMsgBuf,-1,wBuffer,wSize);
wBuffer[wSize]='\0';
wstring wmsg(wBuffer);

delete []wBuffer;
LocalFree(lpMsgBuf);
return wmsg;
}

//------------------------------------------------------------

#endif
*/
//------------------------------------------------------------

void TSystem::copyFile(const TFilePath &dst, const TFilePath &src,
                       bool overwrite) {
  assert(dst != TFilePath());

  if (dst == src) return;

  const QString &qDst = toQString(dst);
  if (overwrite && QFile::exists(qDst)) QFile::remove(qDst);

  if (!QFile::copy(toQString(src), qDst))
    throw TSystemException(dst, "can't copy file!");
}

//------------------------------------------------------------

void TSystem::renameFile(const TFilePath &dst, const TFilePath &src,
                         bool overwrite) {
  assert(dst != TFilePath());

  if (dst == src) return;

  const QString &qDst = toQString(dst);
  if (overwrite && QFile::exists(qDst)) QFile::remove(qDst);

  if (!QFile::rename(toQString(src), qDst))
    throw TSystemException(dst, "can't rename file!");
}

//------------------------------------------------------------

// gestire gli errori con GetLastError?
void TSystem::deleteFile(const TFilePath &fp) {
  if (!QFile::remove(toQString(fp)))
    throw TSystemException(fp, "can't delete file!");
}

//------------------------------------------------------------

void TSystem::hideFile(const TFilePath &fp) {
#ifdef _WIN32
  if (!SetFileAttributesW(fp.getWideString().c_str(), FILE_ATTRIBUTE_HIDDEN))
    throw TSystemException(fp, "can't hide file!");
#else  // MACOSX, and others
  TSystem::renameFile(TFilePath(fp.getParentDir() + L"." + fp.getLevelNameW()),
                      fp);
#endif
}

//------------------------------------------------------------

class CaselessFilepathLess final
    : public std::binary_function<TFilePath, TFilePath, bool> {
public:
  bool operator()(const TFilePath &a, const TFilePath &b) const {
    // Perform case sensitive compare, fallback to case insensitive.
    const wstring a_str = a.getWideString();
    const wstring b_str = b.getWideString();

    unsigned int i   = 0;
    int case_compare = -1;
    while (a_str[i] || b_str[i]) {
      if (a_str[i] != b_str[i]) {
        const wchar_t a_wchar = towlower(a_str[i]);
        const wchar_t b_wchar = towlower(b_str[i]);
        if (a_wchar < b_wchar) {
          return true;
        } else if (a_wchar > b_wchar) {
          return false;
        } else if (case_compare == -1) {
          case_compare = a_str[i] < b_str[i];
        }
      }
      i++;
    }
    return (case_compare == 1);
  }
};

//------------------------------------------------------------
/*! return the file list which is readable and executable
*/
void TSystem::readDirectory_Dir_ReadExe(TFilePathSet &dst,
                                        const TFilePath &path) {
  if (!TFileStatus(path).isDirectory())
    throw TSystemException(path, " is not a directory");

  std::set<TFilePath, CaselessFilepathLess> fileSet;

  QStringList fil =
      QDir(toQString(path))
          .entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::Readable);

  int i;
  for (i = 0; i < fil.size(); i++) {
    QString fi = fil.at(i);

    TFilePath son = path + TFilePath(fi.toStdWString());

    fileSet.insert(son);
  }

  dst.insert(dst.end(), fileSet.begin(), fileSet.end());
}

//------------------------------------------------------------
/*! to retrieve the both lists with groupFrames option = on and off.
*/
void TSystem::readDirectory(TFilePathSet &groupFpSet, TFilePathSet &allFpSet,
                            const TFilePath &path) {
  if (!TFileStatus(path).isDirectory())
    throw TSystemException(path, " is not a directory");

  std::set<TFilePath, CaselessFilepathLess> fileSet_group;
  std::set<TFilePath, CaselessFilepathLess> fileSet_all;

  QStringList fil =
      QDir(toQString(path))
          .entryList(QDir::Files | QDir::NoDotAndDotDot | QDir::Readable);

  if (fil.size() == 0) return;

  for (int i = 0; i < fil.size(); i++) {
    QString fi = fil.at(i);

    TFilePath son = path + TFilePath(fi.toStdWString());

    // store all file paths
    fileSet_all.insert(son);

    // in case of the sequencial files
    if (son.getDots() == "..") son = son.withFrame();

    // store the group. insersion avoids duplication of the item
    fileSet_group.insert(son);
  }

  groupFpSet.insert(groupFpSet.end(), fileSet_group.begin(),
                    fileSet_group.end());
  allFpSet.insert(allFpSet.end(), fileSet_all.begin(), fileSet_all.end());
}

//------------------------------------------------------------

void TSystem::readDirectory(TFilePathSet &dst, const QDir &dir,
                            bool groupFrames) {
  if (!(dir.exists() && QFileInfo(dir.path()).isDir()))
    throw TSystemException(TFilePath(dir.path().toStdWString()),
                           " is not a directory");

  QStringList entries(dir.entryList(dir.filter() | QDir::NoDotAndDotDot));
  TFilePath dirPath(dir.path().toStdWString());

  std::set<TFilePath, CaselessFilepathLess> fpSet;

  int e, eCount = entries.size();
  for (e = 0; e != eCount; ++e) {
    TFilePath path(dirPath + TFilePath(entries.at(e).toStdWString()));

    if (groupFrames && path.getDots() == "..") path = path.withFrame();

    fpSet.insert(path);
  }

  dst.insert(dst.end(), fpSet.begin(), fpSet.end());
}

//------------------------------------------------------------

void TSystem::readDirectory(TFilePathSet &dst, const TFilePath &path,
                            bool groupFrames, bool onlyFiles,
                            bool getHiddenFiles) {
  QDir dir(toQString(path));

  QDir::Filters filters(QDir::Files);
  if (!onlyFiles) filters |= QDir::Dirs;
  if (getHiddenFiles) filters |= QDir::Hidden;
  dir.setFilter(filters);

  readDirectory(dst, dir, groupFrames);
}

//------------------------------------------------------------

void TSystem::readDirectory(TFilePathSet &dst, const TFilePathSet &pathSet,
                            bool groupFrames, bool onlyFiles,
                            bool getHiddenFiles) {
  for (TFilePathSet::const_iterator it = pathSet.begin(); it != pathSet.end();
       it++)
    readDirectory(dst, *it, groupFrames, onlyFiles);
}

//------------------------------------------------------------

TFilePathSet TSystem::readDirectory(const TFilePath &path, bool groupFrames,
                                    bool onlyFiles, bool getHiddenFiles) {
  TFilePathSet filePathSet;
  readDirectory(filePathSet, path, groupFrames, onlyFiles, getHiddenFiles);
  return filePathSet;
}

//------------------------------------------------------------

TFilePathSet TSystem::readDirectory(const TFilePathSet &pathSet,
                                    bool groupFrames, bool onlyFiles,
                                    bool getHiddenFiles) {
  TFilePathSet dst;
  readDirectory(dst, pathSet, groupFrames, onlyFiles, getHiddenFiles);
  return dst;
}

//------------------------------------------------------------

void TSystem::readDirectoryTree(TFilePathSet &dst, const TFilePath &path,
                                bool groupFrames, bool onlyFiles) {
  if (!TFileStatus(path).isDirectory())
    throw TSystemException(path, " is not a directory");

  QFileInfoList fil = QDir(toQString(path)).entryInfoList();
  int i;
  for (i = 0; i < fil.size(); i++) {
    QFileInfo fi = fil.at(i);
    if (fi.fileName() == QString(".") || fi.fileName() == QString(".."))
      continue;
    TFilePath son = TFilePath(fi.filePath().toStdWString());
    if (TFileStatus(son).isDirectory()) {
      if (!onlyFiles) dst.push_back(son);
      readDirectoryTree(dst, son, groupFrames, onlyFiles);
    } else
      dst.push_back(son);
  }
}

//------------------------------------------------------------

void TSystem::readDirectoryTree(TFilePathSet &dst, const TFilePathSet &pathSet,
                                bool groupFrames, bool onlyFiles) {
  for (TFilePathSet::const_iterator it = pathSet.begin(); it != pathSet.end();
       it++)
    readDirectoryTree(dst, *it, groupFrames, onlyFiles);
}

//------------------------------------------------------------

TFilePathSet TSystem::readDirectoryTree(const TFilePath &path, bool groupFrames,
                                        bool onlyFiles) {
  TFilePathSet dst;
  readDirectoryTree(dst, path, groupFrames, onlyFiles);
  return dst;
}

//------------------------------------------------------------

TFilePathSet TSystem::readDirectoryTree(const TFilePathSet &pathSet,
                                        bool groupFrames, bool onlyFiles) {
  TFilePathSet dst;
  readDirectoryTree(dst, pathSet, groupFrames, onlyFiles);
  return dst;
}

//------------------------------------------------------------

TFilePathSet TSystem::packLevelNames(const TFilePathSet &fps) {
  std::set<TFilePath> tmpSet;
  TFilePathSet::const_iterator cit;
  for (cit = fps.begin(); cit != fps.end(); ++cit)
    tmpSet.insert(cit->getParentDir() + cit->getLevelName());

  TFilePathSet fps2;
  for (std::set<TFilePath>::const_iterator c_sit = tmpSet.begin();
       c_sit != tmpSet.end(); ++c_sit) {
    fps2.push_back(*c_sit);
  }
  return fps2;
}

//------------------------------------------------------------

TFilePathSet TSystem::getDisks() {
  TFilePathSet filePathSet;
  QFileInfoList fil = QDir::drives();
  int i;
  for (i = 0; i < fil.size(); i++)
    filePathSet.push_back(TFilePath(fil.at(i).filePath().toStdWString()));

  return filePathSet;
}

//------------------------------------------------------------

class LocalThread final : public QThread {
public:
  static LocalThread *currentThread() {
    return (LocalThread *)QThread::currentThread();
  }
  void sleep(TINT64 delay) { msleep(delay); }
};

void TSystem::sleep(TINT64 delay) {
  LocalThread::currentThread()->sleep(delay);
}

//--------------------------------------------------------------

int TSystem::getProcessorCount() { return QThread::idealThreadCount(); }

//--------------------------------------------------------------

bool TSystem::doesExistFileOrLevel(const TFilePath &fp) {
  if (TFileStatus(fp).doesExist()) return true;

  if (fp.isLevelName()) {
    const TFilePath &parentDir = fp.getParentDir();
    if (!TFileStatus(parentDir).doesExist()) return false;

    TFilePathSet files;
    try {
      files = TSystem::readDirectory(parentDir, false, true, true);
    } catch (...) {
    }

    TFilePathSet::iterator it, end = files.end();
    for (it = files.begin(); it != end; ++it) {
      if (it->getLevelNameW() == fp.getLevelNameW()) return true;
    }
  } else if (fp.getType() == "psd") {
    QString name(QString::fromStdWString(fp.getWideName()));
    name.append(QString::fromStdString(fp.getDottedType()));

    int sepPos                               = name.indexOf("#");
    int dotPos                               = name.indexOf(".", sepPos);
    int removeChars                          = dotPos - sepPos;
    int doubleUnderscorePos                  = name.indexOf("__", sepPos);
    if (doubleUnderscorePos > 0) removeChars = doubleUnderscorePos - sepPos;

    name.remove(sepPos, removeChars);

    TFilePath psdpath(fp.getParentDir() + TFilePath(name.toStdWString()));
    if (TFileStatus(psdpath).doesExist()) return true;
  }

  return false;
}

//--------------------------------------------------------------

void TSystem::copyFileOrLevel_throw(const TFilePath &dst,
                                    const TFilePath &src) {
  if (src.isLevelName()) {
    TFilePathSet files;
    files = TSystem::readDirectory(src.getParentDir(), false);

    TFilePathSet::iterator it, end = files.end();
    for (it = files.begin(); it != end; ++it) {
      if (it->getLevelNameW() == src.getLevelNameW()) {
        TFilePath src1 = *it;
        TFilePath dst1 = dst.withFrame(it->getFrame());

        TSystem::copyFile(dst1, src1);
      }
    }
  } else
    TSystem::copyFile(dst, src);
}

//--------------------------------------------------------------

void TSystem::renameFileOrLevel_throw(const TFilePath &dst,
                                      const TFilePath &src,
                                      bool renamePalette) {
  if (renamePalette && ((src.getType() == "tlv") || (src.getType() == "tzp") ||
                        (src.getType() == "tzu"))) {
    // Special case: since renames cannot be 'grouped' in the UI, palettes are
    // automatically
    // renamed here if required
    const char *type = (src.getType() == "tlv") ? "tpl" : "plt";

    TFilePath srcpltname(src.withNoFrame().withType(type));
    TFilePath dstpltname(dst.withNoFrame().withType(type));

    if (TSystem::doesExistFileOrLevel(src) &&
        TSystem::doesExistFileOrLevel(srcpltname))
      TSystem::renameFile(dstpltname, srcpltname, false);
  }

  if (src.isLevelName()) {
    TFilePathSet files;
    files = TSystem::readDirectory(src.getParentDir(), false);

    for (TFilePathSet::iterator it = files.begin(); it != files.end(); it++) {
      if (it->getLevelName() == src.getLevelName()) {
        TFilePath src1 = *it;
        TFilePath dst1 = dst.withFrame(it->getFrame());

        TSystem::renameFile(dst1, src1);
      }
    }
  } else
    TSystem::renameFile(dst, src);
}

//--------------------------------------------------------------

void TSystem::removeFileOrLevel_throw(const TFilePath &fp) {
  if (fp.isLevelName()) {
    TFilePathSet files;
    files = TSystem::readDirectory(fp.getParentDir(), false, true, true);

    TFilePathSet::iterator it, end = files.end();
    for (it = files.begin(); it != end; ++it) {
      if (it->getLevelName() == fp.getLevelName()) TSystem::deleteFile(*it);
    }
  } else
    TSystem::deleteFile(fp);
}

//--------------------------------------------------------------

void TSystem::hideFileOrLevel_throw(const TFilePath &fp) {
  if (fp.isLevelName()) {
    TFilePathSet files;
    files = TSystem::readDirectory(fp.getParentDir(), false);

    TFilePathSet::iterator it, end = files.end();
    for (it = files.begin(); it != end; ++it) {
      if (it->getLevelNameW() == fp.getLevelNameW()) TSystem::hideFile(*it);
    }
  } else
    TSystem::hideFile(fp);
}

//--------------------------------------------------------------

void TSystem::moveFileOrLevelToRecycleBin_throw(const TFilePath &fp) {
  if (fp.isLevelName()) {
    TFilePathSet files;
    files = TSystem::readDirectory(fp.getParentDir(), false, true, true);

    TFilePathSet::iterator it, end = files.end();
    for (it = files.begin(); it != end; ++it) {
      if (it->getLevelNameW() == fp.getLevelNameW())
        TSystem::moveFileToRecycleBin(*it);
    }
  } else
    TSystem::moveFileToRecycleBin(fp);
}

//--------------------------------------------------------------

bool TSystem::copyFileOrLevel(const TFilePath &dst, const TFilePath &src) {
  try {
    copyFileOrLevel_throw(dst, src);
  } catch (...) {
    return false;
  }
  return true;
}

//--------------------------------------------------------------

bool TSystem::renameFileOrLevel(const TFilePath &dst, const TFilePath &src,
                                bool renamePalette) {
  try {
    renameFileOrLevel_throw(dst, src, renamePalette);
  } catch (...) {
    return false;
  }
  return true;
}

//--------------------------------------------------------------

bool TSystem::removeFileOrLevel(const TFilePath &fp) {
  try {
    removeFileOrLevel_throw(fp);
  } catch (...) {
    return false;
  }
  return true;
}

//--------------------------------------------------------------

bool TSystem::hideFileOrLevel(const TFilePath &fp) {
  try {
    hideFileOrLevel_throw(fp);
  } catch (...) {
    return false;
  }
  return true;
}

//--------------------------------------------------------------

bool TSystem::moveFileOrLevelToRecycleBin(const TFilePath &fp) {
  try {
    moveFileOrLevelToRecycleBin_throw(fp);
  } catch (...) {
    return false;
  }
  return true;
}

//--------------------------------------------------------------

bool TSystem::touchParentDir(const TFilePath &fp) {
  TFilePath parentDir = fp.getParentDir();
  TFileStatus fs(parentDir);
  if (fs.isDirectory())
    return true;
  else if (fs.doesExist())
    return false;
  try {
    mkDir(parentDir);
  } catch (...) {
    return false;
  }
  return true;
}

//--------------------------------------------------------------

bool TSystem::showDocument(const TFilePath &path) {
#ifdef _WIN32
  int ret = (int)ShellExecuteW(0, L"open", path.getWideString().c_str(), 0, 0,
                               SW_SHOWNORMAL);
  if (ret <= 32) {
    return false;
    throw TSystemException(path, "Can't open");
  }
  return true;
#else
  string cmd = "open ";
  string thePath(::to_string(path));
  UINT pos = 0, count = 0;
  // string newPath;
  char newPath[2048];

  while (pos < thePath.size()) {
    char c                         = thePath[pos];
    if (c == ' ') newPath[count++] = '\\';

    newPath[count++] = c;
    ++pos;
  }
  newPath[count] = 0;

  cmd = cmd + string(newPath);
  system(cmd.c_str());
  return true;
#endif
}

#else

#include <windows.h>

void TSystem::sleep(TINT64 delay) { Sleep((DWORD)delay); }

// gestire gli errori con GetLastError?
void TSystem::deleteFile(const TFilePath &fp) { assert(false); }

void TSystem::rmDirTree(const TFilePath &path) { assert(false); }

//------------------------------------------------------------

//------------------------------------------------------------

#endif  // TNZCORE_LIGHT

//--------------------------------------------------------------

TSystemException::TSystemException(const TFilePath &fname, int err)
    : m_fname(fname)
    , m_err(err)
    , m_msg(L"")

{}

//--------------------------------------------------------------

TSystemException::TSystemException(const TFilePath &fname,
                                   const std::string &msg)
    : m_fname(fname), m_err(-1), m_msg(::to_wstring(msg)) {}
//--------------------------------------------------------------

TSystemException::TSystemException(const TFilePath &fname, const wstring &msg)
    : m_fname(fname), m_err(-1), m_msg(msg) {}

//--------------------------------------------------------------

TSystemException::TSystemException(const std::string &msg)
    : m_fname(""), m_err(-1), m_msg(::to_wstring(msg)) {}
//--------------------------------------------------------------

TSystemException::TSystemException(const wstring &msg)
    : m_fname(""), m_err(-1), m_msg(msg) {}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Web.Http.Filters;
using Abp.Web;

namespace Abp.WebApi.Controllers.Dynamic.Builders
{
    /// <summary>
    /// This interface is used to define a dynamic api controllers.
    /// </summary>
    /// <typeparam name="T">Type of the proxied object</typeparam>
    public interface IBatchApiControllerBuilder<T>
    {
        /// <summary>
        /// Used to filter types.
        /// </summary>
        /// <param name="predicate">Predicate to filter types</param>
        IBatchApiControllerBuilder<T> Where(Func<Type, bool> predicate);

        /// <summary>
        /// The adds Action filters for the Dynamic Controller.
        /// </summary>
        /// <param name="filters"> The filters. </param>
        /// <returns>The current Controller Builder </returns>
        IBatchApiControllerBuilder<T> WithFilters(params IFilter[] filters);

        /// <summary>
        /// Selects service name for a controller.
        /// </summary>
        /// <param name="serviceNameSelector">Service name selector</param>
        /// <returns></returns>
        IBatchApiControllerBuilder<T> WithServiceName(Func<Type, string> serviceNameSelector);

        /// <summary>
        /// Use conventional Http Verbs by method names.
        /// By default, it uses <see cref="HttpVerb.Post"/> for all actions.
        /// </summary>
        /// <returns>The current Controller Builder</returns>
        IBatchApiControllerBuilder<T> WithConventionalVerbs();

        /// <summary>
        /// Builds the controller.
        /// This method must be called at last of the build operation.
        /// </summary>
        void Build();
    }
}


text:
%% play_music: Play music using a certain generator.
function play_music(generator)
    f_sample = 8e3;
    [t, music] = make_music(generator, f_sample);
    sound(music, f_sample);


text:
PLH::Detour* duckHook = new PLH::Detour;
PLH::Detour* finishUnduckHook = new PLH::Detour;

bool g_bShouldDoubleDuck = false;

void __fastcall hkDuck( CCSGameMovement* thisptr )
{
	using fn_t = void( __thiscall* )(CCSGameMovement*);

	if ( thisptr->player->GetFlags() & FL_ONGROUND )
	{
		static bool bCanDoubleDuck = false;

		if ( thisptr->player->GetFlags() & FL_DUCKING )
			bCanDoubleDuck = false;
		else if ( thisptr->mv->m_nButtons & IN_DUCK )
			bCanDoubleDuck = true;
		else if ( thisptr->player->m_Local.m_bDucking && bCanDoubleDuck )
			g_bShouldDoubleDuck = true;
	}

	duckHook->GetOriginal<fn_t>()(thisptr);
}

void __fastcall hkFinishUnDuck( CCSGameMovement* thisptr )
{
	using fn_t = void( __thiscall* )(CCSGameMovement*);

	if ( g_bShouldDoubleDuck )
	{
		Vector origin = thisptr->mv->GetAbsOrigin();
		origin.z += DOUBLEDUCK_JUMP_HEIGHT;

		trace_t trace;

		// Let's just use MASK_PLAYERSOLID, getting player mask inside the arguments fucks up the stack (pushes false)
		UTIL_TraceHull( thisptr->mv->GetAbsOrigin(), origin, VEC_HULL_MIN, VEC_HULL_MAX, MASK_PLAYERSOLID, thisptr->player, COLLISION_GROUP_PLAYER_MOVEMENT, &trace );

		if ( !trace.startsolid || trace.fraction != 1.0f )
			thisptr->mv->SetAbsOrigin( origin );

		g_bShouldDoubleDuck = false;
	}

	finishUnduckHook->GetOriginal<fn_t>()(thisptr);
}

void HookCSGameMovement()
{
	duckHook->SetupHook( (BYTE*) Addresses::Duck, (BYTE*) &hkDuck );
	duckHook->Hook();

	finishUnduckHook->SetupHook( (BYTE*) Addresses::FinishUnDuck, (BYTE*) &hkFinishUnDuck );
	finishUnduckHook->Hook();
}


text:
package edu.jhu.pacaya.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public abstract class Prm implements Serializable {

    private static final long serialVersionUID = 1L;

    //TODO: Move this to a utility class.
    @SuppressWarnings("unchecked")
    public static <T extends Serializable> T clone(T prm) {
        try {
            ByteArrayOutputStream strOut = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(strOut);
            out.writeObject(prm);
            out.close();
            ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(strOut.toByteArray()));
            T prm2 = (T) in.readObject();
            in.close();
            return prm2;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

}


text:
<?php

/**
 * This file contains all the configuration options for the PHP Telegram Bot.
 *
 * It is based on the configuration array of the PHP Telegram Bot Manager project.
 *
 * Simply adjust all the values that you need and extend where necessary.
 *
 * Options marked as [Manager Only] are only required if you use `manager.php`.
 *
 * For a full list of all options, check the Manager Readme:
 * https://github.com/php-telegram-bot/telegram-bot-manager#set-extra-bot-parameters
 */

return [
    // Add you bot's API key and name
    'api_key'      => 'your:bot_api_key',
    'bot_username' => 'username_bot', // Without "@"

    // [Manager Only] Secret key required to access the webhook
    'secret'       => 'super_secret',

    // When using the getUpdates method, this can be commented out
    'webhook'      => [
        'url' => 'https://your-domain/path/to/hook-or-manager.php',
        // Use self-signed certificate
        // 'certificate'     => __DIR__ . '/path/to/your/certificate.crt',
        // Limit maximum number of connections
        // 'max_connections' => 5,
    ],

    // All command related configs go here
    'commands'     => [
        // Define all paths for your custom commands
        // DO NOT PUT THE COMMAND FOLDER THERE. IT WILL NOT WORK.
        // Copy each needed Commandfile into the CustomCommand folder and uncommend the Line 49 below
        'paths'   => [
            // __DIR__ . '/CustomCommands',
        ],
        // Here you can set any command-specific parameters
        'configs' => [
            // - Google geocode/timezone API key for /date command (see DateCommand.php)
            // 'date'    => ['google_api_key' => 'your_google_api_key_here'],
            // - OpenWeatherMap.org API key for /weather command (see WeatherCommand.php)
            // 'weather' => ['owm_api_key' => 'your_owm_api_key_here'],
            // - Payment Provider Token for /payment command (see Payments/PaymentCommand.php)
            // 'payment' => ['payment_provider_token' => 'your_payment_provider_token_here'],
        ],
    ],

    // Define all IDs of admin users
    'admins'       => [
        // 123,
    ],

    // Enter your MySQL database credentials
    // 'mysql'        => [
    //     'host'     => '127.0.0.1',
    //     'user'     => 'root',
    //     'password' => 'root',
    //     'database' => 'telegram_bot',
    // ],

    // Logging (Debug, Error and Raw Updates)
    // 'logging'  => [
    //     'debug'  => __DIR__ . '/php-telegram-bot-debug.log',
    //     'error'  => __DIR__ . '/php-telegram-bot-error.log',
    //     'update' => __DIR__ . '/php-telegram-bot-update.log',
    // ],

    // Set custom Upload and Download paths
    'paths'        => [
        'download' => __DIR__ . '/Download',
        'upload'   => __DIR__ . '/Upload',
    ],

    // Requests Limiter (tries to prevent reaching Telegram API limits)
    'limiter'      => [
        'enabled' => true,
    ],
];


text:
import { cloneVNode } from "inferno-clone-vnode";
import { Component } from "inferno";

type PopoverChildProps = {
  children?: React.Node
};

export class PopoverContainer extends Component {
  render() {
    const children = this.props.children.map(c => {
      if (!c.props) {
        return c;
      } else if (c.props.popoverButton) {
        const updatedPopover = cloneVNode(c, {
          onClick: this.props.toggleOpen
        });
        const buttonChildren =
          updatedPopover.children != null
            ? updatedPopover.children.map(c2 => {
                if (c2.props && c2.props.popover)
                  return cloneVNode(c2, {
                    visible: this.props.isOpen
                  });
                else return c2;
              })
            : [];

        updatedPopover.children = buttonChildren;
        return updatedPopover;
      } else if (c.props.popover) {
        return cloneVNode(c, {
          visible: this.props.isOpen
        });
      } else {
        return c;
      }
    });

    return <>{children}</>;
  }
}

export const PopoverTitle = ({ children }: PopoverChildProps) =>
{children}
;

export const PopoverContent = ({ children }: PopoverChildProps) =>
{children}
;

type PopoverProps = {
  children?: React.Node,
  visible?: boolean,
  direction: "top" | "bottom" | "left" | "right"
};

export const Popover = ({ children, visible, direction }: PopoverProps) => {
  if (!visible) return null;

  return (
    <div className={`fade popover ${direction} in`}>

      {children}

  );
};


text:
package org.elinker.core.api.service

import org.elinker.core.api.auth.TokenAuthentication
import scala.concurrent.ExecutionContext.Implicits.global

/**
 * Created by nilesh on 16/12/2014.
 */
trait ApiService extends MentionApiService with TokenAuthentication {
  val apiRoute =
    pathPrefix("api") {
      authenticate(authenticateToken) {
        user =>
          mentionRoute(user)
      }
    }
}


text:
.. module:: sqlalchemy.orm

.. _query_api_toplevel:

=========
Query API
=========

This section presents the API reference for the ORM :class:`.Query` object.  For a walkthrough
of how to use this object, see :ref:`ormtutorial_toplevel`.

The Query Object
================

:class:`~.Query` is produced in terms of a given :class:`~.Session`, using the :meth:`~.Session.query` method::

    q = session.query(SomeMappedClass)

Following is the full interface for the :class:`.Query` object.

.. autoclass:: sqlalchemy.orm.query.Query
   :members:

ORM-Specific Query Constructs
=============================

.. autofunction:: sqlalchemy.orm.aliased

.. autoclass:: sqlalchemy.orm.util.AliasedClass

.. autoclass:: sqlalchemy.orm.util.AliasedInsp

.. autoclass:: sqlalchemy.orm.query.Bundle
    :members:

.. autoclass:: sqlalchemy.util.KeyedTuple
    :members: keys, _fields, _asdict

.. autoclass:: sqlalchemy.orm.strategy_options.Load
    :members:

.. autofunction:: join

.. autofunction:: outerjoin

.. autofunction:: with_parent


text:
require "conduit/braintree/parsers/create_customer"

module Conduit::Driver::Braintree
  class FindCustomer::Parser < CreateCustomer::Parser
  end
end


text:
"""Provide a base HTML template variable for population with appropriate
statistics in the report.py module.
"""

base_template = \
"""

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="../main.css">

<title>Analysis Report on {header}</title>

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            Toggle navigation

          </button>
          Contents

Invalid/Empty

Numerical

String

Enum

Analysis Report on {header}

Invalid Rows ({len_invalid_rows})

These rows contain either too many or too few columns.

            {invalid_rows}

Empty Columns ({len_empty_columns})

These columns contain >= 90% empty values.

            {empty_columns}

Column Analysis (Based on {len_columns} rows)

Numerical

                    Column
                    Min
                    Max
                    Mode
                    Mean
                    Median Low
                    Median
                    Median High
                    Most Common (Top 5)

                {numerical_analysis}

String

                    Column
                    Mode
                    Most Common (Top 5)

                {string_analysis}

Enumerated

                    Column
                    Mode
                    Most Common (Top 5)

                {enum_analysis}

"""


text:
package org.apache.sling.distribution.resources.impl;

import org.apache.sling.distribution.agent.DistributionAgent;
import org.apache.sling.distribution.agent.DistributionAgentException;
import org.apache.sling.distribution.agent.DistributionAgentState;
import org.apache.sling.distribution.component.impl.DistributionComponent;
import org.apache.sling.distribution.component.impl.DistributionComponentKind;
import org.apache.sling.distribution.component.impl.DistributionComponentProvider;
import org.apache.sling.distribution.log.DistributionLog;
import org.apache.sling.distribution.packaging.DistributionPackageInfo;
import org.apache.sling.distribution.packaging.impl.DistributionPackageUtils;
import org.apache.sling.distribution.queue.DistributionQueue;
import org.apache.sling.distribution.queue.DistributionQueueException;
import org.apache.sling.distribution.queue.DistributionQueueItem;
import org.apache.sling.distribution.queue.DistributionQueueItemStatus;
import org.apache.sling.distribution.queue.DistributionQueueState;
import org.apache.sling.distribution.resources.DistributionResourceTypes;
import org.apache.sling.distribution.resources.impl.common.SimplePathInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Extended service resource provider exposes children resources like .../agents/agentName/queues/queueName/queueItem
 */
public class ExtendedDistributionServiceResourceProvider extends DistributionServiceResourceProvider {

    private static final String QUEUES_PATH = "queues";
    private static final String LOG_PATH = "log";
    private static final String STATUS_PATH = "status";

    private static final int MAX_QUEUE_DEPTH = 100;

    public ExtendedDistributionServiceResourceProvider(String kind,
                                               DistributionComponentProvider componentProvider,
                                               String resourceRoot) {
        super(kind, componentProvider, resourceRoot);
    }

    @Override
    protected Map<String,Object> getChildResourceProperties(DistributionComponent component, String childResourceName) {
        DistributionComponentKind kind =  component.getKind();
        if (kind.equals(DistributionComponentKind.AGENT)) {
            DistributionAgent agent = (DistributionAgent) component.getService();

            if (agent != null && childResourceName != null) {
                if (childResourceName.startsWith(QUEUES_PATH)) {
                    SimplePathInfo queuePathInfo = SimplePathInfo.parsePathInfo(QUEUES_PATH, childResourceName);
                    Map<String, Object> result = getQueueProperties(agent, queuePathInfo);
                    return result;
                } else if (childResourceName.startsWith(LOG_PATH)) {
                    Map<String, Object> result = new HashMap<String, Object>();
                    result.put(SLING_RESOURCE_TYPE, DistributionResourceTypes.LOG_RESOURCE_TYPE);
                    DistributionLog distributionLog = agent.getLog();

                    result.put(ADAPTABLE_PROPERTY_NAME, distributionLog);

                    return result;
                } else if (childResourceName.startsWith(STATUS_PATH)) {
                    Map<String, Object> result = new HashMap<String, Object>();
                    DistributionAgentState agentState = agent.getState();

                    result.put("state", agentState.name());
                    return result;
                }

            }
        }
        return null;
    }

    @Override
    protected Iterable<String> getChildResourceChildren(DistributionComponent component, String childResourceName) {

        DistributionComponentKind kind =  component.getKind();
        if (kind.equals(DistributionComponentKind.AGENT)) {
            DistributionAgent agent = (DistributionAgent) component.getService();

            if (agent != null) {
                if (childResourceName == null) {
                    List<String> nameList = new ArrayList<String>();
                    nameList.add(QUEUES_PATH);
                    nameList.add(LOG_PATH);
                    nameList.add(STATUS_PATH);

                    return nameList;
                }
            }
        }
        return null;
    }

    private Map<String,Object> getQueueProperties(DistributionAgent agent, SimplePathInfo queueInfo) {
        if (queueInfo.isRoot()) {
            Map<String, Object> result = new HashMap<String, Object>();

            List<String> nameList = new ArrayList<String>();
            for (String name : agent.getQueueNames()) {
                nameList.add(name);
            }
            result.put(ITEMS, nameList.toArray(new String[nameList.size()]));

            result.put(SLING_RESOURCE_TYPE, DistributionResourceTypes.AGENT_QUEUE_LIST_RESOURCE_TYPE);
            return result;
        } else if (queueInfo.isMain()) {
            String queueName = queueInfo.getMainResourceName();
            Map<String, Object> result = new HashMap<String, Object>();

            try {
                DistributionQueue queue = agent.getQueue(queueName);

                result.put(SLING_RESOURCE_TYPE, DistributionResourceTypes.AGENT_QUEUE_RESOURCE_TYPE);

                result.put("state", queue.getState().name());
                result.put("empty", queue.isEmpty());
                result.put("itemsCount", queue.getItemsCount());

                List<String> nameList = new ArrayList<String>();
                for (DistributionQueueItem item : queue.getItems(0, MAX_QUEUE_DEPTH)) {
                    nameList.add(item.getId());
                }
                result.put(ITEMS, nameList.toArray(new String[0]));
                result.put(ADAPTABLE_PROPERTY_NAME, queue);

            } catch (DistributionAgentException e) {
                // do nothing

            }

            return result;

        } else if (queueInfo.isChild()) {
            String queueName = queueInfo.getMainResourceName();
            Map<String, Object> result = new HashMap<String, Object>();

            try {
                DistributionQueue queue = agent.getQueue(queueName);
                String itemId = queueInfo.getChildResourceName();

                DistributionQueueItem item = queue.getItem(itemId);
                DistributionPackageInfo packageInfo = DistributionPackageUtils.fromQueueItem(item);

                if (item != null) {

                    result.put(SLING_RESOURCE_TYPE, DistributionResourceTypes.AGENT_QUEUE_ITEM_RESOURCE_TYPE);
                    result.put("id", item.getId());
                    result.put("paths", packageInfo.getPaths());
                    result.put("action", packageInfo.getRequestType());
                    result.put("type", packageInfo.getType());

                    DistributionQueueItemStatus status = queue.getStatus(item);
                    result.put("attempts", status.getAttempts());
                    result.put("time", status.getEntered().getTime());
                    result.put("state", status.getItemState().name());

                }
            } catch (DistributionAgentException e) {
                // do nothing

            } catch (DistributionQueueException e) {
                // do nothing
            }
            return result;
        }

        return null;
    }

}


text:
package org.edx.mobile.user;

import android.content.Context;
import android.support.annotation.NonNull;

import com.google.inject.Inject;

import org.edx.mobile.event.AccountUpdatedEvent;
import org.edx.mobile.task.Task;

import de.greenrobot.event.EventBus;

public abstract class UpdateAccountTask extends
        Task<Account> {

    @Inject
    private UserAPI userAPI;

    @NonNull
    private final String username;

    @NonNull
    private final String field;

    @NonNull
    private final Object value;

    public UpdateAccountTask(@NonNull Context context, @NonNull String username, @NonNull String field, @NonNull Object value) {
        super(context);
        this.username = username;
        this.field = field;
        this.value = value;
    }

    public Account call() throws Exception {
        final Account updatedAccount = userAPI.updateAccount(username, field, value);
        EventBus.getDefault().post(new AccountUpdatedEvent(updatedAccount));
        return updatedAccount;
    }
}


text:
package org.jboss.pnc.integration;

import com.jayway.restassured.http.ContentType;
import com.jayway.restassured.response.Response;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.pnc.AbstractTest;
import org.jboss.pnc.integration.assertions.ResponseAssertion;
import org.jboss.pnc.integration.client.ArtifactRestClient;
import org.jboss.pnc.integration.deployments.Deployments;
import org.jboss.pnc.rest.endpoint.ArtifactEndpoint;
import org.jboss.pnc.rest.provider.ArtifactProvider;
import org.jboss.pnc.rest.restmodel.ArtifactRepositoryRest;
import org.jboss.pnc.rest.restmodel.ArtifactRest;
import org.jboss.pnc.test.category.ContainerTest;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.invoke.MethodHandles;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

import static org.assertj.core.api.Assertions.assertThat;
import static com.jayway.restassured.RestAssured.given;
import static org.jboss.pnc.integration.env.IntegrationTestEnv.getHttpPort;

/**
 *
 * @author jmichalo
 */
@RunWith(Arquillian.class)
@Category(ContainerTest.class)
public class ArtifactRestTest extends AbstractTest {

    public static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

    public static final String ARTIFACT_REST_SPECIFIC_ENDPOINT = "/pnc-rest/rest/artifacts/%d";

    private static AtomicBoolean isInitialized = new AtomicBoolean();

    private static ArtifactRest artifactRest1;
    private static ArtifactRest artifactRest2;
    private static ArtifactRest artifactRest3;

    private static ArtifactRestClient artifactRestClient;

    @Deployment(testable = false)
    public static EnterpriseArchive deploy() {
        EnterpriseArchive enterpriseArchive = Deployments.baseEar();
        WebArchive restWar = enterpriseArchive.getAsType(WebArchive.class, REST_WAR_PATH);
        restWar.addClass(ArtifactRestTest.class);
        restWar.addClass(ArtifactProvider.class);
        restWar.addClass(ArtifactEndpoint.class);
        restWar.addClass(ArtifactRestClient.class);
        restWar.addClass(ArtifactRepositoryRest.class);
        restWar.addClass(ArtifactRest.class);

        logger.info(enterpriseArchive.toString(true));
        return enterpriseArchive;
    }

    @Before
    public void before() {
        if (artifactRestClient == null) {
            artifactRestClient = new ArtifactRestClient();
        }
        if (!isInitialized.getAndSet(true)) {
            List<ArtifactRest> arts = artifactRestClient.all().getValue();
            logger.debug(arts.toString());
            // look at org.jboss.pnc.demo.data.DatabaseDataInitializer builtArtifacts 1,2,3
            // artifact number 3 is 5th initialized
            artifactRest1 = arts.get(0);
            artifactRest2 = arts.get(1);
            artifactRest3 = arts.get(4);
        }
    }

    @Test
    public void testGetAllArtifacts() {
        Response response = given().headers(testHeaders)
                .contentType(ContentType.JSON).port(getHttpPort()).when()
                .get(ArtifactRestClient.ARTIFACT_REST_ENDPOINT);

        ResponseAssertion.assertThat(response).hasStatus(200);
        ResponseAssertion.assertThat(response).hasJsonValueNotNullOrEmpty("content[0]");
    }

    @Test
    public void testGetAllArfifactsWithMd5() {
        Response response = given().headers(testHeaders)
                .contentType(ContentType.JSON).port(getHttpPort()).when()
                .queryParam("md5",artifactRest1.getMd5())
                .get(ArtifactRestClient.ARTIFACT_REST_ENDPOINT);
        ResponseAssertion.assertThat(response).hasStatus(200);

        //artifacts 1 and 2 have same MD5
        List<Map<String,Object>> list = response.jsonPath().getList("content");
        assertThat(list)
                .hasSize(2)
                .allSatisfy(map -> {
                    assertThat(map).containsKey("id");
                    assertThat(map.get("id")).isIn(artifactRest1.getId(), artifactRest2.getId());
                    }
                );
    }

    @Test
    public void testGetAllArfifactsWithSha1() {
        Response response = given().headers(testHeaders)
                .contentType(ContentType.JSON).port(getHttpPort()).when()
                .queryParam("sha1",artifactRest2.getSha1())
                .get(ArtifactRestClient.ARTIFACT_REST_ENDPOINT);
        ResponseAssertion.assertThat(response).hasStatus(200);

        //artifacts 2 and 3 have same SHA1
        List<Map<String,Object>> list = response.jsonPath().getList("content");
        assertThat(list)
                .hasSize(2)
                .allSatisfy(map -> {
                    assertThat(map).containsKey("id");
                    assertThat(map.get("id")).isIn(artifactRest2.getId(), artifactRest3.getId());
                    }
                );
    }

    @Test
    public void testGetAllArfifactsWithSha256() {
        Response response = given().headers(testHeaders)
                .contentType(ContentType.JSON).port(getHttpPort()).when()
                .queryParam("sha256",artifactRest1.getSha256())
                .get(ArtifactRestClient.ARTIFACT_REST_ENDPOINT);
        ResponseAssertion.assertThat(response).hasStatus(200);

        //artifacts 1 and 3 have same SHA256
        List<Map<String,Object>> list = response.jsonPath().getList("content");
        assertThat(list)
                .hasSize(2)
                .allSatisfy(map -> {
                    assertThat(map).containsKey("id");
                    assertThat(map.get("id")).isIn(artifactRest1.getId(), artifactRest3.getId());
                    }
                );
    }

    @Test
    public void testGetAllArfifactsWithMd5AndSha1() {
        Response response = given().headers(testHeaders)
                .contentType(ContentType.JSON).port(getHttpPort()).when()
                .queryParam("sha1",artifactRest2.getSha1())
                .queryParam("md5", artifactRest2.getMd5())
                .get(ArtifactRestClient.ARTIFACT_REST_ENDPOINT);
        ResponseAssertion.assertThat(response).hasStatus(200);

        List<Map<String,Object>> list = response.jsonPath().getList("content");
        assertThat(list).hasSize(1);
        ResponseAssertion.assertThat(response).hasJsonValueEqual("content[0].id",artifactRest2.getId());
    }

    @Test
    public void testGetAllArfifactsWithMd5AndSha256() {
        Response response = given().headers(testHeaders)
                .contentType(ContentType.JSON).port(getHttpPort()).when()
                .queryParam("sha256",artifactRest1.getSha256())
                .queryParam("md5", artifactRest1.getMd5())
                .get(ArtifactRestClient.ARTIFACT_REST_ENDPOINT);
        ResponseAssertion.assertThat(response).hasStatus(200);

        List<Map<String,Object>> list = response.jsonPath().getList("content");
        assertThat(list).hasSize(1);
        ResponseAssertion.assertThat(response).hasJsonValueEqual("content[0].id",artifactRest1.getId());
    }

    @Test
    public void testGetAllArfifactsWithSha1AndSha256() {
        Response response = given().headers(testHeaders)
                .contentType(ContentType.JSON).port(getHttpPort()).when()
                .queryParam("sha256",artifactRest3.getSha256())
                .queryParam("sha1", artifactRest3.getSha1())
                .get(ArtifactRestClient.ARTIFACT_REST_ENDPOINT);
        ResponseAssertion.assertThat(response).hasStatus(200);

        List<Map<String,Object>> list = response.jsonPath().getList("content");
        assertThat(list).hasSize(1);
        ResponseAssertion.assertThat(response).hasJsonValueEqual("content[0].id",artifactRest3.getId());
    }

    @Test
    public void testGetSpecificArtifact() {
        Response response = given().headers(testHeaders)
                .contentType(ContentType.JSON).port(getHttpPort()).when()
                .get(String.format(ARTIFACT_REST_SPECIFIC_ENDPOINT, artifactRest1.getId()));

        ResponseAssertion.assertThat(response).hasStatus(200);
        ResponseAssertion.assertThat(response).hasJsonValueEqual("content.id",artifactRest1.getId());

    }
}


text:
package org.yeastrc.proxl.import_xml_to_db_runner_pgm.manager_thread;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import org.slf4j.LoggerFactory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.yeastrc.proxl.import_xml_to_db_runner_pgm.config.ImporterRunnerConfigData;
import org.yeastrc.proxl.import_xml_to_db_runner_pgm.config.ProcessImporterRunnerConfigFile;
import org.yeastrc.proxl.import_xml_to_db_runner_pgm.constants.RunControlFileConstants;
import org.yeastrc.proxl.import_xml_to_db_runner_pgm.get_import_and_process_thread.GetImportAndProcessThread;
import org.yeastrc.proxl.import_xml_to_db_runner_pgm.main.ImporterRunnerMain;

/**
 *
 *
 */
public class ManagerThread extends Thread {

	private static final String className = ManagerThread.class.getSimpleName();

	private static final Logger log = LoggerFactory.getLogger( ManagerThread.class);

	private static final int WAIT_TIME_FOR_MANAGER_THREAD_TO_EXIT_IN_SECONDS = 10;

//	private static final int WAIT_TIME_FOR_CLIENT_STATUS_UPDATE_THREAD_TO_EXIT_IN_SECONDS = 10;

	//  For shutdown wait for current import to finish
	private static final int WAIT_TIME_FOR_GET_IMPORT_THREAD_TO_EXIT_IN_SECONDS = 30 * 60; // X minutes

	private static final int WAIT_TIME_FOR_CHECK_RUN_CONTROL_FILE_IN_SECONDS = 10;

	private static final String GET_IMPORT_AND_PROCESS_THREAD = "GetImportAndProcessThread";

	private volatile boolean keepRunning = true;
	private volatile boolean stopProcessingNextImport = false;
	private volatile boolean stopProxlRunImporterProgram = false;;

	private int maxTrackingRecordPriorityToRetrieve;
	private ImporterRunnerMain importerRunnerMain;
	private volatile GetImportAndProcessThread getImportAndProcessThread;
	private int getImportAndProcessThreadCounter = 2;  // used if need to replace the thread

//	private volatile ClientStatusUpdateThread clientStatusUpdateThread;
//
//	private int clientStatusUpdateThreadCounter = 2;  // used if need to replace the thread
	/**
	 * default Constructor
	 */
	public ManagerThread() {
		//  Set a name for the thread
		String threadName = className;
		setName( threadName );
		init();
	}
	/**
	 * Constructor
	 * @param s
	 */
	public ManagerThread( String s ) {
		super(s);
		init();
	}
	/**
	 *
	 */
	private void init() {
	}
	/**
	 * awaken thread to process request
	 */
	public void awaken() {
		synchronized (this) {
			notify();
		}
	}
	/* (non-Javadoc)
	 * @see java.lang.Thread#run()
	 */
	@Override
	public void run() {
		log.debug( "run() called " );
		//		ClassLoader thisClassLoader = this.getClass().getClassLoader();
		//		this.setContextClassLoader( thisClassLoader );
		try {
			createClientControlFile();
//			clientStatusUpdateThread = new ClientStatusUpdateThread();
//
//			clientStatusUpdateThread.start();
			getImportAndProcessThread = new GetImportAndProcessThread( GET_IMPORT_AND_PROCESS_THREAD /* name */ );
			getImportAndProcessThread.setMaxTrackingRecordPriorityToRetrieve( maxTrackingRecordPriorityToRetrieve );
			getImportAndProcessThread.start();

			runProcessLoop( );  // Call main processing loop that will run while keepRunning == true

			if ( stopProcessingNextImport ) {
				File clientControlFile = null;
				FileWriter clientControlFileWriter = null;
				try {
					clientControlFile = new File( RunControlFileConstants.CLIENT_RUN_CONTROL_FILENAME );
					log.info( "ClientControlFile: filename = '" + RunControlFileConstants.CLIENT_RUN_CONTROL_FILENAME + "' filepath is = '" + clientControlFile.getAbsolutePath() + "'." );
					clientControlFileWriter = new FileWriter( clientControlFile );
					if ( stopProxlRunImporterProgram ) {
						log.info( "ClientControlFile: Changing file contents to: \n" + RunControlFileConstants.CLIENT_RUN_CONTROL_CURRENT_IMPORT_COMPLETE_SHUTDOWN_PROCEEDING );
						clientControlFileWriter.write( RunControlFileConstants.CLIENT_RUN_CONTROL_CURRENT_IMPORT_COMPLETE_SHUTDOWN_PROCEEDING );
					} else {
						log.info( "ClientControlFile: Changing file contents to: \n" + RunControlFileConstants.CLIENT_RUN_CONTROL_CURRENT_IMPORT_COMPLETE_READY_FOR_SHUTDOWN );
						clientControlFileWriter.write( RunControlFileConstants.CLIENT_RUN_CONTROL_CURRENT_IMPORT_COMPLETE_READY_FOR_SHUTDOWN );
					}
				} catch (Throwable e) {
					log.error( "Exception in createClientControlFile(): ", e );
				} finally {
					if ( clientControlFileWriter != null ) {
						try {
							clientControlFileWriter.close();
						} catch (Throwable e) {
							log.error( "Exception in createClientControlFile(): calling clientControlFileWriter.close(); ", e );
						}
					}
				}
				if ( stopProxlRunImporterProgram ) {
					//  Remove PID file since requested via run control file to shut down program
					removePIDFileOnShutdownViaRunControlFile();
				}
				if ( stopProxlRunImporterProgram ) {
					importerRunnerMain.stopMainThread();
				}
			}
		} catch (Throwable e) {
			log.error( "Exception in run(): ", e );
		}
		log.debug( "About to exit run()" );
//		LogOpenFiles.logOpenFiles( LogOpenFiles.LIST_FILES_TRUE );
		log.info( "exitting run()" );
	}

	/**
	 * Main Processing loop
	 */
	private void runProcessLoop() {
		while ( keepRunning ) {
//			if ( log.isDebugEnabled() ) {
//				log.debug( "Top of loop in 'runProcessLoop()', waitTime in microseconds = " + waitTime );
//			}
			try {
				replaceWorkerThreadsIfDead();
				if ( keepRunning && ! stopProcessingNextImport ) {
					checkForStopProcessingJobsRequest();
				}
				if ( keepRunning ) {
					synchronized (this) {
						try {
							int waitTimeInSeconds = WAIT_TIME_FOR_CHECK_RUN_CONTROL_FILE_IN_SECONDS; // ClientConfigDTO.getSingletonInstance().getSleepTimeCheckingControlFile();
							wait( waitTimeInSeconds * 1000 ); //  wait for notify() call or timeout, in milliseconds
						} catch (InterruptedException e) {
							log.warn( "wait( waitTime ) was interrupted." );
						}
					}
				}
				// this.getId();
			} catch (Throwable e) {
				log.error( "Exception in runProcessLoop(): ", e );
			}
		}
	}

	/**
	 *
	 */
	private void replaceWorkerThreadsIfDead() {

		if ( keepRunning ) {  //  only do if keep running is true

			//  check health of heartbeatThread, replace thread if dead
//			if ( ! clientStatusUpdateThread.isAlive() ) {
//				ClientStatusUpdateThread oldHeartbeatThread = clientStatusUpdateThread;
//				clientStatusUpdateThread = new ClientStatusUpdateThread(  );
//				clientStatusUpdateThread.setName( ClientStatusUpdateThread.className + "_" + clientStatusUpdateThreadCounter );
//				clientStatusUpdateThreadCounter++;
//				log.error( "HeartbeatThread thread '" + oldHeartbeatThread.getName() + "' is dead.  Replacing it with HeartbeatThread thread '" + clientStatusUpdateThread.getName() + "'."  );
//				clientStatusUpdateThread.start();
//			}

			//  check health of getImportAndProcessThread, replace thread if dead
			if ( ! getImportAndProcessThread.isAlive() ) {
				GetImportAndProcessThread oldGetImportAndProcessThread = getImportAndProcessThread;
				getImportAndProcessThread = new GetImportAndProcessThread(  GET_IMPORT_AND_PROCESS_THREAD + "_" + getImportAndProcessThreadCounter /* name */  );
				getImportAndProcessThreadCounter += 1;
//				ThreadsHolderSingleton.getInstance().setGetJobThread( getJobThread );
				log.error( "GetImportAndProcessThread thread '" + oldGetImportAndProcessThread.getName() + "' is dead.  Replacing it with GetImportAndProcessThread thread '" + getImportAndProcessThread.getName() + "'."  );
				getImportAndProcessThread.start();
			}
		}
	}

	/**
	 *
	 */
	private void createClientControlFile() {

		File clientControlFile = null;
		BufferedWriter clientControlFileWriter = null;
		try {
			clientControlFile = new File( RunControlFileConstants.CLIENT_RUN_CONTROL_FILENAME );
			@SuppressWarnings("unused")
			String clientControlFileWithPathString = clientControlFile.getCanonicalPath();
			log.info( "ClientControlFile: filename = '" + RunControlFileConstants.CLIENT_RUN_CONTROL_FILENAME + "' filepath is = '" + clientControlFile.getAbsolutePath() + "'." );
			clientControlFileWriter = new BufferedWriter( new FileWriter( clientControlFile ) );
			if ( log.isDebugEnabled() ) {
				StringBuilder contentsSB = new StringBuilder( 2000);
				for ( String line : RunControlFileConstants.CLIENT_RUN_CONTROL_INITIAL_CONTENTS ) {
					contentsSB.append( line  );
					contentsSB.append( "\n" );
				}
				log.debug( "ClientControlFile: Changing file contents to: \n" + contentsSB );
			}
			for ( String line : RunControlFileConstants.CLIENT_RUN_CONTROL_INITIAL_CONTENTS ) {
				clientControlFileWriter.append( line  );
				clientControlFileWriter.newLine();
			}
		} catch (Throwable e) {
			log.error( "Exception in createClientControlFile(): ", e );
		} finally {
			if ( clientControlFileWriter != null ) {
				try {
					clientControlFileWriter.close();
				} catch (Throwable e) {
					log.error( "Exception in createClientControlFile(): calling clientControlFileWriter.close(); ", e );
				}
			}
		}
	}

	/**
	 * Check if the control file has been updated to indicate that a "stop" has been requested
	 */
	private void checkForStopProcessingJobsRequest() {

		File clientControlFile = null;
		BufferedReader clientControlFileReader = null;
		BufferedWriter clientControlFileWriter = null;
		try {
			clientControlFile = new File( RunControlFileConstants.CLIENT_RUN_CONTROL_FILENAME );
			clientControlFileReader = new BufferedReader( new FileReader( clientControlFile ) );
			String inputLine = clientControlFileReader.readLine();
			if ( inputLine != null ) {
				boolean stopRequestedLocal = false;
				String stopRequestType = null;
				if ( inputLine.startsWith(  RunControlFileConstants.CLIENT_RUN_CONTROL_STOP_JOBS_TEXT ) ) {
					stopRequestedLocal = true;
					stopRequestType = RunControlFileConstants.CLIENT_RUN_CONTROL_STOP_JOBS_TEXT;
					log.info(  "File '" + RunControlFileConstants.CLIENT_RUN_CONTROL_FILENAME
							+ "' has been changed to specify to stop processing new imports and keep running when the current import is complete."
							+ "  All threads except for the main thread will be dead when the current import is complete." );
				} else if ( inputLine.startsWith(  RunControlFileConstants.CLIENT_RUN_CONTROL_STOP_RUN_TEXT ) ) {
					stopProxlRunImporterProgram = true;
					stopRequestedLocal = true;
					stopRequestType = RunControlFileConstants.CLIENT_RUN_CONTROL_STOP_RUN_TEXT;
					log.info(  "File '" + RunControlFileConstants.CLIENT_RUN_CONTROL_FILENAME
							+ "' has been changed to specify to stop processing new imports and exit when the current import is complete." );
				}
				if ( stopRequestedLocal ) {
					stopProcessingNextImport = true;
					log.info( "ClientControlFile: Adding to file contents : \n" + RunControlFileConstants.CLIENT_RUN_CONTROL_STOP_REQUEST_ACCEPTED );
					log.info( "ClientControlFile: filename = '" + RunControlFileConstants.CLIENT_RUN_CONTROL_FILENAME + "' filepath is = '" + clientControlFile.getAbsolutePath() + "'." );
					clientControlFileWriter = new BufferedWriter( new FileWriter( clientControlFile, true /* append */ ) );
					for ( String line : RunControlFileConstants.CLIENT_RUN_CONTROL_STOP_REQUEST_ACCEPTED ) {
						clientControlFileWriter.append( line  );
						clientControlFileWriter.newLine();
					}
					try {
						clientControlFileReader.close();
						clientControlFileReader = null;
					} catch (Throwable e) {
						log.error( "Exception in checkForStopProcessingJobsRequest(): calling clientControlFileReader.close(); ", e );
					}
					processStopProcessingNewImportsRequest( stopRequestType );
				}
			}
		} catch (Throwable e) {
			log.error( "Exception in checkForStopProcessingJobsRequest(): ", e );
		} finally {
			if ( clientControlFileReader != null ) {
				try {
					clientControlFileReader.close();
				} catch (Throwable e) {
					log.error( "Exception in checkForStopProcessingJobsRequest(): calling clientControlFileReader.close(); ", e );
				}
			}
			if ( clientControlFileWriter != null ) {
				try {
					clientControlFileWriter.close();
				} catch (Throwable e) {
					log.error( "Exception in checkForStopProcessingJobsRequest(): calling clientControlFileWriter.close(); ", e );
				}
			}
		}
	}

	/**
	 * Process the "stop" request from the control file.
	 */
	private void processStopProcessingNewImportsRequest( String stopRequestType ) {

		keepRunning = false;  // Set thread of the current object to exit main processing loop.
		//  call getImportAndProcessThread.stopRunningAfterProcessingImport();
		if ( getImportAndProcessThread != null ) {
			try {
				getImportAndProcessThread.stopRunningAfterProcessingImport();
			} catch (Throwable e) {
				log.error( "In processStopProcessingNewImportsRequest(): call to getImportAndProcessThread.stopRunningAfterProcessingImport() threw Throwable " + e.toString(), e );
			}
		} else {
			log.info( "In processStopProcessingNewImportsRequest(): getImportAndProcessThread == null" );
		}
		waitForGetImportAndProcessThread();
	}

	/**
	 * Called on a separate thread when a shutdown request comes from the operating system.
	 * If this is not heeded, the process may be killed by the operating system after some time has passed ( controlled by the operating system )
	 */
	public void shutdown() {

		log.debug( "shutdown() called " );
		//  Update DB that process has received shut down request.
//		if ( clientStatusUpdateThread != null ) {
//
//			clientStatusUpdateThread.shutdown();
//		}
		//  call getImportAndProcessThread.shutdown();
		if ( getImportAndProcessThread != null ) {
			try {
				getImportAndProcessThread.shutdown();
			} catch (Throwable e) {
				log.error( "In processStopProcessingNewImportsRequest(): call to getImportAndProcessThread.shutdown() threw Throwable " + e.toString(), e );
			}
		} else {
			log.info( "In processStopProcessingNewImportsRequest(): getImportAndProcessThread == null" );
		}
		keepRunning = false;  // Set thread of the current object to exit main processing loop.
		awaken();  // send notify() to to the thread of the current object to start it so it will exit.
		boolean managerThreadExited = false;
		while ( ! managerThreadExited ) {
			try {  // wait for thread of the current object to die, so it won't start any threads to replace the threads that will be setup to die next.
				this.join( WAIT_TIME_FOR_MANAGER_THREAD_TO_EXIT_IN_SECONDS * 1000 );
			} catch (Throwable e) {
				log.error( "In processStopRetrievingJobsRequest(): call to this.shutdown() threw Throwable " + e.toString(), e );
			}
			if ( this.isAlive() ) {
//				log.warn( "The thread 'managerThread' has not exited in the allocated time of "
//						+ WAIT_TIME_FOR_MANAGER_THREAD_TO_EXIT_IN_SECONDS
//						+ " seconds.  The wait for 'managerThread' to exit will be repeated with the same wait time." );
			} else {
				managerThreadExited = true;
			}
		}
		waitForGetImportAndProcessThread();
		//  TODO   Update process status in DB to about to shut down or shut down
	}

	/**
	 * wait For GetImportAndProcessThread To Complete
	 */
	private void waitForGetImportAndProcessThread () {

		log.warn( "INFO: waitForGetImportAndProcessThread(): wait for getImportAndProcessThread to complete, call getImportAndProcessThread.join() " );
		// wait for getImportAndProcessThread to complete
		if ( getImportAndProcessThread != null ) {
//			boolean getJobThreadExited = false;
//			while ( ! getJobThreadExited ) {
				try {
					getImportAndProcessThread.join( WAIT_TIME_FOR_GET_IMPORT_THREAD_TO_EXIT_IN_SECONDS * 1000 );
				} catch (InterruptedException e) {
					log.info( "In waitForGetJobThreadToComplete(): call to getJobThread.join() threw InterruptedException " + e.toString(), e );
				}
				if ( getImportAndProcessThread.isAlive() ) {
					log.error( "The thread 'getImportAndProcessThread' has not exited in the allocated time of "
							+ WAIT_TIME_FOR_GET_IMPORT_THREAD_TO_EXIT_IN_SECONDS
							+ " seconds.  The thread 'getJobThread' will not be waited for any further." );
//					log.error( "The thread 'getJobThread' has not exited in the allocated time of "
//							+ WAIT_TIME_FOR_GET_JOB_THREAD_TO_EXIT_IN_SECONDS
//							+ " seconds.  The wait for 'getJobThread' to exit will be repeated with the same wait time." );
				} else {
//					getJobThreadExited = true;
				}
//			}
		} else {
			log.warn( "INFO: In waitForGetImportAndProcessThread(): getImportAndProcessThread == null" );
		}
		log.warn( "INFO: waitForGetImportAndProcessThread():  getImportAndProcessThread IS complete, called getImportAndProcessThread.join() " );
	}

	/**
	 *
	 */
	private void removePIDFileOnShutdownViaRunControlFile() {

		String importerPidFileWithPath = ImporterRunnerConfigData.getImporterPidFileWithPath();

		if ( StringUtils.isNotEmpty( importerPidFileWithPath ) ) {
			try {
				File importerPidFileWithPath_File = new File( importerPidFileWithPath );
				if ( ! importerPidFileWithPath_File.exists() ) {
					log.warn( "INFO: PID file configured, but not found so do not delete it."
							+ " Config file property name: '"
							+ ProcessImporterRunnerConfigFile.PROPERTY_NAME__IMPORTER_PID_FILE_WITH_PATH
							+ "'"
							+ ", PID File: " + importerPidFileWithPath);
					return; // EARLY EXIT
				}
				if ( ! importerPidFileWithPath_File.delete() ) {
					log.error( "PID file configured, but failed to delete it.  NO Exception. "
							+ " Config file property name: '"
							+ ProcessImporterRunnerConfigFile.PROPERTY_NAME__IMPORTER_PID_FILE_WITH_PATH
							+ "'"
							+ ", PID File: " + importerPidFileWithPath );
					return; // EARLY EXIT
				}
				log.warn( "INFO: PID file configured so deleted it."
						+ " Config file property name: '"
						+ ProcessImporterRunnerConfigFile.PROPERTY_NAME__IMPORTER_PID_FILE_WITH_PATH
						+ "'"
						+ ", PID File: " + importerPidFileWithPath);
			} catch ( Throwable t ) {
				log.error( "PID file configured, but failed to delete it.  Exception. "
						+ " Config file property name: '"
						+ ProcessImporterRunnerConfigFile.PROPERTY_NAME__IMPORTER_PID_FILE_WITH_PATH
						+ "'"
						+ ", PID File: " + importerPidFileWithPath
						,
						t );
				//  EAT Exception
			}
		}
	}

	public ImporterRunnerMain getImporterRunnerMain() {
		return importerRunnerMain;
	}
	public void setImporterRunnerMain(ImporterRunnerMain importerRunnerMain) {
		this.importerRunnerMain = importerRunnerMain;
	}
	public int getMaxTrackingRecordPriorityToRetrieve() {
		return maxTrackingRecordPriorityToRetrieve;
	}
	public void setMaxTrackingRecordPriorityToRetrieve(
			int maxTrackingRecordPriorityToRetrieve) {
		this.maxTrackingRecordPriorityToRetrieve = maxTrackingRecordPriorityToRetrieve;
	}
}


text:
This strategy renders a select field with all the available polymophic models that may be related as options, in option groups per model class.

Note that this is only usable for sets of models that are guaranteed to be small.

It submits a model key that may be stored with the [RelationSingleMorph store strategy](../FormFieldStoreStrategies/RelationSingleMorph.md).

To be used for `MorphTo` relations.
Data is retrieved and stored as `<model class>:<model key>` combination.

## Options

It is generally not necessary to set options for this strategy if the related model is part of the CMS.
In any case these options may still be overridden to specificy specific reference behavior.

- `models` (array, associative, keyed by model class FQN)
    Set this to configure which models are selectable in the dropdown or the autocomplete search results.
    If the model is not present as a key in this list, its instances will not be selectable
    and no references will be retrieved for autocomplete searches.
    See the [RelationSingleMorph store strategy](../FormFieldStoreStrategies/RelationSingleMorph.md) for more information about nested model reference information.

- `source` (string)
    If not set, the model's default reference source is used (if it is part of the CMS).
    Otherwise, the model's key will be used.

- `strategy` (string)
    Strategy identifier for a [model reference strategy](../Strategies.md#model-reference-strategies). The `source` value is used for this strategy.
    If not set, the model's default reference strategy is used (if it is part of the CMS).
    Otherwise, the model's key will be displayed.
    This determines how the related models are referenced as displayed options.

- `context_strategy` (string)
    Strategy identifier for a [repository context strategy](../Strategies.md#repository-context-strategies).
     If not set, the model's default `context_strategy` is used (if it is part of the CMS).
     Otherwise, only `withoutGlobalScopes()` will be applied to the query.
     This allows you to (un)restrict the models that will be available as options for the select input.

- `sort_direction` (string: `asc` or `desc`)
    This determines the direction the displayed model references will be sorted in. This will only work for table columns directly belonging to the model, or columns on related translation models.
    Other sources are currently not supported, and will not be used for sorting references.

- `parameters` (array, associative)
    Optional parameters that may be required by the `strategy`.

 ```php
     'options' => [

         // The source column(s) to use for the reference strategy
         'source' => 'title',

         // The reference strategy to use.
         'strategy' => SomeReferenceStrategyClass::class,

         // The query context strategy to use.
         'context_strategy' => 'OnlyActive',

         // Sorting direction for references displayed.
         `sort_direction` => 'desc',
     ]
 ```


text:
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.

package com.google.api.ads.admanager.jaxws.v202208;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *             Represents a technology entity that can be targeted.
 *
 *
 *
Java class for Technology complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="Technology">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="id" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
 *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Technology", propOrder = {
    "id",
    "name"
})
@XmlSeeAlso({
    OperatingSystem.class,
    BrowserLanguage.class,
    DeviceCategory.class,
    MobileCarrier.class,
    MobileDevice.class,
    BandwidthGroup.class,
    DeviceManufacturer.class,
    OperatingSystemVersion.class,
    DeviceCapability.class,
    Browser.class,
    MobileDeviceSubmodel.class
})
public class Technology {

    protected Long id;
    protected String name;

    /**
     * Gets the value of the id property.
     *
     * @return
     *     possible object is
     *     {@link Long }
     *
     */
    public Long getId() {
        return id;
    }

    /**
     * Sets the value of the id property.
     *
     * @param value
     *     allowed object is
     *     {@link Long }
     *
     */
    public void setId(Long value) {
        this.id = value;
    }

    /**
     * Gets the value of the name property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getName() {
        return name;
    }

    /**
     * Sets the value of the name property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setName(String value) {
        this.name = value;
    }

}


text:
/**
 * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
 * @version v25.1.0
 * @link http://www.ag-grid.com/
 * @license MIT
 */
/**
 * These variables are lazy loaded, as otherwise they try and get initialised when we are loading
 * unit tests and we don't have references to window or document in the unit tests
 * from http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
 */
var isSafari;
var isIE;
var isEdge;
var isChrome;
var isFirefox;
var isIOS;
export function isBrowserIE() {
    if (isIE === undefined) {
        isIE = /*@cc_on!@*/ false || !!document.documentMode; // At least IE6
    }
    return isIE;
}
export function isBrowserEdge() {
    if (isEdge === undefined) {
        isEdge = !isBrowserIE() && !!window.StyleMedia;
    }
    return isEdge;
}
export function isBrowserSafari() {
    if (isSafari === undefined) {
        // taken from https://stackoverflow.com/a/23522755/1388233
        isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
    }
    return isSafari;
}
export function isBrowserChrome() {
    if (isChrome === undefined) {
        var win = window;
        isChrome = (!!win.chrome && (!!win.chrome.webstore || !!win.chrome.runtime)) ||
            (/Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor));
    }
    return isChrome;
}
export function isBrowserFirefox() {
    if (isFirefox === undefined) {
        var win = window;
        isFirefox = typeof win.InstallTrigger !== 'undefined';
    }
    return isFirefox;
}
export function isIOSUserAgent() {
    if (isIOS === undefined) {
        // taken from https://stackoverflow.com/a/58064481/1388233
        isIOS = (/iPad|iPhone|iPod/.test(navigator.platform) ||
            // eslint-disable-next-line
            (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)) &&
            !window.MSStream;
    }
    return isIOS;
}
export function getTabIndex(el) {
    if (!el) {
        return null;
    }
    var numberTabIndex = el.tabIndex;
    var tabIndex = el.getAttribute('tabIndex');
    if (isBrowserIE() && numberTabIndex === 0 && tabIndex === null) {
        var map = {
            a: true,
            body: true,
            button: true,
            frame: true,
            iframe: true,
            img: true,
            input: true,
            isindex: true,
            object: true,
            select: true,
            textarea: true
        };
        return map[el.nodeName.toLowerCase()] === true ? '0' : null;
    }
    if (numberTabIndex === -1 && (tabIndex === null || (tabIndex === '' && !isBrowserFirefox()))) {
        return null;
    }
    return numberTabIndex.toString();
}
export function getMaxDivHeight() {
    if (!document.body) {
        return -1;
    }
    var res = 1000000;
    // FF reports the height back but still renders blank after ~6M px
    var testUpTo = navigator.userAgent.toLowerCase().match(/firefox/) ? 6000000 : 1000000000;
    var div = document.createElement('div');
    document.body.appendChild(div);
    while (true) {
        var test_1 = res * 2;
        div.style.height = test_1 + 'px';
        if (test_1 > testUpTo || div.clientHeight !== test_1) {
            break;
        }
        else {
            res = test_1;
        }
    }
    document.body.removeChild(div);
    return res;
}
export function getScrollbarWidth() {
    var body = document.body;
    var div = document.createElement('div');
    div.style.width = div.style.height = '100px';
    div.style.opacity = '0';
    div.style.overflow = 'scroll';
    div.style.msOverflowStyle = 'scrollbar'; // needed for WinJS apps
    div.style.position = 'absolute';
    body.appendChild(div);
    var width = div.offsetWidth - div.clientWidth;
    // if width is 0 and client width is 0, means the DOM isn't ready
    if (width === 0 && div.clientWidth === 0) {
        return null;
    }
    // remove divs
    if (div.parentNode) {
        div.parentNode.removeChild(div);
    }
    return width;
}
/** @deprecated */
export function hasOverflowScrolling() {
    var prefixes = ['webkit', 'moz', 'o', 'ms'];
    var div = document.createElement('div');
    var body = document.getElementsByTagName('body')[0];
    var found = false;
    var p;
    body.appendChild(div);
    div.setAttribute('style', prefixes.map(function (prefix) { return "-" + prefix + "-overflow-scrolling: touch"; }).concat('overflow-scrolling: touch').join(';'));
    var computedStyle = window.getComputedStyle(div);
    if (computedStyle.overflowScrolling === 'touch') {
        found = true;
    }
    if (!found) {
        for (var _i = 0, prefixes_1 = prefixes; _i < prefixes_1.length; _i++) {
            p = prefixes_1[_i];
            if (computedStyle[p + "OverflowScrolling"] === 'touch') {
                found = true;
                break;
            }
        }
    }
    if (div.parentNode) {
        div.parentNode.removeChild(div);
    }
    return found;
}
/**
 * Gets the document body width
 * from: http://stackoverflow.com/questions/1038727/how-to-get-browser-width-using-javascript-code
 * @returns {number}
 */
export function getBodyWidth() {
    if (document.body) {
        return document.body.clientWidth;
    }
    if (window.innerHeight) {
        return window.innerWidth;
    }
    if (document.documentElement && document.documentElement.clientWidth) {
        return document.documentElement.clientWidth;
    }
    return -1;
}
/**
 * Gets the body height
 * from: http://stackoverflow.com/questions/1038727/how-to-get-browser-width-using-javascript-code
 * @returns {number}
 */
export function getBodyHeight() {
    if (document.body) {
        return document.body.clientHeight;
    }
    if (window.innerHeight) {
        return window.innerHeight;
    }
    if (document.documentElement && document.documentElement.clientHeight) {
        return document.documentElement.clientHeight;
    }
    return -1;
}