text:
<?php

use Sunlight\Post\PostService;
use Sunlight\Database\Database as DB;
use Sunlight\Extend;
use Sunlight\Paginator;
use Sunlight\Post\Post;
use Sunlight\Router;
use Sunlight\Settings;
use Sunlight\User;
use Sunlight\Util\UrlHelper;

defined('SL_ROOT') or exit;

if (!ctype_digit($_index->segment)) {
    $_index->notFound();
    return;
}

// nacteni dat
$id = (int) $_index->segment;
$userQuery = User::createQuery('p.author');
$query = DB::queryRow("SELECT p.*," . $userQuery['column_list'] . " FROM " . DB::table('post') . " p " . $userQuery['joins'] . " WHERE p.id=" . $id . " AND p.type=" . Post::FORUM_TOPIC . " AND p.home=" . $_page['id'] . " AND p.xhome=-1");
if ($query === false) {
    $_index->notFound();
    return;
}

// drobecek
$_index->crumbs[] = [
    'title' => $query['subject'],
    'url' => Router::topic($id, $_page['slug'])
];

// extend
$continue = true;

Extend::call('topic.before', Extend::args($output, [
    'topic' => &$query,
    'continue' => &$continue,
    'page' => $_page,
]));

if (!$continue) {
    return;
}

// atributy
$_index->title = $_page['title'] . ' ' . Settings::get('titleseparator') . ' ' . $query['subject'];
$_index->heading = $_page['title'];
$_index->url = Router::topic($id, $_page['slug']);

// priprava zpetneho odkazu
$_index->backlink = Router::page($_page['id'], $_page['slug']);
if (!$query['sticky']) {
    $_index->backlink = UrlHelper::appendParams($_index->backlink, 'page=' . Paginator::getItemPage($_page['var1'], DB::table('post'), "bumptime>" . $query['bumptime'] . " AND xhome=-1 AND type=" . Post::FORUM_TOPIC . " AND home=" . $_page['id']));
}

// sprava tematu
$topic_access = Post::checkAccess($userQuery, $query);
$topic_admin = [];

if ($topic_access) {
    if (User::hasPrivilege('locktopics')) {
        $topic_admin[] = "" . (_lang('mod.locktopic.link' . (($query['locked'] == 1) ? '2' : ''))) . "";
    }
    if (User::hasPrivilege('stickytopics')) {
        $topic_admin[] = "" . (_lang('mod.stickytopic.link' . (($query['sticky'] == 1) ? '2' : ''))) . "";
    }
    if (User::hasPrivilege('movetopics')) {
        $topic_admin[] = "" . (_lang('mod.movetopic.link')) . "";
    }
}

// vystup
$output .= "
\n";
$output .= "
" . _lang('posts.topic') . ": " . $query['subject'] . "
\n";
$output .= PostService::renderPost($query, $userQuery, [
    'post_link' => false,
    'allow_reply' => false,
    'extra_actions' => $topic_admin,
]);
$output .= "
\n";

// odpovedi
$output .= PostService::render(
    PostService::RENDER_FORUM_TOPIC,
    $_page['id'],
    [
        Settings::get('commentsperpage'),
        User::checkPublicAccess($_page['var3']),
        $_page['var2'],
        $id
    ],
    $query['locked'] == 1
);


text:
from django.conf import settings
from django.utils.translation import ugettext_lazy as _

SOFTBUTTERFLY = getattr(settings, 'SOFTBUTTERFLY', None)
MAILAUTH = SOFTBUTTERFLY.get('MAILAUTH', {})

APP_VERBOSE_NAME = MAILAUTH.get('APP_VERBOSE_NAME', _("Authentication and Authorization"))
REGISTER_PROXY_AUTH_GROUP_MODEL = MAILAUTH.get('REGISTER_PROXY_AUTH_GROUP_MODEL', True)
ENABLE_USERNAME = MAILAUTH.get('ENABLE_USERNAME', True)

redpajama_set_name: RedPajamaGithub


text:
package com.intellij.openapi.vfs.impl.jar;

import com.intellij.openapi.diagnostic.LogUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.io.BufferExposingByteArrayInputStream;
import com.intellij.openapi.util.io.FileAttributes;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.JarFile;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.reference.SoftReference;
import com.intellij.util.ArrayUtil;
import com.intellij.util.TimedReference;
import gnu.trove.THashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.Reference;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class JarHandlerBase {
  private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vfs.impl.jar.JarHandlerBase");

  private static final long DEFAULT_LENGTH = 0L;
  private static final long DEFAULT_TIMESTAMP = -1L;

  private final TimedReference<JarFile> myJarFile = new TimedReference<JarFile>(null);
  private Reference<Map<String, EntryInfo>> myRelPathsToEntries = new SoftReference<Map<String, EntryInfo>>(null);
  private final Object lock = new Object();

  protected final String myBasePath;

  protected static class EntryInfo {
    protected final boolean isDirectory;
    protected final String shortName;
    protected final EntryInfo parent;

    public EntryInfo(@NotNull String shortName, final EntryInfo parent, final boolean directory) {
      this.shortName = shortName;
      this.parent = parent;
      isDirectory = directory;
    }
  }

  public JarHandlerBase(@NotNull String path) {
    myBasePath = path;
  }

  protected void clear() {
    synchronized (lock) {
      myRelPathsToEntries = null;
      myJarFile.set(null);
    }
  }

  public File getMirrorFile(@NotNull File originalFile) {
    return originalFile;
  }

  @Nullable
  public JarFile getJar() {
    JarFile jar = myJarFile.get();
    if (jar == null) {
      synchronized (lock) {
        jar = myJarFile.get();
        if (jar == null) {
          jar = createJarFile();
          if (jar != null) {
            myJarFile.set(jar);
          }
        }
      }
    }
    return jar;
  }

  @Nullable
  protected JarFile createJarFile() {
    final File originalFile = getOriginalFile();
    try {
      @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") final ZipFile zipFile = new ZipFile(getMirrorFile(originalFile));

      class MyJarEntry implements JarFile.JarEntry {
        private final ZipEntry myEntry;

        MyJarEntry(ZipEntry entry) {
          myEntry = entry;
        }

        public ZipEntry getEntry() {
          return myEntry;
        }

        @Override
        public String getName() {
          return myEntry.getName();
        }

        @Override
        public long getSize() {
          return myEntry.getSize();
        }

        @Override
        public long getTime() {
          return myEntry.getTime();
        }

        @Override
        public boolean isDirectory() {
          return myEntry.isDirectory();
        }
      }

      return new JarFile() {
        @Override
        public JarFile.JarEntry getEntry(String name) {
          try {
            ZipEntry entry = zipFile.getEntry(name);
            if (entry != null) {
              return new MyJarEntry(entry);
            }
          }
          catch (RuntimeException e) {
            LOG.warn("corrupted: " + zipFile.getName(), e);
          }
          return null;
        }

        @Override
        public InputStream getInputStream(JarFile.JarEntry entry) throws IOException {
          return zipFile.getInputStream(((MyJarEntry)entry).myEntry);
        }

        @Override
        public Enumeration<? extends JarFile.JarEntry> entries() {
          return new Enumeration<JarEntry>() {
            private final Enumeration<? extends ZipEntry> entries = zipFile.entries();

            @Override
            public boolean hasMoreElements() {
              return entries.hasMoreElements();
            }

            @Override
            public JarEntry nextElement() {
              try {
                ZipEntry entry = entries.nextElement();
                if (entry != null) {
                  return new MyJarEntry(entry);
                }
              }
              catch (RuntimeException e) {
                LOG.warn("corrupted: " + zipFile.getName(), e);
              }
              return null;
            }
          };
        }

        @Override
        public ZipFile getZipFile() {
          return zipFile;
        }
      };
    }
    catch (IOException e) {
      LOG.warn(e.getMessage() + ": " + originalFile.getPath(), e);
      return null;
    }
  }

  @NotNull
  protected File getOriginalFile() {
    return new File(myBasePath);
  }

  @NotNull
  private static EntryInfo getOrCreate(@NotNull String entryName, boolean isDirectory, @NotNull Map<String, EntryInfo> map) {
    EntryInfo info = map.get(entryName);
    if (info == null) {
      int idx = entryName.lastIndexOf('/');
      final String parentEntryName = idx > 0 ? entryName.substring(0, idx) : "";
      String shortName = idx > 0 ? entryName.substring(idx + 1) : entryName;
      if (".".equals(shortName)) return getOrCreate(parentEntryName, true, map);

      info = new EntryInfo(shortName, getOrCreate(parentEntryName, true, map), isDirectory);
      map.put(entryName, info);
    }

    return info;
  }

  @NotNull
  public String[] list(@NotNull final VirtualFile file) {
    synchronized (lock) {
      EntryInfo parentEntry = getEntryInfo(file);

      Set<String> names = new HashSet<String>();
      for (EntryInfo info : getEntriesMap().values()) {
        if (info.parent == parentEntry) {
          names.add(info.shortName);
        }
      }

      return ArrayUtil.toStringArray(names);
    }
  }

  protected EntryInfo getEntryInfo(@NotNull VirtualFile file) {
    synchronized (lock) {
      String parentPath = getRelativePath(file);
      return getEntryInfo(parentPath);
    }
  }

  public EntryInfo getEntryInfo(@NotNull String parentPath) {
    return getEntriesMap().get(parentPath);
  }

  @NotNull
  protected Map<String, EntryInfo> getEntriesMap() {
    synchronized (lock) {
      Map<String, EntryInfo> map = SoftReference.dereference(myRelPathsToEntries);

      if (map == null) {
        final JarFile zip = getJar();
        if (zip != null) {
          LogUtil.debug(LOG, "mapping %s", myBasePath);

          map = new THashMap<String, EntryInfo>();
          map.put("", new EntryInfo("", null, true));
          final Enumeration<? extends JarFile.JarEntry> entries = zip.entries();
          while (entries.hasMoreElements()) {
            final JarFile.JarEntry entry = entries.nextElement();
            final String name = entry.getName();
            final boolean isDirectory = StringUtil.endsWithChar(name, '/');
            getOrCreate(isDirectory ? name.substring(0, name.length() - 1) : name, isDirectory, map);
          }

          myRelPathsToEntries = new SoftReference<Map<String, EntryInfo>>(map);
        }
        else {
          map = Collections.emptyMap();
        }
      }

      return map;
    }
  }

  @NotNull
  private String getRelativePath(@NotNull VirtualFile file) {
    final String path = file.getPath().substring(myBasePath.length() + 1);
    return StringUtil.startsWithChar(path, '/') ? path.substring(1) : path;
  }

  @Nullable
  private JarFile.JarEntry convertToEntry(@NotNull VirtualFile file) {
    String path = getRelativePath(file);
    final JarFile jar = getJar();
    return jar == null ? null : jar.getEntry(path);
  }

  public long getLength(@NotNull final VirtualFile file) {
    final JarFile.JarEntry entry = convertToEntry(file);
    synchronized (lock) {
      return entry == null ? DEFAULT_LENGTH : entry.getSize();
    }
  }

  @NotNull
  public InputStream getInputStream(@NotNull final VirtualFile file) throws IOException {
    return new BufferExposingByteArrayInputStream(contentsToByteArray(file));
  }

  @NotNull
  public byte[] contentsToByteArray(@NotNull final VirtualFile file) throws IOException {
    final JarFile.JarEntry entry = convertToEntry(file);
    if (entry == null) {
      return ArrayUtil.EMPTY_BYTE_ARRAY;
    }
    synchronized (lock) {
      final JarFile jar = getJar();
      assert jar != null : file;

      final InputStream stream = jar.getInputStream(entry);
      assert stream != null : file;

      try {
        return FileUtil.loadBytes(stream, (int)entry.getSize());
      }
      finally {
        stream.close();
      }
    }
  }

  public long getTimeStamp(@NotNull final VirtualFile file) {
    if (file.getParent() == null) return getOriginalFile().lastModified(); // Optimization
    final JarFile.JarEntry entry = convertToEntry(file);
    synchronized (lock) {
      return entry == null ? DEFAULT_TIMESTAMP : entry.getTime();
    }
  }

  public boolean isDirectory(@NotNull final VirtualFile file) {
    if (file.getParent() == null) return true; // Optimization
    synchronized (lock) {
      final String path = getRelativePath(file);
      final EntryInfo info = getEntryInfo(path);
      return info == null || info.isDirectory;
    }
  }

  public boolean exists(@NotNull final VirtualFile fileOrDirectory) {
    if (fileOrDirectory.getParent() == null) {
      // Optimization. Do not build entries if asked for jar root existence.
      return myJarFile.get() != null || getOriginalFile().exists();
    }

    return getEntryInfo(fileOrDirectory) != null;
  }

  @Nullable
  public FileAttributes getAttributes(@NotNull final VirtualFile file) {
    final JarFile.JarEntry entry = convertToEntry(file);
    synchronized (lock) {
      final EntryInfo entryInfo = getEntryInfo(getRelativePath(file));
      if (entryInfo == null) return null;
      final long length = entry != null ? entry.getSize() : DEFAULT_LENGTH;
      final long timeStamp = entry != null ? entry.getTime() : DEFAULT_TIMESTAMP;
      return new FileAttributes(entryInfo.isDirectory, false, false, false, length, timeStamp, false);
    }
  }
}


text:
class CreateTalks < ActiveRecord::Migration
  def change
    create_table :talks do |t|
      t.string :name
      t.integer :author_id
      t.integer :club_id
      t.text :description
      t.timestamps
    end
  end
end


text:
FILE(REMOVE_RECURSE
  "CMakeFiles/gtest_dll.dir/src/gtest-all.cc.o"
  "CMakeFiles/gtest_dll.dir/src/gtest_main.cc.o"
  "libgtest_dll.pdb"
  "libgtest_dll.dylib"
)

# Per-language clean rules from dependency scanning.
FOREACH(lang CXX)
  INCLUDE(CMakeFiles/gtest_dll.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)


text:
package core

import (
	"crypto/aes"
	"crypto/cipher"
)

type crypto struct {
	key []byte
	gcm cipher.AEAD
}

func createCrypto(key []byte) (*crypto, error) {
	aesBlock, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	gcm, err := cipher.NewGCM(aesBlock)
	if err != nil {
		return nil, err
	}
	return &crypto{key: key,
		gcm: gcm}, nil
}

func (c *crypto) Encrypt(message []byte) []byte {
	/*TODO I don't yet understand all this stuff, look into message structure etc!*/
	return c.gcm.Seal(nil, []byte("noncehere!"), message, message)
}

func (c *crypto) Decrypt(message []byte) ([]byte, error) {
	return nil, nil
}


text:
package org.sourcepit.b2.directory.parser.internal.project;

import java.io.File;

import javax.inject.Inject;
import javax.inject.Named;

import org.sourcepit.b2.model.module.Project;
import org.sourcepit.common.utils.props.PropertiesSource;

/**
 * @author Bernd
 */
@Named
public class ProjectParser {
   @Inject
   private ProjectDetector detector;

   @Inject
   private ProjectPreprocessor preprocessor;

   @Inject
   private ProjectModelInitializer modelInitializer;

   public Project parse(File directory, PropertiesSource properties) {
      final Project project = detector.detect(directory, properties);
      if (project != null) {
         preprocessor.preprocess(project, properties);
         modelInitializer.initialize(project, properties);
      }
      return project;
   }
}


text:
//HK_REFLECTION_PARSER_EXCLUDE_FILE

#ifndef HK_CHECK_DETERMINISM_UTIL_H
#define HK_CHECK_DETERMINISM_UTIL_H

#include <Common/Base/Config/hkConfigThread.h>
#include <Common/Base/Thread/JobQueue/hkJobQueue.h>

// Uncomment the next line if you want to check the engine for determinism
//#define HK_WANT_DETERMINISM_CHECKS

#if defined(HK_WANT_DETERMINISM_CHECKS)
	#define HK_ON_DETERMINISM_CHECKS_WANTED(CODE) CODE
		#define	HK_ENABLE_DETERMINISM_CHECKS
#else
	#define HK_ON_DETERMINISM_CHECKS_WANTED(CODE)
#endif

#if defined(HK_ENABLE_DETERMINISM_CHECKS)
	#include <Common/Base/Thread/Thread/hkThreadLocalData.h>
	#include <Common/Base/System/Io/IStream/hkIStream.h>
	#include <Common/Base/System/Io/OStream/hkOStream.h>

	#define HK_ON_DETERMINISM_CHECKS_ENABLED(CODE) CODE

	// Uncomment the following define to get a report of the total size of the data checked aggregated by ID at then end
	// of the first run of each demo.
	//#define HK_DETERMINISM_CHECK_SIZES
	#if defined HK_DETERMINISM_CHECK_SIZES
		#include <Common/Base/Container/PointerMap/hkPointerMap.h>
	#endif
#else
	#define HK_ON_DETERMINISM_CHECKS_ENABLED(CODE)
#endif

class hkIstream;
class hkOstream;
class hkCriticalSection;
class hkMemoryTrack;

/// This is a small helper class allowing to check the determinism of
/// a system. Basically it works by running an application twice:
/// First a binary logfile is created and the second time the system
/// checks against this binary logfile.
///
/// Usage quick start:
///
/// You activate writing or reading+checking with startWriteMode() or startCheckMode() functions from anywhere in your app.
/// Similarly you call finish() when you're done with writing or reading+checking.
///
/// Then for every single thread that you're intending to use the utility in, you must call workerThreadStartFrame() before
/// and workerThreadFinishFrame() after any use of the utility.
///
/// The workerThreadStartFrame() function takes a parameter isPrimaryWorkerThread. This can be true for only one thread.
/// That 'marked' thread is allowed to used the utility immediately. This is used when the primary thread performs special
/// operations besides the jobs taken off of the job queue.
///
/// Other threads must register a job first. The primary thread can also register jobs, when it starts working
/// in parallel to other threads.
///
/// Why do we need to register jobs? When multithreading, before the utility is used, you must tell it what that thread
/// is about to start doing -- you must do that, as the same thread may be given different jobs on each consecutive run.
/// You do that by calling registerAndStartJob() and finishJob(). Those functions take a job ID which must be unique
/// across all jobs performed during that one frame.
///
/// Soo, only now after starting, and before finishing a job. You can use the hkCheckDeterminismUtil::checkMt() function.
struct HK_EXPORT_COMMON hkCheckDeterminismUtil
{
	public:

		// Frame-unique ID
		//
		// This id has to be unique for a job in the scope of a single frame.
		// It is made up of the hkpSimulationIslands's unite tag, job type, job task's sequential id, and one another counter (hmm).
		// See hkCheckDeterminismUtil::Fuid hkpDynamicsJob::getFuid().
		struct Fuid
		{
			public:
				HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_BASE_CLASS, hkCheckDeterminismUtil::Fuid );

				static Fuid& getZeroFuid();
				static Fuid& getCanceledFuid();

				HK_FORCE_INLINE hkBool32 operator==(const Fuid& f);
				HK_FORCE_INLINE hkBool32 operator!=(const Fuid& f);
				HK_FORCE_INLINE void setPackedJobId(const struct hkJob& job);
				HK_FORCE_INLINE void setPackedJobId(hkJobType jobType, hkJobSubType jobSubType);
				HK_FORCE_INLINE hkUint16 getPackedJobId() const { return m_jobPackedId; }

			public:
				hkUint32 m_0;
				hkUint16 m_jobPackedId; // use getJobFuid() to initialize for this value
				hkUint16 m_2;
				hkUint32 m_3, m_4;
		};

		/// Controls the behavior when a determinism check fails.
		enum CheckFailMode
		{
			/// Break with an error. Default mode.
			CHECK_FAIL_MODE_BREAK,

			/// Store a copy of the current reference data and return. Calling didLastCheckFail() will return true.
			/// Useful if you want to add some code to visualize the data.
			CHECK_FAIL_MODE_CONTINUE
		};

	public:

		HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_BASE_CLASS, hkCheckDeterminismUtil );

		 hkCheckDeterminismUtil();
		~hkCheckDeterminismUtil();

		static HK_FORCE_INLINE hkCheckDeterminismUtil& HK_CALL getInstance();
		static HK_FORCE_INLINE void HK_CALL createInstance();
		static HK_FORCE_INLINE void HK_CALL destroyInstance();

		/// Sets this utility to write mode. Call at startup of your test.
		/// Make sure to call finish() at the end.
		void startWriteMode(bool stampFilename = false, const char* filename = "hkDeterminismCheckfile.bin");

		/// Sets this utility to check mode. Call at startup of your test.
		/// Make sure to call finish() at the end.
		void startCheckMode(const char* filename = HK_NULL);

		/// Call this function at the end of your write/check run. This closes the open files
		void finish();

		/// Check an array, but only check the crc number of the whole array. The excluded array must have the same
		/// format as described in checkMt().
		template<typename TYPE>
		static HK_ALWAYS_INLINE void HK_CALL checkMtCrc(
			int id, const TYPE* object, int numObjects = 1, int* excluded = HK_NULL );

		/// The excluded array excludes specific bytes of the data from checking.
		/// It is an array of (offset, sizeBytes) pairs, ordered by offset, with -1 as the last element.
		/// Per example, to exclude 2 bytes at offset 12 and 1 byte at offset 15, one would pass: { 12, 2, 15, 1, -1 }
		/// as the excluded array.
		template<typename TYPE>
		static HK_FORCE_INLINE void HK_CALL checkMt(
			int id, const TYPE* object, int numObjects = 1, int* excluded = HK_NULL );

		/// Check a simple type object
		template<typename TYPE>
		static HK_FORCE_INLINE void HK_CALL checkMt( int id, const TYPE& object );

		static HK_FORCE_INLINE void HK_CALL randomizeMemory( void* data, int numBytes );

		/// Sets the values used when writing or checking the determinism log.
		/// The user may set the values used when allocating and deallocating,
		/// both when writing and when checking the determinism log. Moreover,
		/// the user can change the value used for wiping the stack memory every time
		/// one of the check functions is called in case of write and check.
		static HK_FORCE_INLINE void HK_CALL setMemoryScrubValues(
			hkUint32 heapAllocWrite, hkUint32 heapFreeWrite, hkUint32 heapAllocCheck, hkUint32 heapFreeCheck,
			hkUint32 stackWipeWrite, hkUint32 stackWipeCheck );

		/// Automatically called to wipe the stack (128 4 bytes words, 512 bytes) at the end
		/// of checkMt() and checkMtCrc(). May also be called explicitly.
		static HK_FORCE_INLINE void HK_CALL wipeStack();

		static HK_FORCE_INLINE void HK_CALL initThread();
		static HK_FORCE_INLINE void HK_CALL quitThread();

		static HK_FORCE_INLINE void HK_CALL workerThreadStartFrame(hkBool isPrimaryWorkerThread);
		static HK_FORCE_INLINE void HK_CALL workerThreadFinishFrame();

		static HK_FORCE_INLINE void HK_CALL registerAndStartJob(Fuid& jobFuid);
		static HK_FORCE_INLINE void HK_CALL finishJob(Fuid& jobFuid, hkBool skipCheck);
		static HK_FORCE_INLINE void HK_CALL cancelJob(Fuid& jobFuid);

		void flushWrite();
		void setCurrentJobFuid(Fuid jobFuid);
		static void setCurrentCheckIndex(hkUint32 checkIndex);
		static void bumpCurrentCheckIndex();
		static hkUint32 getCurrentCheckIndex();
		static Fuid getCurrentJobFuid();

		bool isNearBreakpoint(hkUint64 offset);

		/// Set the current check fail mode. See CheckFailMode.
		HK_FORCE_INLINE void setCheckFailMode(CheckFailMode checkFailMode);

		/// Returns true if the last check failed and the check fail mode is CHECK_FAIL_MODE_CONTINUE, otherwise it
		/// returns false. Calling this method clears the failure flag.
		HK_FORCE_INLINE hkBool32 didLastCheckFail();

		/// Returns an array with the last reference data that failed a check if check fail mode is
		/// CHECK_FAIL_MODE_CONTINUE.
		HK_FORCE_INLINE const hkArray<hkUint8>& getLastReferenceData() const;

	protected:

		enum Mode
		{
			MODE_IDLE,
			MODE_WRITE,
			MODE_COMPARE
		};

		/// Per thread data
		struct ThreadData
		{
			public:

				HK_FORCE_INLINE void reset();

			public:

				/// Contains the last read reference data if a check fails and the check fail mode is set to continue.
				hkArray<hkUint8> m_referenceData;

				hkIstream* m_inputStream;
				hkOstream* m_outputStream;
				void* m_jobInfoIdx;
				void* m_isPrimaryWorkerThread;
				hkUint32 m_currentJobFuid0;
				hkUint32 m_currentJobFuid1;
				hkUint32 m_currentJobFuid2;
				hkUint32 m_currentJobFuid3;
				hkUint32 m_currentCheckIndex;

				/// True if the check fail mode is set to continue and the last determinism check failed.
				hkBool m_didLastCheckFail;
		};

		struct JobInfo
		{
			HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_BASE_CLASS, hkCheckDeterminismUtil::JobInfo );
			Fuid		m_jobFuid;

			// This is the data. In multi threaded mode, the thread-local m_input/outputStreams connect to the corresponding hkArray.
			// This array is resizable, therefore it has to point to the data array.
			hkMemoryTrack* m_data; // for write

			hkBool			m_isOpen;
		};

	protected:

		/// Returns the thread data corresponding to the current hkThreadNumber.
		HK_FORCE_INLINE ThreadData& getThreadData();
		HK_FORCE_INLINE const ThreadData& getThreadData() const;

		static HK_FORCE_INLINE void HK_CALL combineRegisteredJobs();
		static HK_FORCE_INLINE void HK_CALL extractRegisteredJobs();
		static HK_FORCE_INLINE void HK_CALL clearRegisteredJobs();

		static void HK_CALL initThreadImpl();
		static void HK_CALL quitThreadImpl();

		void workerThreadStartFrameImpl(hkBool isPrimaryWorkerThread);
		void workerThreadFinishFrameImpl();

		static HK_NEVER_INLINE void HK_CALL wipeStackImpl( hkUint32 value );

		void  registerAndStartJobImpl(Fuid& jobFuid);
		//There is an MT check in finish job; If the job was defered due to running out of memory, skipCheck must be true
		void  finishJobImpl(Fuid& jobFuid, hkBool skipCheck);
		void  cancelJobImpl(Fuid& jobFuid);
		void  combineRegisteredJobsImpl();
		void  extractRegisteredJobsImpl();
		void  clearRegisteredJobsImpl();
		void  delayJob(const Fuid& id, bool start) const;

		// check the object of size of the object.
		// Note: the referenceObject pointer will be set to the object of the previous run, this pointer is only valid
		// if you get a breakpoint in this function call, it is pointing to garbage once this function has finished.
		// This sounds useless, but it is really handy for debugging, see checkMt.
		void checkImpl( int id, const void* object, int size, int* excluded = HK_NULL, const void** referenceObject = HK_NULL );
		void checkCrcImpl( int id, const void* object, int numBytes, int* excluded = HK_NULL);
		static void HK_CALL randomizeMemoryImpl( void* data, int numBytes );

	protected:

		ThreadData m_threadData[HK_MAX_NUM_THREADS];
		Mode m_mode;
		hkEnum<CheckFailMode, hkUint8> m_checkFailMode;
		hkUint64 m_frame;
		static hkUint32 s_randomSeed;

		hkBool m_inSingleThreadedCode;

		hkMemoryTrack* m_memoryTrack;	///< This will be created when this utility works in memory ( no file name given in the startXXX() functions)

		hkStringPtr	m_filename;
		hkIstream*	m_sharedInputStream;
		hkOstream*	m_sharedOutputStream;

		hkIstream* m_primaryWorkerThreadInputStream;
		hkOstream* m_primaryWorkerThreadOutputStream;
		int m_primaryWorkerThreadJobInfoIdx;

		hkCriticalSection* m_shared;

		hkArray<JobInfo> m_registeredJobs;

		hkBool m_delayJobs;
		hkUint32 m_delayCounter;
		hkArray<unsigned char> m_delayJobSeed;

		bool m_enableThreadTracker;
		int m_maxTheadId;
		hkArray<Fuid> m_threadTracker;

#if defined(HK_DETERMINISM_CHECK_SIZES)
		hkPointerMap<int,int> m_sizePerId;
#endif
		hkBool m_writingStFromWorker;

		friend class hkNetworkedDeterminismUtil;

		static hkUint32 s_heapAllocScrubValueWrite; // used in write mode
		static hkUint32 s_heapFreeScrubValueWrite; // used in write mode
		static hkUint32 s_heapAllocScrubValueCheck; // used in check mode
		static hkUint32 s_heapFreeScrubValueCheck; // used in check mode
		static hkUint32 s_stackScrubValueWrite; // used in write or idle mode
		static hkUint32 s_stackScrubValueCheck; // used in check mode

		static hkCheckDeterminismUtil* s_instance;
};

#if defined (HK_ENABLE_DETERMINISM_CHECKS)
	// Global variables filled in with relevant data on determinism check fails
	extern int hkCheckDeterminismUtil_id;
	extern hkReal* hkCheckDeterminismUtil_reference;
	extern hkReal* hkCheckDeterminismUtil_object;
	extern int hkCheckDeterminismUtil_size;
	extern hkReal* hkCheckDeterminismUtil_crcObject;
#endif

#include <Common/Base/DebugUtil/DeterminismUtil/hkCheckDeterminismUtil.inl>

#endif // HK_CHECK_DETERMINISM_UTIL_H

/*
 * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20140907)
 *
 * Confidential Information of Havok.  (C) Copyright 1999-2014
 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
 * Logo, and the Havok buzzsaw logo are trademarks of Havok.  Title, ownership
 * rights, and intellectual property rights in the Havok software remain in
 * Havok and/or its suppliers.
 *
 * Use of this software for evaluation purposes is subject to and indicates
 * acceptance of the End User licence Agreement for this product. A copy of
 * the license is included with this software and is also available at www.havok.com/tryhavok.
 *
 */


text:
package com.netflix.genie.web.apis.rest.v3.controllers;

import com.google.common.collect.Sets;
import com.netflix.genie.common.dto.JobRequest;
import com.netflix.genie.common.exceptions.GenieException;
import com.netflix.genie.common.exceptions.GenieNotFoundException;
import com.netflix.genie.common.exceptions.GenieServerException;
import com.netflix.genie.common.exceptions.GenieServerUnavailableException;
import com.netflix.genie.common.internal.dtos.ArchiveStatus;
import com.netflix.genie.common.internal.dtos.JobStatus;
import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException;
import com.netflix.genie.common.internal.jobs.JobConstants;
import com.netflix.genie.common.internal.util.GenieHostInfo;
import com.netflix.genie.web.agent.services.AgentRoutingService;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.ApplicationModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.ClusterModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.CommandModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.EntityModelAssemblers;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.JobExecutionModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.JobMetadataModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.JobModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.JobRequestModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.JobSearchResultModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.RootModelAssembler;
import com.netflix.genie.web.data.services.DataServices;
import com.netflix.genie.web.data.services.PersistenceService;
import com.netflix.genie.web.properties.JobsProperties;
import com.netflix.genie.web.services.AttachmentService;
import com.netflix.genie.web.services.JobDirectoryServerService;
import com.netflix.genie.web.services.JobKillService;
import com.netflix.genie.web.services.JobLaunchService;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.Mockito;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.mock.http.client.MockClientHttpResponse;
import org.springframework.mock.web.DelegatingServletOutputStream;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Stream;

/**
 * Unit tests for the Job rest controller.
 *
 * @author tgianos
 * @since 3.0.0
 */
// TODO move these tests over to JobRestControllerSpec
class JobRestControllerTest {

    //Mocked variables
    private AgentRoutingService agentRoutingService;
    private PersistenceService persistenceService;
    private String hostname;
    private RestTemplate restTemplate;
    private JobDirectoryServerService jobDirectoryServerService;
    private JobsProperties jobsProperties;
    private Environment environment;
    private JobKillService jobKillService;

    private JobRestController controller;

    private static Stream<Arguments> forwardJobOutputTestArguments() {
        final HttpHeaders headers = new HttpHeaders();
        return Stream.of(
            Arguments.of(
                HttpClientErrorException.create(HttpStatus.NOT_FOUND, "Not found", headers, null, null),
                GenieNotFoundException.class
            ),
            Arguments.of(
                HttpClientErrorException.create(HttpStatus.INTERNAL_SERVER_ERROR, "Error", headers, null, null),
                GenieException.class
            ),
            Arguments.of(
                new RuntimeException("..."),
                GenieException.class
            )
        );
    }

    @BeforeEach
    void setup() {
        this.persistenceService = Mockito.mock(PersistenceService.class);
        this.agentRoutingService = Mockito.mock(AgentRoutingService.class);
        this.hostname = UUID.randomUUID().toString();
        this.restTemplate = Mockito.mock(RestTemplate.class);
        this.jobDirectoryServerService = Mockito.mock(JobDirectoryServerService.class);
        this.jobsProperties = JobsProperties.getJobsPropertiesDefaults();
        this.environment = Mockito.mock(Environment.class);
        this.jobKillService = Mockito.mock(JobKillService.class);

        final MeterRegistry registry = Mockito.mock(MeterRegistry.class);
        final Counter counter = Mockito.mock(Counter.class);
        Mockito.when(registry.counter(Mockito.anyString())).thenReturn(counter);

        final DataServices dataServices = Mockito.mock(DataServices.class);
        Mockito.when(dataServices.getPersistenceService()).thenReturn(this.persistenceService);

        this.controller = new JobRestController(
            Mockito.mock(JobLaunchService.class),
            dataServices,
            this.createMockResourceAssembler(),
            new GenieHostInfo(this.hostname),
            this.restTemplate,
            this.jobDirectoryServerService,
            this.jobsProperties,
            registry,
            this.agentRoutingService,
            this.environment,
            Mockito.mock(AttachmentService.class),
            this.jobKillService
        );
    }

    @Test
    void wontForwardJobOutputRequestIfNotEnabled() throws GenieException, GenieCheckedException {
        this.jobsProperties.getForwarding().setEnabled(false);

        final String jobId = UUID.randomUUID().toString();
        final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
        final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

        Mockito
            .when(request.getRequestURL())
            .thenReturn(new StringBuffer("https://localhost:8443/api/v3/jobs/1234/output"));
        Mockito
            .doNothing()
            .when(this.jobDirectoryServerService)
            .serveResource(
                Mockito.eq(jobId),
                Mockito.any(URL.class),
                Mockito.anyString(),
                Mockito.eq(request),
                Mockito.eq(response)
            );
        Mockito.when(this.persistenceService.getJobStatus(jobId)).thenReturn(JobStatus.RUNNING);

        this.controller.getJobOutput(jobId, null, request, response);

        Mockito.verify(this.agentRoutingService, Mockito.never()).getHostnameForAgentConnection(jobId);
        Mockito
            .verify(this.jobDirectoryServerService, Mockito.times(1))
            .serveResource(
                Mockito.eq(jobId),
                Mockito.any(URL.class),
                Mockito.anyString(),
                Mockito.eq(request),
                Mockito.eq(response)
            );
    }

    @Test
    void wontForwardJobOutputRequestIfAlreadyForwarded() throws GenieException, GenieCheckedException {
        this.jobsProperties.getForwarding().setEnabled(true);
        final String jobId = UUID.randomUUID().toString();
        final String forwardedFrom = "https://localhost:8443/api/v3/jobs/1234/output";
        final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
        final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

        Mockito
            .doNothing()
            .when(this.jobDirectoryServerService)
            .serveResource(
                Mockito.eq(jobId),
                Mockito.any(URL.class),
                Mockito.anyString(),
                Mockito.eq(request),
                Mockito.eq(response)
            );
        Mockito.when(this.persistenceService.getJobStatus(jobId)).thenReturn(JobStatus.RUNNING);

        this.controller.getJobOutput(jobId, forwardedFrom, request, response);

        Mockito
            .verify(this.jobDirectoryServerService, Mockito.times(1))
            .serveResource(
                Mockito.eq(jobId),
                Mockito.any(URL.class),
                Mockito.anyString(),
                Mockito.eq(request),
                Mockito.eq(response)
            );
    }

    @Test
    void wontForwardJobOutputRequestIfOnCorrectHost() throws GenieException, GenieCheckedException {
        this.jobsProperties.getForwarding().setEnabled(true);
        final String jobId = UUID.randomUUID().toString();
        final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
        final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

        Mockito
            .when(request.getRequestURL())
            .thenReturn(new StringBuffer("https://" + this.hostname + "/api/v3/jobs/1234/output"));
        Mockito
            .doNothing()
            .when(this.jobDirectoryServerService)
            .serveResource(
                Mockito.eq(jobId),
                Mockito.any(URL.class),
                Mockito.anyString(),
                Mockito.eq(request),
                Mockito.eq(response)
            );

        Mockito.when(this.persistenceService.getJobArchiveStatus(jobId)).thenReturn(ArchiveStatus.PENDING);
        Mockito
            .when(this.agentRoutingService.getHostnameForAgentConnection(jobId))
            .thenReturn(Optional.of(this.hostname));

        this.controller.getJobOutput(jobId, null, request, response);

        Mockito.verify(this.agentRoutingService, Mockito.times(1)).getHostnameForAgentConnection(jobId);
        Mockito
            .verify(this.restTemplate, Mockito.never())
            .execute(
                Mockito.anyString(),
                Mockito.any(),
                Mockito.any(),
                Mockito.any(),
                Mockito.anyString(),
                Mockito.anyString()
            );
        Mockito
            .verify(this.jobDirectoryServerService, Mockito.times(1))
            .serveResource(
                Mockito.eq(jobId),
                Mockito.any(URL.class),
                Mockito.anyString(),
                Mockito.eq(request),
                Mockito.eq(response)
            );
    }

    @Test
    void wontThrow404ForJobOutputRequestIfAgentNotFound() throws GenieException, GenieCheckedException {
        this.jobsProperties.getForwarding().setEnabled(true);
        final String jobId = UUID.randomUUID().toString();
        final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
        final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

        Mockito
            .when(request.getRequestURL())
            .thenReturn(new StringBuffer("https://" + this.hostname + "/api/v3/jobs/1234/output"));

        Mockito.when(this.persistenceService.getJobArchiveStatus(jobId)).thenReturn(ArchiveStatus.PENDING);
        Mockito.when(this.agentRoutingService.getHostnameForAgentConnection(jobId)).thenReturn(Optional.empty());

        Assertions.assertThatThrownBy(
            () -> this.controller.getJobOutput(jobId, null, request, response)
        ).isInstanceOf(GenieServerException.class);

        Mockito.verify(this.agentRoutingService, Mockito.times(1)).getHostnameForAgentConnection(Mockito.eq(jobId));
    }

    @Test
    void wontForwardJobOutputRequestIfForwardingRequestWasForwarded() throws GenieException, GenieCheckedException {
        this.jobsProperties.getForwarding().setEnabled(true);
        final String jobId = UUID.randomUUID().toString();
        final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
        final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

        Mockito
            .when(request.getRequestURL())
            .thenReturn(new StringBuffer("https://" + this.hostname + "/api/v3/jobs/1234/output"));
        Mockito
            .doNothing()
            .when(this.jobDirectoryServerService)
            .serveResource(
                Mockito.eq(jobId),
                Mockito.any(URL.class),
                Mockito.anyString(),
                Mockito.eq(request),
                Mockito.eq(response)
            );

        Mockito.when(this.persistenceService.getJobArchiveStatus(jobId)).thenReturn(ArchiveStatus.PENDING);
        Mockito
            .when(this.agentRoutingService.getHostnameForAgentConnection(jobId))
            .thenReturn(Optional.of(UUID.randomUUID().toString()));

        Assertions.assertThatThrownBy(
            () -> this.controller.getJobOutput(jobId, "https://some-node:1234", request, response)
        ).isInstanceOf(GenieServerException.class);

        Mockito.verify(this.agentRoutingService, Mockito.times(1)).getHostnameForAgentConnection(jobId);
        Mockito
            .verify(this.restTemplate, Mockito.never())
            .execute(
                Mockito.anyString(),
                Mockito.any(),
                Mockito.any(),
                Mockito.any(),
                Mockito.anyString(),
                Mockito.anyString()
            );
    }

    @ParameterizedTest(name = "Exception: {0} throws {1}")
    @MethodSource("forwardJobOutputTestArguments")
    void canHandleForwardJobOutputRequestWithError(
        final Throwable forwardingException,
        final Class<? extends Throwable> expectedException
    ) throws GenieException, GenieCheckedException {
        this.jobsProperties.getForwarding().setEnabled(true);
        final String jobId = UUID.randomUUID().toString();
        final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
        final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

        Mockito
            .when(request.getRequestURL())
            .thenReturn(new StringBuffer("http://" + this.hostname + ":8080/api/v3/jobs/1234/output"));
        Mockito
            .doNothing()
            .when(this.jobDirectoryServerService)
            .serveResource(
                Mockito.eq(jobId),
                Mockito.any(URL.class),
                Mockito.anyString(),
                Mockito.eq(request),
                Mockito.eq(response)
            );
        Mockito.when(this.persistenceService.getJobArchiveStatus(jobId)).thenReturn(ArchiveStatus.PENDING);

        final String jobHostName = UUID.randomUUID().toString();
        Mockito
            .when(this.agentRoutingService.getHostnameForAgentConnection(jobId))
            .thenReturn(Optional.of(jobHostName));

        //Mock parts of the http request
        final String http = "http";
        Mockito.when(request.getScheme()).thenReturn(http);
        final int port = 8080;
        Mockito.when(request.getServerPort()).thenReturn(port);
        final String requestURI = "/" + jobId + "/" + UUID.randomUUID().toString();
        Mockito.when(request.getRequestURI()).thenReturn(requestURI);
        Mockito.when(request.getHeaderNames()).thenReturn(null);

        Mockito.when(
                this.restTemplate.execute(
                    Mockito.anyString(),
                    Mockito.any(),
                    Mockito.any(),
                    Mockito.any()
                )
            )
            .thenThrow(forwardingException);

        Assertions.assertThatThrownBy(
            () -> this.controller.getJobOutput(jobId, null, request, response)
        ).isInstanceOf(expectedException);

        Mockito.verify(this.agentRoutingService, Mockito.times(1)).getHostnameForAgentConnection(jobId);
        Mockito.verify(this.restTemplate, Mockito.times(1))
            .execute(
                Mockito.eq("http://" + jobHostName + ":8080/api/v3/jobs/" + jobId + "/output/"),
                Mockito.eq(HttpMethod.GET),
                Mockito.any(),
                Mockito.any()
            );

    }

    @Test
    void canHandleForwardJobOutputRequestWithSuccess() throws IOException, GenieException, GenieCheckedException {
        this.jobsProperties.getForwarding().setEnabled(true);
        final String jobId = UUID.randomUUID().toString();
        final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
        final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
        final String jobHostName = UUID.randomUUID().toString();

        Mockito
            .when(request.getRequestURL())
            .thenReturn(new StringBuffer("http://localhost:8080/api/v3/jobs/1234/output"));
        Mockito
            .doNothing()
            .when(this.jobDirectoryServerService)
            .serveResource(
                Mockito.eq(jobId),
                Mockito.any(URL.class),
                Mockito.anyString(),
                Mockito.eq(request),
                Mockito.eq(response)
            );
        Mockito.when(this.persistenceService.getJobArchiveStatus(jobId)).thenReturn(ArchiveStatus.PENDING);
        Mockito
            .when(this.agentRoutingService.getHostnameForAgentConnection(jobId))
            .thenReturn(Optional.of(jobHostName));

        //Mock parts of the http request
        final String http = "http";
        Mockito.when(request.getScheme()).thenReturn(http);
        final int port = 8080;
        Mockito.when(request.getServerPort()).thenReturn(port);
        final String requestURI = "/" + jobId + "/" + UUID.randomUUID().toString();
        Mockito.when(request.getRequestURI()).thenReturn(requestURI);

        final Set<String> headerNames = Sets.newHashSet(HttpHeaders.ACCEPT);
        Mockito.when(request.getHeaderNames()).thenReturn(Collections.enumeration(headerNames));
        Mockito.when(request.getHeader(HttpHeaders.ACCEPT)).thenReturn(MediaType.APPLICATION_JSON_VALUE);

        //Mock parts of forward response
        final HttpResponse forwardResponse = Mockito.mock(HttpResponse.class);
        final StatusLine statusLine = Mockito.mock(StatusLine.class);
        Mockito.when(forwardResponse.getStatusLine()).thenReturn(statusLine);
        final int successCode = 200;
        Mockito.when(statusLine.getStatusCode()).thenReturn(successCode);
        final Header contentTypeHeader = Mockito.mock(Header.class);
        Mockito.when(contentTypeHeader.getName()).thenReturn(HttpHeaders.CONTENT_TYPE);
        Mockito.when(contentTypeHeader.getValue()).thenReturn(MediaType.TEXT_PLAIN_VALUE);
        Mockito.when(forwardResponse.getAllHeaders()).thenReturn(new Header[]{contentTypeHeader});

        final String text = UUID.randomUUID().toString() + UUID.randomUUID().toString() + UUID.randomUUID().toString();
        final ByteArrayInputStream bis = new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8));
        final HttpEntity entity = Mockito.mock(HttpEntity.class);
        Mockito.when(entity.getContent()).thenReturn(bis);
        Mockito.when(forwardResponse.getEntity()).thenReturn(entity);

        final DelegatingServletOutputStream bos = new DelegatingServletOutputStream(new ByteArrayOutputStream());
        Mockito.when(response.getOutputStream()).thenReturn(bos);

        final ClientHttpRequestFactory factory = Mockito.mock(ClientHttpRequestFactory.class);
        final ClientHttpRequest clientHttpRequest = Mockito.mock(ClientHttpRequest.class);
        Mockito.when(clientHttpRequest.execute())
            .thenReturn(new MockClientHttpResponse(text.getBytes(StandardCharsets.UTF_8), HttpStatus.OK));
        Mockito.when(clientHttpRequest.getHeaders())
            .thenReturn(new HttpHeaders());
        Mockito.when(factory.createRequest(Mockito.any(), Mockito.any())).thenReturn(clientHttpRequest);
        final RestTemplate template = new RestTemplate(factory);
        final MeterRegistry registry = Mockito.mock(MeterRegistry.class);
        final Counter counter = Mockito.mock(Counter.class);
        Mockito.when(registry.counter(Mockito.anyString())).thenReturn(counter);

        final DataServices dataServices = Mockito.mock(DataServices.class);
        Mockito.when(dataServices.getPersistenceService()).thenReturn(this.persistenceService);

        final JobRestController jobController = new JobRestController(
            Mockito.mock(JobLaunchService.class),
            dataServices,
            this.createMockResourceAssembler(),
            new GenieHostInfo(this.hostname),
            template,
            this.jobDirectoryServerService,
            this.jobsProperties,
            registry,
            this.agentRoutingService,
            this.environment,
            Mockito.mock(AttachmentService.class),
            this.jobKillService
        );
        jobController.getJobOutput(jobId, null, request, response);

        Assertions.assertThat(bos.getTargetStream().toString()).isEqualTo(text);
        Mockito.verify(request, Mockito.times(1)).getHeader(HttpHeaders.ACCEPT);
        Mockito.verify(this.agentRoutingService, Mockito.times(1)).getHostnameForAgentConnection(jobId);
        Mockito.verify(response, Mockito.never()).sendError(Mockito.anyInt());
        Mockito
            .verify(this.jobDirectoryServerService, Mockito.never())
            .serveResource(
                Mockito.eq(jobId),
                Mockito.any(URL.class),
                Mockito.anyString(),
                Mockito.eq(request),
                Mockito.eq(response)
            );
    }

    /**
     * Make sure when job submission is disabled it won't run the job and will return the proper error message.
     */
    @Test
    void whenJobSubmissionIsDisabledItThrowsCorrectError() {
        final String errorMessage = UUID.randomUUID().toString();
        Mockito.when(
            this.environment.getProperty(
                JobConstants.JOB_SUBMISSION_ENABLED_PROPERTY_KEY,
                Boolean.class,
                true
            )
        ).thenReturn(false);
        Mockito.when(
            this.environment.getProperty(
                JobConstants.JOB_SUBMISSION_DISABLED_MESSAGE_KEY,
                JobConstants.JOB_SUBMISSION_DISABLED_DEFAULT_MESSAGE
            )
        ).thenReturn(errorMessage);

        Assertions
            .assertThatExceptionOfType(GenieServerUnavailableException.class)
            .isThrownBy(() ->
                this.controller.submitJob(
                    Mockito.mock(JobRequest.class),
                    null,
                    null,
                    Mockito.mock(HttpServletRequest.class)
                ))
            .withMessage(errorMessage);
    }

    private EntityModelAssemblers createMockResourceAssembler() {
        return new EntityModelAssemblers(
            Mockito.mock(ApplicationModelAssembler.class),
            Mockito.mock(ClusterModelAssembler.class),
            Mockito.mock(CommandModelAssembler.class),
            Mockito.mock(JobExecutionModelAssembler.class),
            Mockito.mock(JobMetadataModelAssembler.class),
            Mockito.mock(JobRequestModelAssembler.class),
            Mockito.mock(JobModelAssembler.class),
            Mockito.mock(JobSearchResultModelAssembler.class),
            Mockito.mock(RootModelAssembler.class)
        );
    }
}


text:
package org.neo4j.driver.internal.reactivestreams;

import java.util.concurrent.CompletionStage;
import org.neo4j.driver.Query;
import org.neo4j.driver.internal.async.UnmanagedTransaction;
import org.neo4j.driver.internal.cursor.RxResultCursor;
import org.neo4j.driver.internal.reactive.AbstractReactiveTransaction;
import org.neo4j.driver.internal.util.Futures;
import org.neo4j.driver.reactivestreams.ReactiveResult;
import org.neo4j.driver.reactivestreams.ReactiveTransaction;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Mono;

public class InternalReactiveTransaction extends AbstractReactiveTransaction
        implements ReactiveTransaction, BaseReactiveQueryRunner {
    protected InternalReactiveTransaction(UnmanagedTransaction tx) {
        super(tx);
    }

    @Override
    public Publisher<ReactiveResult> run(Query query) {
        CompletionStage<RxResultCursor> cursorStage;
        try {
            cursorStage = tx.runRx(query);
        } catch (Throwable t) {
            cursorStage = Futures.failedFuture(t);
        }

        return Mono.fromCompletionStage(cursorStage)
                .flatMap(cursor -> {
                    Mono<RxResultCursor> publisher;
                    Throwable runError = cursor.getRunError();
                    if (runError != null) {
                        publisher = Mono.error(runError);
                        tx.markTerminated(runError);
                    } else {
                        publisher = Mono.just(cursor);
                    }
                    return publisher;
                })
                .map(InternalReactiveResult::new);
    }

    /**
     * Marks transaction as terminated and sends {@code RESET} message over allocated connection.
     *

     * THIS METHOD IS NOT PART OF PUBLIC API. This method may be changed or removed at any moment in time.
     *
     * @return {@code RESET} response publisher
     */
    public Publisher<Void> interrupt() {
        return Mono.fromCompletionStage(tx.interruptAsync());
    }

    @Override
    public <T> Publisher<T> commit() {
        return doCommit();
    }

    @Override
    public <T> Publisher<T> rollback() {
        return doRollback();
    }

    @Override
    public Publisher<Void> close() {
        return doClose();
    }

    @Override
    public Publisher<Boolean> isOpen() {
        return doIsOpen();
    }
}


text:
            <button ng-click="startJoyRide('tour_story')" type="button" class="btn btn-primary btn-lg pull-right">Tour the story </button>
            <form class="form-horizontal" role="form" id="storyForm" name="storyForm" novalidate="novalidate">

                    {{story.dirPath}}
                    <input id="storyName" name="storyName" class="form-control" type="text" ng-model="story.name" placeholder="story name" required="true">

                        <button id="expandPanels" class="btn btn-info" type="button" ng-click="expandPanels()">

                        </button>

                    <button id="storyPanel" type="button" class="panel-heading panel-title btn btn-block btn-info" ng-click="panels.story = !panels.story">
                        Story
                    </button>

                            <button id="storyDescriptionPanel" type="button" class="panel-heading panel-title btn btn-block btn-info" ng-click="panels.description = !panels.description">
                                Description
                            </button>

                                    <textarea id="storyDescription" name="storyDescription" class="form-control" ng-model="story.description" placeholder="story description" rows="5"></textarea>

                            <button id="storyMetaPanel" type="button" class="panel-heading panel-title btn btn-block btn-info" ng-click="panels.meta = !panels.meta">
                                Meta
                            </button>

                                        @

                                    <input id="storyMeta{{$index + 1}}" name="storyMeta" class="form-control" type="text" ng-model="meta.element" required="true">

                                        <button id="removeStoryMeta{{$index + 1}}" class="btn btn-danger" ng-click="removeCollectionElement(story.meta, $index)" type="button">

                                        </button>

                                        <button id="addStoryMeta" class="btn btn-info" ng-click="addElement(story.meta, element)" type="button">

                                        </button>

                            <button id="storyNarrativePanel" type="button" class="panel-heading panel-title btn btn-block btn-info" ng-click="panels.narrative = !panels.narrative">
                                Narrative
                            </button>

                                    In order to

                                        <input id="storyNarrativeInOrderTo" name="storyNarrativeInOrderTo" class="form-control" type="text" ng-model="story.narrative.inOrderTo">

                                    As a

                                        <input id="storyNarrativeAsA" name="storyNarrativeAsA" class="form-control" type="text" ng-model="story.narrative.asA">

                                    I want to

                                        <input id="storyNarrativeIWantTo" name="storyNarrativeIWantTo" class="form-control" type="text" ng-model="story.narrative.iWantTo">

                            <button id="storyGivenStoriesPanel" type="button" class="panel-heading panel-title btn btn-block btn-info" ng-click="panels.givenStories = !panels.givenStories">
                                Given Stories
                            </button>

                                    <input id="storyGivenStory{{$index + 1}}" name="storyGivenStory" class="form-control" type="text" ng-model="givenStory.story" required="true">

                                        <button id="removeStoryGivenStory{{$index + 1}}" class="btn btn-danger" ng-click="removeCollectionElement(story.givenStories, $index)" type="button">

                                        </button>

                                        <button id="addStoryGivenStory" class="btn btn-info" ng-click="addElement(story.givenStories, story)" type="button">

                                        </button>

                            <button id="storyLifecyclePanel" type="button" class="panel-heading panel-title btn btn-block btn-info" ng-click="panels.lifecycle = !panels.lifecycle">
                                Lifecycle
                            </button>

                                    Before:
                                    <button id="addStoryLifecycleBeforeStep" class="btn btn-info pull-right" ng-click="addElement(story.lifecycle.before, step)" type="button">

                                    </button>

                                        <input id="storyLifecycleBeforeStep{{$index + 1}}" name="storyStepInput" class="form-control" type="text" ng-model="stepElement.step" required="true" typeahead="step as step.step for step in steps.steps | filter:{step:$viewValue} | limitTo:25" ng-keypress="stepEnterKey($event, story.lifecycle.before)" autofocus>

                                            <button id="removeStoryLifecycleBeforeStep{{$index + 1}}" class="btn btn-danger" ng-click="removeCollectionElement(story.lifecycle.before, $index)" type="button">

                                            </button>

                                    After:
                                    <button id="addStoryLifecycleAfterStep" class="btn btn-info pull-right" ng-click="addElement(story.lifecycle.after, step)" type="button">

                                    </button>

                                        <input id="storyLifecycleAfterStep{{$index + 1}}" name="storyStepInput" class="form-control" type="text" ng-model="stepElement.step" required="true" typeahead="step as step.step for step in steps.steps | filter:{step:$viewValue} | limitTo:25" ng-keypress="stepEnterKey($event, story.lifecycle.after)" autofocus>

                                            <button id="removeStoryLifecycleAfterStep{{$index + 1}}" class="btn btn-danger" ng-click="removeCollectionElement(story.lifecycle.after, $index)" type="button">

                                            </button>

                    <button id="scenariosPanel" type="button" class="panel-heading panel-title btn btn-block btn-lg btn-primary" ng-click="panels.scenarios = !panels.scenarios">
                        Scenarios
                    </button>

                                    Scenario

                                <input id="scenario{{scenarioIndex + 1}}Title" name="scenarioTitle" class="form-control" type="text" ng-model="scenario.title" required="true" ng-focus="changeScenarioToggle(scenarioIndex, true)">

                                    <button id="scenario{{scenarioIndex + 1}}Panel" class="btn btn-info" ng-click="changeScenarioToggle(scenarioIndex)" type="button">

                                    </button>
                                    <button id="scenario{{scenarioIndex + 1}}Remove" class="btn btn-danger" ng-click="removeCollectionElement(story.scenarios, $index)" type="button">

                                    </button>

                                        Meta:
                                        <button id="addScenario{{scenarioIndex + 1}}Meta" class="btn btn-info pull-right" ng-click="addElement(scenario.meta, element)" type="button">

                                        </button>

                                             @

                                        <input id="scenario{{scenarioIndex + 1}}Meta{{$index + 1}}" name="scenarioMeta" class="form-control" type="text" ng-model="meta.element" required="true" ng-keypress="stepEnterKey($event, scenario.meta)" autofocus>

                                            <button id="removeScenario{{scenarioIndex + 1}}Meta{{$index}}" class="btn btn-danger" ng-click="removeCollectionElement(scenario.meta, $index)" type="button">

                                            </button>

                                        Steps:
                                        <button id="addScenario{{scenarioIndex + 1}}Step" class="btn btn-info pull-right" ng-click="addElement(scenario.steps, step)" type="button">

                                        </button>

                                        <input id="scenario{{scenarioIndex + 1}}Step{{$index + 1}}" name="scenarioStep" class="form-control" type="text" ng-model="stepElement.step" required="true" typeahead="step.step as step.step for step in steps.steps | filter:{step:$viewValue} | limitTo:25" ng-keypress="stepEnterKey($event, scenario.steps)" autofocus>

                                            <button id="removeScenario{{scenarioIndex + 1}}Step{{$index + 1}}" class="btn btn-danger" ng-click="removeCollectionElement(scenario.steps, $index)" type="button">

                                            </button>

Examples:

                                    <textarea id="scenario{{scenarioIndex + 1}}Examples" rows="4" style="resize: vertical" name="storyScenarioExamplesInput" class="form-control" ng-model="scenario.examplesTable"></textarea>

                                <button id="addScenario" class="btn btn-info" ng-click="addScenarioElement(story.scenarios)" type="button">

                                </button>

Form is incorrect!

                        <button id="saveStory" class="btn btn-primary" ng-class="buttonCssClass(storyForm)" ng-disabled="!features.saveStory.enabled || !canSaveStory()" ng-click="saveStory()" type="button">Save</button>
                        <button id="runStory" class="btn btn-primary" ng-class="buttonCssClass(storyForm)" ng-disabled="!canRunStory()" ng-click="runStory()" type="button">Run Story</button>
                        <button id="revertStory" class="btn btn-info" ng-click="revertStory()" ng-disabled="!canRevertStory()" type="button">Revert Changes</button>
                        <button id="deleteStory" class="btn btn-danger" ng-click="deleteStory()" ng-disabled="!features.deleteStory.enabled || !canDeleteStory()" type="button">Delete Story</button>

            </form>

                    {{getStoryRunnerStatusText()}}

Pending Steps

{{step.text}}


text:
package ws.vinta.albedo

import org.apache.spark.SparkConf
import org.apache.spark.ml.feature._
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions._
import ws.vinta.albedo.transformers._
import ws.vinta.albedo.utils.DatasetUtils._
import ws.vinta.albedo.utils.ModelUtils._

object Word2VecCorpusBuilder {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf()
    if (scala.util.Properties.envOrElse("RUN_WITH_INTELLIJ", "false") == "true") {
      conf.setMaster("local[*]")
      conf.set("spark.driver.memory", "12g")
      //conf.setMaster("local-cluster[1, 3, 12288]")
      //conf.setJars(List("target/albedo-1.0.0-SNAPSHOT-uber.jar"))
      //conf.setMaster("spark://localhost:7077")
      //conf.set("spark.driver.memory", "2g")
      //conf.set("spark.executor.cores", "3")
      //conf.set("spark.executor.memory", "12g")
      //conf.setJars(List("target/albedo-1.0.0-SNAPSHOT-uber.jar"))
    }

    implicit val spark: SparkSession = SparkSession
      .builder()
      .appName("Word2VecCorpusBuilder")
      .config(conf)
      .getOrCreate()

    import spark.implicits._

    val sc = spark.sparkContext
    sc.setCheckpointDir(s"${settings.checkpointDir}")

    // Load Data

    val rawUserInfoDS = loadRawUserInfoDS().cache()

    val rawRepoInfoDS = loadRawRepoInfoDS().cache()

    // Train the Model

    val columnName = "text"

    val userTextDF = rawUserInfoDS
      .withColumn(columnName, concat_ws(", ", $"user_login", $"user_name", $"user_bio", $"user_company", $"user_location"))
      .select("user_id", "user_login", columnName)

    val repoTextDF = rawRepoInfoDS
      .withColumn(columnName, concat_ws(", ", $"repo_owner_username", $"repo_name", $"repo_language", $"repo_description", $"repo_topics"))
      .select("repo_id", "repo_full_name", columnName)

    val corpusDF = userTextDF.select(columnName)
      .union(repoTextDF.select(columnName))
      .cache()

    val hanLPTokenizer = new HanLPTokenizer()
      .setInputCol(columnName)
      .setOutputCol(s"${columnName}_words")
      .setShouldRemoveStopWords(true)
    val tokenizedDF = hanLPTokenizer.transform(corpusDF)

    val stopWordsRemover = new StopWordsRemover()
      .setInputCol(s"${columnName}_words")
      .setOutputCol(s"${columnName}_filtered_words")
      .setStopWords(StopWordsRemover.loadDefaultStopWords("english"))
    val filteredDF = stopWordsRemover.transform(tokenizedDF)

    val finalDF = filteredDF.cache()

    val word2VecModelPath = s"${settings.dataDir}/${settings.today}/word2VecModel.parquet"
    val word2VecModel = loadOrCreateModel[Word2VecModel](Word2VecModel, word2VecModelPath, () => {
      val word2Vec = new Word2Vec()
        .setInputCol(s"${columnName}_filtered_words")
        .setOutputCol(s"${columnName}_w2v")
        .setMaxIter(30)
        .setVectorSize(200)
        .setWindowSize(5)
        .setMinCount(10)
      word2Vec.fit(finalDF)
    })

    println(word2VecModel.explainParams())

    val word2VecDF = word2VecModel.transform(finalDF)
    word2VecDF.show(false)

    spark.stop()
  }
}


text:
/**
 * Auto configuration for aspects applied to the Genie server.
 *
 * @author tgianos
 * @since 4.0.0
 */
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.aspects;

import javax.annotation.ParametersAreNonnullByDefault;


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Rhizina zonata Berk.

### Remarks
null


text:
import {statementType} from "../_utils";
import * as Statements from "../../../src/abap/2_statements/statements";

const tests = [
  "INSERT TEXTPOOL is_progdir-name FROM it_tpool LANGUAGE mv_language STATE 'I'.",
  "INSERT textpool l_name FROM it_tpool LANGUAGE sy-langu.",
  "INSERT TEXTPOOL target FROM tab.",
];

statementType(tests, "INSERT TEXTPOOL", Statements.InsertTextpool);


text:
Vagrant Server Ubuntu 14.04 with Virtual Box
----

## Setup

#### 1) Install virtual box
https://www.virtualbox.org/wiki/Downloads

Win = http://download.virtualbox.org/virtualbox/5.0.6/VirtualBox-5.0.6-103037-Win.exe

OSX = http://download.virtualbox.org/virtualbox/5.0.6/VirtualBox-5.0.6-103037-OSX.dmg

#### 2) Install extension pack
https://www.virtualbox.org/wiki/Downloads
http://download.virtualbox.org/virtualbox/5.0.6/Oracle_VM_VirtualBox_Extension_Pack-5.0.6-103037.vbox-extpack

#### 3) Install Vagrant
Win = https://dl.bintray.com/mitchellh/vagrant/vagrant_1.7.4.msi

OSX = https://dl.bintray.com/mitchellh/vagrant/vagrant_1.7.4.dmg

#### 4) Run `vagrant up`

#### 5) SSH into 10.1.2.2 (eg. from mobaXterm)
or run vagrant ssh from project folder

#### 6) (optional) change mysql root password

Find and replace the default password:

```
W4IoA_dKb7gRgzDt
```

#### 7) Run install script

```
sudo su
/vagrant/setup/install-scripts/install.sh
```

#### 8) Test info & cache files

- http://10.1.2.2/info.php
- http://10.1.2.2/cache.php
- http://10.1.2.2/project/

#### 9) Next steps

- Replace the project folder contents with your own project

----

## Notes

#### xdebug
use the idekey
```
ide-xdebug
```

#### Virtualbox trouble with Windows?
Download Fix for Windows:
- https://www.virtualbox.org/ticket/14040
- https://www.virtualbox.org/attachment/ticket/14040/VBox-Win10-fix-14040.exe


text:
<!DOCTYPE HTML>

  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <title>SlickGrid example 7: Events</title>
  <link rel="stylesheet" href="../slick.grid.css" type="text/css"/>
  <link rel="stylesheet" href="../css/smoothness/jquery-ui-1.8.24.custom.css" type="text/css"/>
  <link rel="stylesheet" href="examples.css" type="text/css"/>

Demonstrates:

handling events from the grid:

Right-click the row to open the context menu

Click the priority cell to toggle values

View Source:

 View the source for this example on Github

  Set priority:

Low

Medium

High


text:
package org.apache.rya.joinselect.mr;

import java.io.IOException;

import org.apache.rya.joinselect.mr.FullTableSize;

import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.Value;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mrunit.mapreduce.MapReduceDriver;
import org.junit.Test;

//TODO fix table names!

public class FullTableSizeTest {

    private static final String DELIM = "\u0000";

    @Test
    public void testFullTableSize() throws IOException {

        Value value = new Value(new byte[0]);

        Mutation m = new Mutation(new Text("subjectpredicateobject" + DELIM + "FullTableCardinality"));
        m.put(new Text("FullTableCardinality"), new Text("15"), new Value(new byte[0]));

        new MapReduceDriver<Key, Value, Text, IntWritable, Text, Mutation>()
                .withMapper(new FullTableSize.FullTableMapper()).withInput(new Key(new Text("entry1")), value)
                .withInput(new Key(new Text("entry2")), value).withInput(new Key(new Text("entry3")), value)
                .withInput(new Key(new Text("entry4")), value).withInput(new Key(new Text("entry5")), value)
                .withInput(new Key(new Text("entry6")), value).withInput(new Key(new Text("entry7")), value)
                .withInput(new Key(new Text("entry8")), value).withInput(new Key(new Text("entry9")), value)
                .withInput(new Key(new Text("entry10")), value).withInput(new Key(new Text("entry11")), value)
                .withInput(new Key(new Text("entry12")), value).withInput(new Key(new Text("entry13")), value)
                .withInput(new Key(new Text("entry14")), value).withInput(new Key(new Text("entry15")), value)
                .withCombiner(new FullTableSize.FullTableCombiner()).withReducer(new FullTableSize.FullTableReducer())
                .withOutput(new Text(""), m).runTest();

    }

}


text: require('./gulpTasks/gulpFile');


text:
////////////////////////////////////////////////////////////////////////////////
//
// #OWNER# ___PROJECTNAME___
// Copyright (c) ___YEAR___ #OWNER#
// All Rights Reserved Worldwide
// Proprietary and Confidential - Not for Distribution
// Written by #AUTHOR#
//
// ___FILENAME___
//
// AUTHOR IDENTITY:
//		___FULLUSERNAME___		___DATE___
//
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/**
 *
 */
@protocol ___FILEBASENAMEASIDENTIFIER___ <NSObject>

@end


text:
Munch's
=======

The ultimate site for Online Deals from restaurants


text:
#!/bin/sh
# Copyright 2018 Google Inc.
#
# 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.

# Detect platform properties based on the cc command given as first argument,
# then invoke the make command that follows on the command line with variables
# NSYNC_OS, NSYNC_OS_TYPE, NSYNC_CC, and NSYNC_ARCH indicating those
# properties.
#
# This script must use _only_ properties derived from the compiler supplied,
# becuase that may be a cross compiler, targeting a platform quite different
# from the host.
#
# detect.sh will work for most Unix-like platforms.  Uses the path to the detect.c
# header if specified; otherwise it assumes that it is called "detect.c" in the same
# directory as the detect.sh script.

usage="usage: detect.sh \\
	[-target_lang <target_lang_type>] \\
	[-target_arch <target_arch_type>] \\
	[-target_cc <target_cc_type>] \\
	[-target_os <target_os_type>] \\
	[-nsync_base <path_to_nsync_root>] \\
	[-detect_path <path_to_detect.c>] \\
	<cc_command> <make_command> [make_args...]

It is not usually necessary to specify options.   The target compiler, operating system, language, and architecture
types are normally deduced by running the supplied compiler.

The paths are normally inferred from the structure of the nsync tree and the
fact that this script is usually invoked from a child of the 'builds'
directory.
"

detect_base=detect.c

detect_path=
nsync_base=../..
target_lang=
target_arch=
target_cc=
target_os=
while
	arg="$1"
	case "$arg" in
	-*)	found=false
		for flag in target_lang target_arch target_cc target_os detect_path nsync_base; do
			case "$arg" in
			"-$flag")	eval $flag='"${2?"$usage"}"'; shift; found=true; break;;
			-"$flag"=*)	s=`expr "$arg" : '^[^=]*=\(.*\)$'`; eval $flag="'$s'"; found=true; break;;
			esac
		done
		case "$found" in false)	echo "$usage" >&2; exit 2;; esac
		;;
	*)	break;;
	esac
do
	shift
done

case $# in [01]) echo "$usage" >&2; exit 2;; esac
cc="$1"
make="$2"
shift
shift

case "$detect_path" in
"")	case "$0" in
	*/*)	detect_path=`expr "$0" : '^\(.*/\)[^/]*$'`"$detect_base";;
	*)	path="$PATH":.
		while [ ! -f "$detect_path" -a -n "$path" ]; do
			detect_path=`expr "$path" : '^\([^:]*\).*$'`"/$detect_base"
			path=`expr "$path" : '^[^:]*:\(.*\)$'`
		done;;
	esac
esac

if [ ! -f "$detect_path" ]; then
	echo "$0: can't find $detect_base; maybe use -detect_path flag?" >&2; exit 2
fi

# Set variables detected_* from detect.c
eval `$cc -E "$detect_path" | sed -n 's,^\(detected_.*=.*\)X,\1,p'`

case "$detected_cc.$detected_lang" in
pcc.c11)  # pcc lies when it claims to implement c11
	detected_lang=c;;
esac

# Allow overrides from the command line.
case "$target_lang" in ?*) detected_lang="$target_lang";; esac
case "$target_arch" in ?*) detected_arch="$target_arch";; esac
case "$target_cc" in   ?*) detected_cc="$target_cc";; esac
case "$target_os" in   ?*) detected_os="$target_os";; esac

extra_c="$DETECT_EXTRA_CFLAGS"
extra_objs=
extra_s=
extra_cpp_flags="$DETECT_EXTRA_CPPFLAGS"
extra_libs="$DETECT_EXTRA_LIBS"

# If we can't get atomics from the OS or the compiler, try to find an assembly
# language implementation based on the architecture, or one provided by the
# language library.
if [ ! -f "$nsync_base/platform/$detected_os/atomic.h" -a ! -f "$nsync_base/platform/$detected_cc/atomic.h" ]; then
	case "$detected_lang" in
	c11)	extra_cpp_flags="$extra_cpp_flags -DNSYNC_ATOMIC_C11 -I../../platform/c11";;
	c++11)	extra_cpp_flags="$extra_cpp_flags -DNSYNC_USE_CPP11_TIMEPOINT -DNSYNC_ATOMIC_CPP11 -I../../platform/c++11";;
	*)	# Try for assembly language.
		for x in "$nsync_base/platform/$detected_arch/src/nsync_atm_$detected_arch".[sS]; do
			if [ -f "$x" ]; then
				extra_cpp_flags="$extra_cpp_flags -I$nsync_base/platform/atomic_ind"
				extra_s="$extra_s $x"
				extra_objs="$extra_objs nsync_atm_$detected_arch.o"
				break
			fi
		done;;
	esac
fi

# Some systems are special in various ways.
case "$detected_arch.$detected_os.$detected_cc" in
*.macos.*)	# Some MacOS versions don't provide clock_gettime().
		extra_c="$extra_c $nsync_base/platform/posix/src/clock_gettime.c"
        	extra_obj="$extra_objs clock_gettime.o";;
*.linux.*)	# Some Linux boxes keep clock_gettime() in librt.
		extra_libs="$extra_libs -lrt";;
esac

# Some compilers support cc -M, but others do not.
case "$detected_cc" in
gcc|clang|decc)	mkdep="$cc -M";;
*)		mkdep="$nsync_base/tools/mkdep.sh $cc -E";;
esac
case "$detected_cc" in
lcc)	extra_c="$extra_c ../../platform/posix/src/time_rep.c"
	extra_objs="$extra_objs time_rep.o"
	pthread=
	cflags=
	ldflags=-lpthread
	opt=OPT=;;
tendracc)
	extra_c="$extra_c ../../platform/posix/src/time_rep.c"
	extra_objs="$extra_objs time_rep.o"
	pthread=
	cflags=
	ldflags=-lpthread
	opt=OPT=;;
pcc)	extra_c="$extra_c ../../platform/num_time/src/time_rep.c"
	extra_objs="$extra_objs time_rep.o"
	extra_cpp_flags="$extra_cpp_flags -I../../platform/num_time -DNSYNC_USE_INT_TIME=int64_t"
	pthread=-pthread
	cflags=
	ldflags=-pthread
	opt=;;
*)	extra_c="$extra_c ../../platform/posix/src/time_rep.c"
	extra_objs="$extra_objs time_rep.o"
	pthread=-pthread
	cflags=
	ldflags=-pthread
	opt=;;
esac

# Invoke command from command line, with various arguments inserted.
"$make" -e \
	"MKDEP=$mkdep" \
	"NSYNC_EXTRA_INC_DIR=$extra_cpp_flags" "NSYNC_EXTRA_PLATFORM_C=$extra_c" "PLATFORM_S=$extra_s" \
	"NSYNC_EXTRA_OBJS=$extra_objs" "NSYNC_OS=$detected_os" \
	"NSYNC_OS_TYPE=posix" "NSYNC_CC=$detected_cc" "NSYNC_ARCH=$detected_arch" \
	"NSYNC_PTHREAD=$pthread" \
	"PLATFORM_CFLAGS=$cflags" \
	"PLATFORM_LIBS=$extra_libs" \
	"PLATFORM_LDFLAGS=$ldflags" \
	$opt \
	${1+"$@"}


text:
require 'socket'
require 'timeout'

require 'riddle/client'
require 'riddle/configuration'
require 'riddle/controller'

module Riddle #:nodoc:
  class ConnectionError < StandardError #:nodoc:
  end

  module Version #:nodoc:
    Major   = 0
    Minor   = 9
    Tiny    = 8
    # Revision number for RubyForge's sake, taken from what Sphinx
    # outputs to the command line.
    Rev     = 1533
    # Release number to mark my own fixes, beyond feature parity with
    # Sphinx itself.
    Release = 4

    String      = [Major, Minor, Tiny].join('.')
    GemVersion  = [Major, Minor, Tiny, Rev, Release].join('.')
  end

  def self.escape(string)
    string.gsub(/[\(\)\|\-!@~"&\/]/) { |char| "\\#{char}" }
  end
end


text:
package edu.udacity.nanodegree;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class MovieDetailActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_movie_detail);
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_moviedetail, new MovieDetailActivityFragment())
                    .commit();
        }
    }

}


text:
require 'pathname'

Puppet::Type.newtype(:dsc_xspinstall) do
  require Pathname.new(__FILE__).dirname + '../../' + 'puppet/type/base_dsc'

  provide :powershell, :parent => Puppet::Type.type(:base_dsc).provider(:powershell) do
    defaultfor :operatingsystem => :windows
  end

  @doc = %q{
    The DSC xSPInstall resource type.
    Originally generated from the following schema.mof file:
      import/dsc_resources/xSharePoint/Modules/xSharePoint/DSCResources/MSFT_xSPInstall/MSFT_xSPInstall.schema.mof
  }

  validate do
      fail('dsc_binarydir is a required attribute') if self[:dsc_binarydir].nil?
    end

  newparam(:dscmeta_resource_friendly_name) do
    defaultto "xSPInstall"
  end

  newparam(:dscmeta_resource_name) do
    defaultto "MSFT_xSPInstall"
  end

  newparam(:dscmeta_import_resource) do
    newvalues(true, false)

    munge do |value|
      provider.munge_boolean(value.to_s)
    end

    defaultto true
  end

  newparam(:dscmeta_module_name) do
    defaultto "xSharePoint"
  end

  newparam(:dscmeta_module_version) do
    defaultto "0.3.1.0"
  end

  newparam(:name, :namevar => true ) do
  end

  ensurable do
    newvalue(:exists?) { provider.exists? }
    newvalue(:present) { provider.create }
    defaultto { :present }
  end

  # Name:         BinaryDir
  # Type:         string
  # IsMandatory:  True
  # Values:       None
  newparam(:dsc_binarydir) do
    isrequired
    validate do |value|
      unless value.kind_of?(String)
        fail("Invalid value '#{value}'. Should be a string")
      end
    end
  end

  # Name:         ProductKey
  # Type:         string
  # IsMandatory:  False
  # Values:       None
  newparam(:dsc_productkey) do
    validate do |value|
      unless value.kind_of?(String)
        fail("Invalid value '#{value}'. Should be a string")
      end
    end
  end

end


text:
<?php
/**
 * User: nikk
 * Date: 2/5/14
 * Time: 1:39 PM
 */

namespace Sp\AppBundle\Repository;

use Doctrine\ORM\EntityRepository;

class MeetRepository extends EntityRepository
{

}


text:
<?php

namespace Minsal\shcpBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * ShcpAboPreproced3
 *
 * @ORM\Table(name="shcp_abo_preproced3", indexes={@ORM\Index(name="IDX_C2C609BB70374B77", columns={"id_preproced1"}), @ORM\Index(name="IDX_C2C609BB1E833DEC", columns={"id_cie10"})})
 * @ORM\Entity
 */
class ShcpAboPreproced3
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="SEQUENCE")
     * @ORM\SequenceGenerator(sequenceName="shcp_abo_preproced3_id_seq", allocationSize=1, initialValue=1)
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="prep3_condicion_ingr", type="string", nullable=true)
     */
    private $prep3CondicionIngr;

    /**
     * @var string
     *
     * @ORM\Column(name="prep3_otro_danio", type="string", length=30, nullable=true)
     */
    private $prep3OtroDanio;

    /**
     * @var string
     *
     * @ORM\Column(name="prep3_estado_actual", type="string", nullable=true)
     */
    private $prep3EstadoActual;

    /**
     * @var string
     *
     * @ORM\Column(name="prep3_tipo_aborto", type="string", nullable=true)
     */
    private $prep3TipoAborto;

    /**
     * @var string
     *
     * @ORM\Column(name="prep3_respons", type="string", length=100, nullable=true)
     */
    private $prep3Respons;

    /**
     * @var \ShcpAboPreproced1
     *
     * @ORM\ManyToOne(targetEntity="ShcpAboPreproced1")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="id_preproced1", referencedColumnName="id")
     * })
     */
    private $idPreproced1;

    /**
     * @var \ShcpAboCtlCie10
     *
     * @ORM\ManyToOne(targetEntity="ShcpAboCtlCie10")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="id_cie10", referencedColumnName="id")
     * })
     */
    private $idCie10;

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

    /**
     * Set prep3CondicionIngr
     *
     * @param string $prep3CondicionIngr
     * @return ShcpAboPreproced3
     */
    public function setPrep3CondicionIngr($prep3CondicionIngr)
    {
        $this->prep3CondicionIngr = $prep3CondicionIngr;

        return $this;
    }

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

    /**
     * Set prep3OtroDanio
     *
     * @param string $prep3OtroDanio
     * @return ShcpAboPreproced3
     */
    public function setPrep3OtroDanio($prep3OtroDanio)
    {
        $this->prep3OtroDanio = $prep3OtroDanio;

        return $this;
    }

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

    /**
     * Set prep3EstadoActual
     *
     * @param string $prep3EstadoActual
     * @return ShcpAboPreproced3
     */
    public function setPrep3EstadoActual($prep3EstadoActual)
    {
        $this->prep3EstadoActual = $prep3EstadoActual;

        return $this;
    }

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

    /**
     * Set prep3TipoAborto
     *
     * @param string $prep3TipoAborto
     * @return ShcpAboPreproced3
     */
    public function setPrep3TipoAborto($prep3TipoAborto)
    {
        $this->prep3TipoAborto = $prep3TipoAborto;

        return $this;
    }

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

    /**
     * Set prep3Respons
     *
     * @param string $prep3Respons
     * @return ShcpAboPreproced3
     */
    public function setPrep3Respons($prep3Respons)
    {
        $this->prep3Respons = $prep3Respons;

        return $this;
    }

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

    /**
     * Set idPreproced1
     *
     * @param \Minsal\shcpBundle\Entity\ShcpAboPreproced1 $idPreproced1
     * @return ShcpAboPreproced3
     */
    public function setIdPreproced1(\Minsal\shcpBundle\Entity\ShcpAboPreproced1 $idPreproced1 = null)
    {
        $this->idPreproced1 = $idPreproced1;

        return $this;
    }

    /**
     * Get idPreproced1
     *
     * @return \Minsal\shcpBundle\Entity\ShcpAboPreproced1
     */
    public function getIdPreproced1()
    {
        return $this->idPreproced1;
    }

    /**
     * Set idCie10
     *
     * @param \Minsal\shcpBundle\Entity\ShcpAboCtlCie10 $idCie10
     * @return ShcpAboPreproced3
     */
    public function setIdCie10(\Minsal\shcpBundle\Entity\ShcpAboCtlCie10 $idCie10 = null)
    {
        $this->idCie10 = $idCie10;

        return $this;
    }

    /**
     * Get idCie10
     *
     * @return \Minsal\shcpBundle\Entity\ShcpAboCtlCie10
     */
    public function getIdCie10()
    {
        return $this->idCie10;
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>PAD2048</title>

  <link href="style/main.css" rel="stylesheet" type="text/css">
  <link rel="shortcut icon" href="favicon.ico">
  <link rel="apple-touch-icon" href="meta/apple-touch-icon.png">
  <meta name="apple-mobile-web-app-capable" content="yes">

  <meta name="HandheldFriendly" content="True">
  <meta name="MobileOptimized" content="320">
  <meta name="viewport" content="width=device-width, target-densitydpi=160dpi, initial-scale=1.0, maximum-scale=1, user-scalable=no, minimal-ui">

PAD2048

0

0

Evolve the cards and get the Dragon Lord!

      New Game

			HELPER:&nbsp
			Hint

			Auto Play

	        Keep going
            Try again
            Yes
            No

      How to play: Use your arrow keys to move the cards. When two cards with the same icon touch, they evolve into one!

			HELPER:&nbsp
			Hint

			Auto Play

        春哥株式會社, based on 2048 by Gabriele Cirulli,
        and the original epic game Threes.


text:
#ifndef QQNXTHEME_H
#define QQNXTHEME_H

#include <qpa/qplatformtheme.h>

#include <QtGui/qfont.h>

#include <QtCore/qhash.h>
#include <QtCore/qstring.h>

QT_BEGIN_NAMESPACE

class QQnxIntegration;

class QQnxTheme : public QPlatformTheme
{
public:
    explicit QQnxTheme(const QQnxIntegration *);
    ~QQnxTheme();

    static QString name() { return QStringLiteral("blackberry"); }

    bool usePlatformNativeDialog(DialogType type) const;
    QPlatformDialogHelper *createPlatformDialogHelper(DialogType type) const;

    const QFont *font(Font type = SystemFont) const;

private:
    mutable QHash<QPlatformTheme::Font, QFont*> m_fonts;
    const QQnxIntegration *m_integration;
};

QT_END_NAMESPACE

#endif // QQNXTHEME_H


text:
import { User } from './user';
import { RequestOptionsArgs, URLSearchParams } from '@angular/http';
import { RequestMethod } from '@angular/http/src/enums';
import { NavigationExtras, ParamMap } from '@angular/router';
import { Util } from './../util';

/**
 * Created by ka-yamao
 */

export class Condition {
    private _user: string;
    private _sort: number;
    private _term: number;
    private _kwd: string;
    private _pg: number;

    public get user(): string {
        return this._user;
    }
    public set user(user: string) {
        this._user = user;
    }
    public get sort(): number {
        return this._sort;
    }
    public set sort(sort: number) {
        this._sort = sort;
    }
    public get term(): number {
        return this._term;
    }
    public set term(term: number) {
        this._term = term;
    }
    public get kwd(): string {
        return this._kwd;
    }
    public set kwd(kwd: string) {
        this._kwd = kwd;
    }
    public get pg(): number {
        return this._pg;
    }
    public set pg(pg: number) {
        this._pg = pg;
    }

    public setUserCodition(userId: string): void {
        // ユーザー
        if (!Util.isEmpty(userId)) {
            this.user = userId;
        } else {
            this.user = '';
        }
    }
    public setCondition(paramMap: ParamMap): void {

        // キーワード
        if (!Util.isEmpty(paramMap.get('kwd')) && paramMap.get('kwd').length < 200) {
            this.kwd = paramMap.get('kwd');
        } else {
            this.kwd = '';
        }

        // 期間
        if (Util.isQueryParamNum(paramMap.get('term'))) {
            this.term = Number(paramMap.get('term'));
        } else {
            this.term = 0;
        }

        // 並び順
        if (Util.isQueryParamNum(paramMap.get('sort'))) {
            this.sort = Number(paramMap.get('sort'));
        } else {
            this.sort = 0;
        }

        // ページング
        if (Util.isQueryParamNum(paramMap.get('pg'))) {
            this.pg = Number(paramMap.get('pg'));
        } else {
            this.pg = 0;
        }

        // ユーザー
        if (!Util.isEmpty(paramMap.get('user'))) {
            this.user = paramMap.get('user');
        } else {
            this.user = '';
        }

        // console.log(this);

        return;
    }

    /**
     * APIリクエストパラメータを設定
     */
    public get serchParam(): any {

        let headers = new Headers();
        headers.append('Content-Type', 'application/json');
        let params = new URLSearchParams();
        params.append('kwd', this.kwd);
        params.append('term', String(this.term));
        params.append('sort', String(this.sort));
        params.append('pg', String(this.pg));
        params.append('user', String(this.user));

        return { headers: headers, search: params };
    }

    /**
     * URL変更用のパラメーター
     *
     */
    public get naviParam(): NavigationExtras {

        let query: any = {};

        // キーワード
        if (!Util.isEmpty(this.kwd) && this.kwd.length < 200) {
            query.kwd = this.kwd
        }

        // 期間
        if (Util.isQueryParamNumMin(this.term, 1)) {
            query.term = String(this.term)
        }

        // 並び順
        if (Util.isQueryParamNumMin(this.sort, 1)) {
            query.sort = String(this.sort)
        }

        // ページング
        if (Util.isQueryParamNumMin(this.pg, 1)) {
            query.pg = this.pg
        }

        let navigationExtras: NavigationExtras = {
            queryParams: query
        }

        return navigationExtras;

    }

}