text:
// Copyright (C) 2014 - 2016 ENSIME Contributors
// Licence: Apache-2.0
package org.ensime

import Imports._
import SExpFormatter._
import java.io.FileNotFoundException
import java.lang.management.ManagementFactory
import sbt._
import sbt.IO._
import sbt.Keys._
import sbt.complete.Parsers._
import scala.collection.JavaConverters._
import scala.util._
import scalariform.formatter.preferences._

/**
 * Conventional way to define importable keys for an AutoPlugin.
 * Note that EnsimePlugin.autoImport == Imports
 */
object Imports {
  object EnsimeKeys {
    // for gen-ensime
    val name = SettingKey[String](
      "Name of the ENSIME project"
    )
    val compilerArgs = TaskKey[Seq[String]](
      "Arguments for the presentation compiler, extracted from the compiler flags."
    )
    val additionalCompilerArgs = TaskKey[Seq[String]](
      "Additional arguments for the presentation compiler."
    )
    val javaFlags = TaskKey[Seq[String]](
      "Flags to be passed to Java compiler."
    )
    val includeSourceJars = settingKey[Boolean](
      "Should source jars be included in the .ensime file."
    )
    val includeDocJars = settingKey[Boolean](
      "Should doc jars be included in the .ensime file."
    )
    val scalariform = settingKey[IFormattingPreferences](
      "Scalariform formatting preferences to use in ENSIME."
    )

    val useJar = settingKey[Boolean](
      "Use the project's jar instead of the classes directory for indexing. " +
        "Note that `proj/compile` does not produce the jar, change your workflow to use `proj/packageBin`."
    )

    val disableSourceMonitoring = settingKey[Boolean](
      "Workaround temporary performance problems on large projects."
    )
    val disableClassMonitoring = settingKey[Boolean](
      "Workaround temporary performance problems on large projects."
    )

    // used to start the REPL and assembly jar bundles of ensime-server.
    // intransitive because we don't need parser combinators, scala.xml or jline
    val scalaCompilerJarModuleIDs = settingKey[Seq[ModuleID]](
      "The artefacts to resolve for :scala-compiler-jars in gen-ensime."
    )

    // for gen-ensime-project
    val compilerProjectArgs = TaskKey[Seq[String]](
      "Arguments for the project definition presentation compiler (not possible to extract)."
    )
    val additionalProjectCompilerArgs = TaskKey[Seq[String]](
      "Additional arguments for the project definition presentation compiler."
    )

    // for debugging
    val debuggingFlag = SettingKey[String](
      "JVM flag to enable remote debugging of forked tasks."
    )
    val debuggingPort = SettingKey[Int](
      "Port for remote debugging of forked tasks."
    )

    val unmanagedSourceArchives = SettingKey[Seq[File]](
      "Source jars (and zips) to complement unmanagedClasspath. May be set for the project and its submodules."
    )
    val unmanagedJavadocArchives = SettingKey[Seq[File]](
      "Documentation jars (and zips) to complement unmanagedClasspath. May only be set for submodules."
    )

    val megaUpdate = TaskKey[Map[ProjectRef, (UpdateReport, UpdateReport)]](
      "Runs the aggregated UpdateReport for `update' and `updateClassifiers' respectively."
    )

  }
}

object EnsimePlugin extends AutoPlugin with CommandSupport {
  // ensures compiler settings are loaded before us
  override def requires = plugins.JvmPlugin
  override def trigger = allRequirements

  val autoImport = Imports

  val EnsimeInternal = config("ensime-internal").hide

  override lazy val buildSettings = Seq(
    commands += Command.args("gen-ensime", "Generate a .ensime for the project.")(genEnsime),
    commands += Command.command("gen-ensime-project", "Generate a project/.ensime for the project definition.", "")(genEnsimeProject),
    commands += Command.command("debugging", "Add debugging flags to all forked JVM processes.", "")(toggleDebugging(true)),
    commands += Command.command("debugging-off", "Remove debugging flags from all forked JVM processes.", "")(toggleDebugging(false)),
    EnsimeKeys.debuggingFlag := "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=",
    EnsimeKeys.debuggingPort := 5005,
    EnsimeKeys.javaFlags := JavaFlags,
    EnsimeKeys.compilerProjectArgs := Seq(), // https://github.com/ensime/ensime-sbt/issues/98
    EnsimeKeys.additionalProjectCompilerArgs := defaultCompilerFlags(Properties.versionNumberString),
    EnsimeKeys.scalariform := FormattingPreferences(),
    EnsimeKeys.disableSourceMonitoring := false,
    EnsimeKeys.disableClassMonitoring := false,
    EnsimeKeys.megaUpdate <<= Keys.state.flatMap { implicit s =>
      val projs = Project.structure(s).allProjectRefs
      log.info("ENSIME update. Please vote for https://github.com/sbt/sbt/issues/2266")
      for {
        updateReport <- update.forAllProjects(s, projs)
        _ = log.info("ENSIME updateClassifiers. Please vote for https://github.com/sbt/sbt/issues/1930")
        updateClassifiersReport <- updateClassifiers.forAllProjects(s, projs)
      } yield {
        projs.map { p =>
          (p, (updateReport(p), updateClassifiersReport(p)))
        }.toMap
      }
    }
  )

  override lazy val projectSettings = Seq(
    EnsimeKeys.unmanagedSourceArchives := Nil,
    EnsimeKeys.unmanagedJavadocArchives := Nil,
    EnsimeKeys.includeSourceJars := true,
    EnsimeKeys.includeDocJars := true,

    EnsimeKeys.useJar := false,

    // Even though these are Global in ENSIME (until
    // https://github.com/ensime/ensime-server/issues/1152) if these
    // are in buildSettings, then build.sbt projects don't see the
    // right scalaVersion unless they used `in ThisBuild`, which is
    // too much to ask of .sbt users.
    EnsimeKeys.additionalCompilerArgs := defaultCompilerFlags((scalaVersion).value),
    EnsimeKeys.compilerArgs := (scalacOptions in Compile).value,

    ivyConfigurations += EnsimeInternal,
    // must be here where the ivy config is defined
    EnsimeKeys.scalaCompilerJarModuleIDs := Seq(
      "org.scala-lang" % "scala-compiler" % scalaVersion.value,
      "org.scala-lang" % "scala-library" % scalaVersion.value,
      "org.scala-lang" % "scala-reflect" % scalaVersion.value,
      "org.scala-lang" % "scalap" % scalaVersion.value
    ).map(_ % EnsimeInternal.name intransitive ()),
    libraryDependencies ++= EnsimeKeys.scalaCompilerJarModuleIDs.value
  )

  def defaultCompilerFlags(scalaVersion: String): Seq[String] = Seq(
    "-feature",
    "-deprecation",
    "-Xlint",
    "-Yinline-warnings",
    "-Yno-adapted-args",
    "-Ywarn-dead-code",
    "-Ywarn-numeric-widen",
    //"-Ywarn-value-discard", // more annoying than useful
    "-Xfuture"
  ) ++ {
      CrossVersion.partialVersion(scalaVersion) match {
        case Some((2, v)) if v >= 11 => Seq("-Ywarn-unused-import")
        case _                       => Nil
      }
    }

  // it would be good if debugging-off was automatically triggered
  // https://stackoverflow.com/questions/32350617
  def toggleDebugging(enable: Boolean): State => State = { implicit state: State =>
    val extracted = Project.extract(state)

    implicit val pr = extracted.currentRef
    implicit val bs = extracted.structure

    if (enable) {
      val port = EnsimeKeys.debuggingPort.gimme
      log.warn(s"Enabling debugging for all forked processes on port $port")
      log.info("Only one process can use the port and it will await a connection before proceeding.")
    }

    val newSettings = extracted.structure.allProjectRefs map { proj =>
      val orig = (javaOptions in proj).run
      val debugFlags = ((EnsimeKeys.debuggingFlag in proj).gimme + (EnsimeKeys.debuggingPort in proj).gimme)
      val withoutDebug = orig.diff(List(debugFlags))
      val withDebug = withoutDebug :+ debugFlags
      val rewritten = if (enable) withDebug else withoutDebug

      (javaOptions in proj) := rewritten
    }
    extracted.append(newSettings, state)
  }

  def genEnsime: (State, Seq[String]) => State = { (state, args) =>
    val extracted = Project.extract(state)
    implicit val st = state
    implicit val pr = extracted.currentRef
    implicit val bs = extracted.structure

    // no way to detect this value later on unless we capture it
    val scalaV = (scalaVersion).gimme

    def transitiveProjects(ref: ProjectRef): Set[ProjectRef] = {
      val proj = Project.getProjectForReference(ref, bs).get
      Set(ref) ++ proj.dependencies.flatMap { dep =>
        transitiveProjects(dep.project)
      }
    }

    val active =
      if (args.isEmpty) bs.allProjectRefs
      else args.flatMap { name =>
        val ref = bs.allProjectRefs.find(_.project == name).getOrElse {
          throw new IllegalArgumentException(s"$name is not a valid project id")
        }
        transitiveProjects(ref)
      }

    val projects = active.flatMap { ref =>
      Project.getProjectForReference(ref, bs).map((ref, _))
    }.toMap

    val updateReports = EnsimeKeys.megaUpdate.run

    val scalaCompilerJars = updateReports.head._2._1.select(
      configuration = configurationFilter(EnsimeInternal.name),
      artifact = artifactFilter(extension = Artifact.DefaultExtension)
    ).toSet

    implicit val rawModules = projects.collect {
      case (ref, proj) =>
        val (updateReport, updateClassifiersReport) = updateReports(ref)
        val module = projectData(scalaV, proj, updateReport, updateClassifiersReport)(ref, bs, state)
        (module.name, module)
    }.toMap

    val modules: Map[String, EnsimeModule] = rawModules.mapValues { m =>
      val deps = m.dependencies
      // restrict jars to immediate deps at each module
      m.copy(
        compileJars = m.compileJars -- deps.flatMap(_.compileJars),
        testJars = m.testJars -- deps.flatMap(_.testJars),
        runtimeJars = m.runtimeJars -- deps.flatMap(_.runtimeJars),
        sourceJars = m.sourceJars -- deps.flatMap(_.sourceJars),
        docJars = m.docJars -- deps.flatMap(_.docJars)
      )
    }

    val root = file(Properties.userDir)
    val out = file(".ensime")
    val cacheDir = file(".ensime_cache")
    val name = (EnsimeKeys.name).gimmeOpt.getOrElse {
      if (modules.size == 1) modules.head._2.name
      else root.getAbsoluteFile.getName
    }
    val compilerArgs = {
      (EnsimeKeys.compilerArgs).run.toList ++
        (EnsimeKeys.additionalCompilerArgs).run
    }.distinct
    val javaH = (javaHome).gimme.getOrElse(JdkDir)
    val javaSrc = {
      file(javaH.getAbsolutePath + "/src.zip") match {
        case f if f.exists => List(f)
        case _ =>
          log.warn(s"No Java sources detected in $javaH (your ENSIME experience will not be as good as it could be.)")
          Nil
      }
    } ++ EnsimeKeys.unmanagedSourceArchives.gimme
    val javaFlags = EnsimeKeys.javaFlags.run.toList

    val formatting = EnsimeKeys.scalariform.gimmeOpt
    val disableSourceMonitoring = (EnsimeKeys.disableSourceMonitoring).gimme
    val disableClassMonitoring = (EnsimeKeys.disableClassMonitoring).gimme

    val config = EnsimeConfig(
      root, cacheDir,
      scalaCompilerJars,
      name, scalaV, compilerArgs,
      modules, javaH, javaFlags, javaSrc, formatting,
      disableSourceMonitoring, disableClassMonitoring
    )

    // workaround for Windows
    write(out, toSExp(config).replaceAll("\r\n", "\n") + "\n")

    if (ignoringSourceDirs.nonEmpty) {
      log.warn(
        s"""Some source directories do not exist and will be ignored by ENSIME.
           |For example: ${ignoringSourceDirs.take(5).mkString(",")} """.stripMargin
      )
    }

    state
  }

  // sbt reports a lot of source directories that the user never
  // intends to use we want to create a report
  var ignoringSourceDirs = Set.empty[File]
  def filteredSources(sources: Set[File], scalaBinaryVersion: String): Set[File] = synchronized {
    ignoringSourceDirs ++= sources.filterNot { dir =>
      // ignoring to ignore a bunch of things that most people don't care about
      val n = dir.getName
      dir.exists() ||
        n.endsWith("-" + scalaBinaryVersion) ||
        n.endsWith("java") ||
        dir.getPath.contains("src_managed")
    }
    sources.filter(_.exists())
  }

  def projectData(
    scalaV: String,
    project: ResolvedProject,
    updateReport: UpdateReport,
    updateClassifiersReport: UpdateReport
  )(
    implicit
    projectRef: ProjectRef,
    buildStruct: BuildStructure,
    state: State
  ): EnsimeModule = {
    log.info(s"ENSIME processing ${project.id} (${name.gimme})")

    val builtInTestPhases = Set(Test, IntegrationTest)
    val testPhases = {
      for {
        phase <- ivyConfigurations.gimme
        if !phase.name.toLowerCase.contains("internal")
        if builtInTestPhases(phase) | builtInTestPhases.intersect(phase.extendsConfigs.toSet).nonEmpty
      } yield phase
    }.toSet

    def sourcesFor(config: Configuration) = {
      // invoke source generation so we can filter on existing directories
      (managedSources in config).runOpt
      (managedSourceDirectories in config).gimmeOpt.map(_.toSet).getOrElse(Set()) ++
        (unmanagedSourceDirectories in config).gimmeOpt.getOrElse(Set())
    }

    def targetFor(config: Configuration) =
      if (EnsimeKeys.useJar.gimme) (artifactPath in (config, packageBin)).gimme
      else (classDirectory in config).gimme

    def targetForOpt(config: Configuration) =
      if (EnsimeKeys.useJar.gimme) (artifactPath in (config, packageBin)).gimmeOpt
      else (classDirectory in config).gimmeOpt

    val myDoc = (artifactPath in (Compile, packageDoc)).gimmeOpt

    def configFilter(config: Configuration): ConfigurationFilter = {
      val c = config.name.toLowerCase
      val internal = EnsimeInternal.name
      if (sbtPlugin.gimme) configurationFilter(("provided" | c) - internal)
      else configurationFilter(c - internal)
    }

    def jarsFor(config: Configuration) = updateReport.select(
      configuration = configFilter(config),
      artifact = artifactFilter(extension = Artifact.DefaultExtension)
    ).toSet

    def unmanagedJarsFor(config: Configuration) =
      (unmanagedJars in config).runOpt.map(_.map(_.data).toSet).getOrElse(Set())

    def jarSrcsFor(config: Configuration) = if (EnsimeKeys.includeSourceJars.gimme) {
      updateClassifiersReport.select(
        configuration = configFilter(config),
        artifact = artifactFilter(classifier = Artifact.SourceClassifier)
      ).toSet ++ (EnsimeKeys.unmanagedSourceArchives in projectRef).gimme
    } else {
      (EnsimeKeys.unmanagedSourceArchives in projectRef).gimme
    }

    def jarDocsFor(config: Configuration) = if (EnsimeKeys.includeDocJars.gimme) {
      updateClassifiersReport.select(
        configuration = configFilter(config),
        artifact = artifactFilter(classifier = Artifact.DocClassifier)
      ).toSet ++ (EnsimeKeys.unmanagedJavadocArchives in projectRef).gimme
    } else {
      (EnsimeKeys.unmanagedJavadocArchives in projectRef).gimme
    }
    val sbv = scalaBinaryVersion.gimme
    val mainSources = filteredSources(sourcesFor(Compile) ++ sourcesFor(Provided) ++ sourcesFor(Optional), sbv)
    val testSources = filteredSources(testPhases.flatMap(sourcesFor), sbv)
    val mainTarget = targetFor(Compile)
    val testTargets = testPhases.flatMap(targetForOpt).toSet
    val deps = project.dependencies.map(_.project.project).toSet
    val mainJars = jarsFor(Compile) ++ unmanagedJarsFor(Compile) ++ jarsFor(Provided) ++ jarsFor(Optional)
    val runtimeJars = jarsFor(Runtime) ++ unmanagedJarsFor(Runtime) -- mainJars
    val testJars = {
      testPhases.flatMap {
        phase => jarsFor(phase) ++ unmanagedJarsFor(phase)
      }
    } -- mainJars
    val jarSrcs = testPhases.flatMap(jarSrcsFor)
    val jarDocs = testPhases.flatMap(jarDocsFor) ++ myDoc

    if (scalaV != scalaVersion.gimme) {
      if (System.getProperty("ensime.sbt.debug") != null) {
        // for testing
        IO.touch(file("scalaVersionAtStartupWarning"))
      }

      log.error(
        s"""You have a different version of scala for your build (${scalaV}) and ${project.id} (${scalaVersion.gimme}).
           |It is highly likely that this is a mistake with your configuration.
           |Please read https://github.com/ensime/ensime-sbt/issues/138""".stripMargin
      )
    }

    EnsimeModule(
      project.id, mainSources, testSources, Set(mainTarget), testTargets, deps,
      mainJars, runtimeJars, testJars, jarSrcs, jarDocs
    )
  }

  def genEnsimeProject: State => State = { implicit state: State =>
    val extracted = Project.extract(state)

    implicit val pr = extracted.currentRef
    implicit val bs = extracted.structure

    val jars = for {
      unit <- bs.units
      file <- unit._2.classpath
      if !file.isDirectory() & file.getName.endsWith(Artifact.DefaultExtension)
    } yield file

    val targets = for {
      unit <- bs.units
      dir <- unit._2.classpath
      if dir.isDirectory()
    } yield dir

    val classifiers = for {
      config <- updateSbtClassifiers.run.configurations
      module <- config.modules
      artefact <- module.artifacts
    } yield artefact

    val srcs = classifiers.collect {
      case (artefact, file) if artefact.classifier == Some(Artifact.SourceClassifier) => file
    }
    // they don't seem to publish docs...
    val docs = classifiers.collect {
      case (artefact, file) if artefact.classifier == Some(Artifact.DocClassifier) => file
    }

    val root = file(Properties.userDir) / "project"
    val out = root / ".ensime"
    val cacheDir = root / ".ensime_cache"
    val name = EnsimeKeys.name.gimmeOpt.getOrElse {
      file(Properties.userDir).getName + "-project"
    }

    val compilerArgs = {
      EnsimeKeys.compilerProjectArgs.run.toList ++
        EnsimeKeys.additionalProjectCompilerArgs.run
    }.distinct
    val scalaV = Properties.versionNumberString
    val javaSrc = JdkDir / "src.zip" match {
      case f if f.exists => List(f)
      case _             => Nil
    }
    val javaFlags = EnsimeKeys.javaFlags.run.toList

    val formatting = EnsimeKeys.scalariform.gimmeOpt

    val module = EnsimeModule(
      name, Set(root), Set.empty, targets.toSet, Set.empty, Set.empty,
      jars.toSet, Set.empty, Set.empty, srcs.toSet, docs.toSet
    )

    val scalaCompilerJars = jars.filter { file =>
      val f = file.getName
      f.startsWith("scala-library") ||
        f.startsWith("scala-compiler") ||
        f.startsWith("scala-reflect") ||
        f.startsWith("scalap")
    }.toSet

    val config = EnsimeConfig(
      root, cacheDir,
      scalaCompilerJars,
      name, scalaV, compilerArgs,
      Map(module.name -> module), JdkDir, javaFlags, javaSrc, formatting,
      false, false
    )

    write(out, toSExp(config).replaceAll("\r\n", "\n") + "\n")

    state
  }

  // WORKAROUND: https://github.com/typelevel/scala/issues/75
  lazy val JdkDir: File = List(
    // manual
    sys.env.get("JDK_HOME"),
    sys.env.get("JAVA_HOME"),
    // osx
    Try("/usr/libexec/java_home".!!.trim).toOption,
    // fallback
    sys.props.get("java.home").map(new File(_).getParent),
    sys.props.get("java.home")
  ).flatten.filter { n =>
      new File(n + "/lib/tools.jar").exists
    }.headOption.map(new File(_)).getOrElse(
      throw new FileNotFoundException(
        """Could not automatically find the JDK/lib/tools.jar.
      |You must explicitly set JDK_HOME or JAVA_HOME.""".stripMargin
      )
    )

  lazy val JavaFlags = {
    // WORKAROUND https://github.com/ensime/ensime-sbt/issues/91
    val raw = ManagementFactory.getRuntimeMXBean.getInputArguments.asScala.toList.map {
      case "-Xss1M" => "-Xss2m"
      case flag     => flag
    }
    raw.find { flag => flag.startsWith("-Xss") } match {
      case Some(has) => raw
      case None      => "-Xss2m" :: raw
    }
  }

}

case class EnsimeConfig(
  root: File,
  cacheDir: File,
  scalaCompilerJars: Set[File],
  name: String,
  scalaVersion: String,
  compilerArgs: List[String],
  modules: Map[String, EnsimeModule],
  javaHome: File,
  javaFlags: List[String],
  javaSrc: List[File],
  formatting: Option[IFormattingPreferences],
  disableSourceMonitoring: Boolean,
  disableClassMonitoring: Boolean
)

case class EnsimeModule(
  name: String,
  mainRoots: Set[File],
  testRoots: Set[File],
  targets: Set[File],
  testTargets: Set[File],
  dependsOnNames: Set[String],
  compileJars: Set[File],
  runtimeJars: Set[File],
  testJars: Set[File],
  sourceJars: Set[File],
  docJars: Set[File]
) {

  def dependencies(implicit lookup: String => EnsimeModule): Set[EnsimeModule] =
    dependsOnNames map lookup

}

trait CommandSupport {
  this: AutoPlugin =>

  import sbt._
  import IO._

  protected def fail(errorMessage: String)(implicit state: State): Nothing = {
    state.log.error(errorMessage)
    throw new IllegalArgumentException()
  }

  protected def log(implicit state: State) = state.log

  // our version of http://stackoverflow.com/questions/25246920
  protected implicit class RichSettingKey[A](key: SettingKey[A]) {
    def gimme(implicit pr: ProjectRef, bs: BuildStructure, s: State): A =
      gimmeOpt getOrElse { fail(s"Missing setting: ${key.key.label}") }
    def gimmeOpt(implicit pr: ProjectRef, bs: BuildStructure, s: State): Option[A] =
      key in pr get bs.data
  }

  protected implicit class RichTaskKey[A](key: TaskKey[A]) {
    def run(implicit pr: ProjectRef, bs: BuildStructure, s: State): A =
      runOpt.getOrElse { fail(s"Missing task key: ${key.key.label}") }
    def runOpt(implicit pr: ProjectRef, bs: BuildStructure, s: State): Option[A] =
      EvaluateTask(bs, key, s, pr).map(_._2) match {
        case Some(Value(v)) => Some(v)
        case _              => None
      }

    def forAllProjects(state: State, projects: Seq[ProjectRef]): Task[Map[ProjectRef, A]] = {
      val tasks = projects.flatMap(p => key.in(p).get(Project.structure(state).data).map(_.map(it => (p, it))))
      std.TaskExtra.joinTasks(tasks).join.map(_.toMap)
    }
  }

}

// direct formatter to deal with a small number of domain objects
// if we had to do this for general objects, it would make sense
// to create a series of implicit convertors to an SExp hierarchy
object SExpFormatter {

  def toSExp(s: String): String =
    "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"") + "\""

  def toSExp(f: File): String = toSExp(f.getAbsolutePath)

  def fsToSExp(ss: Iterable[File]): String =
    if (ss.isEmpty) "nil"
    else ss.toSeq.sortBy { f => f.getName + f.getPath }.map(toSExp).mkString("(", " ", ")")

  def ssToSExp(ss: Iterable[String]): String =
    if (ss.isEmpty) "nil"
    else ss.toSeq.map(toSExp).mkString("(", " ", ")")

  def msToSExp(ss: Iterable[EnsimeModule]): String =
    if (ss.isEmpty) "nil"
    else ss.toSeq.sortBy(_.name).map(toSExp).mkString("(", " ", ")")

  def fToSExp(key: String, op: Option[File]): String =
    op.map { f => s":$key ${toSExp(f)}" }.getOrElse("")

  def sToSExp(key: String, op: Option[String]): String =
    op.map { f => s":$key ${toSExp(f)}" }.getOrElse("")

  def toSExp(b: Boolean): String = if (b) "t" else "nil"

  def toSExp(o: Option[IFormattingPreferences]): String = o match {
    case None                                => "nil"
    case Some(f) if f.preferencesMap.isEmpty => "nil"
    case Some(f) => f.preferencesMap.map {
      case (desc, v: Boolean) =>
        s":${desc.key} ${toSExp(v)}"
      case (desc, v: Int) =>
        s":${desc.key} $v"
    }.mkString("(", " ", ")")
  }

  // a lot of legacy key names and conventions
  def toSExp(c: EnsimeConfig): String = s"""(
 :root-dir ${toSExp(c.root)}
 :cache-dir ${toSExp(c.cacheDir)}
 :scala-compiler-jars ${fsToSExp(c.scalaCompilerJars)}
 :name "${c.name}"
 :java-home ${toSExp(c.javaHome)}
 :java-flags ${ssToSExp(c.javaFlags)}
 :reference-source-roots ${fsToSExp(c.javaSrc)}
 :scala-version ${toSExp(c.scalaVersion)}
 :compiler-args ${ssToSExp(c.compilerArgs)}
 :formatting-prefs ${toSExp(c.formatting)}
 :disable-source-monitoring ${toSExp(c.disableSourceMonitoring)}
 :disable-class-monitoring ${toSExp(c.disableClassMonitoring)}
 :subprojects ${msToSExp(c.modules.values)}
)"""

  // a lot of legacy key names and conventions
  def toSExp(m: EnsimeModule): String = s"""(
   :name ${toSExp(m.name)}
   :source-roots ${fsToSExp((m.mainRoots ++ m.testRoots))}
   :targets ${fsToSExp(m.targets)}
   :test-targets ${fsToSExp(m.testTargets)}
   :depends-on-modules ${ssToSExp(m.dependsOnNames.toList.sorted)}
   :compile-deps ${fsToSExp(m.compileJars)}
   :runtime-deps ${fsToSExp(m.runtimeJars)}
   :test-deps ${fsToSExp(m.testJars)}
   :doc-jars ${fsToSExp(m.docJars)}
   :reference-source-roots ${fsToSExp(m.sourceJars)})"""
}


text:
<?php
namespace Czim\CmsModels\Exceptions;

class StrategyResolutionException extends \Exception
{
}

redpajama_set_name: RedPajamaGithub


text:
layout: team
title:  "David Hager"
date:   2013-12-30 16:22:48
categories: inholland
excerpt: Een alleskunner gespecialiseerd in het samenbrengen van mensen en ideeën
description: I am a graphic desigher from The Netherlands, working for my self since 2009 and recently under the name Studio 210 as a collective of creative designer and developers.
website: http://www.atmedia.nl
phone: +31 (0) 6 10 11 41 79
email: davidhager@gmail.com
twitter_username: atmedia
github_username:
linkedin_username: davidJhager
order: 2
---
All-round marketing- en communicatieprofessional David Hager is de stuwende kracht van Alloy. Met zijn hands-on mentaliteit en positieve karakter slaat hij een brug tussen de verschillende talenten om gezamenlijk projecten van de grond te tillen. Zowel in de rol als projectleider voor online projecten als producer voor film- en animatieproducties. Bij voorkeur de combinatie; een cross-over waarbij design, online en video naadloos in elkaar overvloeien en de pixels op het beeldscherm een onvergetelijk verhaal overbrengen. Kortweg, creative storytelling.

Met ruim 10 jaar ervaring als marketing- en communicatieadviseur en sinds 2010 actief als ondernemer adviseert David zijn opdrachtgevers bij het maken keuzes om hun verhaal goed over te brengen. Hij werkt activerend en weet geruisloos projecten en campagnes te coördineren.

Enkele opdrachtgevers waar David voor werkt(e) zijn o.a. Talpa-RTL, Stichting CliniClowns, KWF Kankerbestrijding, DSM, Boehringer Ingelheim en Corpus Reis door de Mens.


text:
<?php

final class ArcanistPlusOperatorOnStringsXHPASTLinterRule
  extends ArcanistXHPASTLinterRule {

  const ID = 21;

  public function getLintName() {
    return pht('Not String Concatenation');
  }

  public function process(XHPASTNode $root) {
    $binops = $root->selectDescendantsOfType('n_BINARY_EXPRESSION');

    foreach ($binops as $binop) {
      $op = $binop->getChildByIndex(1);
      if ($op->getConcreteString() !== '+') {
        continue;
      }

      $left = $binop->getChildByIndex(0);
      $right = $binop->getChildByIndex(2);

      if ($left->getTypeName() === 'n_STRING_SCALAR' ||
          $right->getTypeName() === 'n_STRING_SCALAR') {
        $this->raiseLintAtNode(
          $binop,
          pht(
            "In PHP, '%s' is the string concatenation operator, not '%s'. ".
            "This expression uses '+' with a string literal as an operand.",
            '.',
            '+'));
      }
    }
  }

}


text:
package sbt

/** Defines a function to call as sbt exits.*/
trait ExitHook
{
	/** Subclasses should implement this method, which is called when this hook is executed. */
	def runBeforeExiting(): Unit
}
object ExitHook
{
	def apply(f: => Unit): ExitHook = new ExitHook { def runBeforeExiting() = f }
}

object ExitHooks
{
	/** Calls each registered exit hook, trapping any exceptions so that each hook is given a chance to run. */
	def runExitHooks(exitHooks: Seq[ExitHook]): Seq[Throwable] =
		exitHooks.flatMap( hook =>
			ErrorHandling.wideConvert( hook.runBeforeExiting() ).left.toOption
		)
}


text:
"use strict";
// In order to keep refactoring low, simply export from ast-tools.
// TODO: move all dependencies of this file to ast-tools directly.
var ast_tools_1 = require('@angular-cli/ast-tools');
exports.getSource = ast_tools_1.getSource;
exports.getSourceNodes = ast_tools_1.getSourceNodes;
exports.findNodes = ast_tools_1.findNodes;
exports.insertAfterLastOccurrence = ast_tools_1.insertAfterLastOccurrence;
exports.getContentOfKeyLiteral = ast_tools_1.getContentOfKeyLiteral;
exports.getDecoratorMetadata = ast_tools_1.getDecoratorMetadata;
exports.addDeclarationToModule = ast_tools_1.addDeclarationToModule;
exports.addProviderToModule = ast_tools_1.addProviderToModule;
//# sourceMappingURL=/Users/hans/Sources/angular-cli/packages/angular-cli/utilities/ast-utils.js.map


text:
import itertools
from .itertoolz import frequencies, pluck, getter
from .compatibility import map

__all__ = ('countby', 'partitionby')

def countby(key, seq):
    """ Count elements of a collection by a key function
    >>> countby(len, ['cat', 'mouse', 'dog'])
    {3: 2, 5: 1}
    >>> def iseven(x): return x % 2 == 0
    >>> countby(iseven, [1, 2, 3])  # doctest:+SKIP
    {True: 1, False: 2}
    See Also:
        groupby
    """
    if not callable(key):
        key = getter(key)
    return frequencies(map(key, seq))

def partitionby(func, seq):
    """ Partition a sequence according to a function
    Partition `s` into a sequence of lists such that, when traversing
    `s`, every time the output of `func` changes a new list is started
    and that and subsequent items are collected into that list.
    >>> is_space = lambda c: c == " "
    >>> list(partitionby(is_space, "I have space"))
    [('I',), (' ',), ('h', 'a', 'v', 'e'), (' ',), ('s', 'p', 'a', 'c', 'e')]
    >>> is_large = lambda x: x > 10
    >>> list(partitionby(is_large, [1, 2, 1, 99, 88, 33, 99, -1, 5]))
    [(1, 2, 1), (99, 88, 33, 99), (-1, 5)]
    See also:
        partition
        groupby
        itertools.groupby
    """
    return map(tuple, pluck(1, itertools.groupby(seq, key=func)))


text:
#ifdef USE_TI_PLATFORM

#import "TiProxy.h"

@interface TiPlatformDisplayCaps : TiProxy {

}

@property(nonatomic,readonly) NSNumber* platformHeight;
@property(nonatomic,readonly) NSNumber* platformWidth;
@property(nonatomic,readonly) NSNumber* density;
@property(nonatomic,readonly) NSString* dpi;
@property(nonatomic,readonly) NSNumber* logicalDensityFactor;

@end

#endif


text:
package com.intellij.ide.util.importProject;

import com.intellij.ide.highlighter.ModuleFileType;
import com.intellij.ide.util.projectWizard.ModuleBuilder;
import com.intellij.ide.util.projectWizard.importSources.DetectedProjectRoot;
import com.intellij.ide.util.projectWizard.importSources.DetectedSourceRoot;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleType;
import com.intellij.openapi.roots.ModifiableRootModel;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.util.SmartList;
import com.intellij.util.containers.MultiMap;
import com.intellij.util.text.CaseInsensitiveStringHashingStrategy;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.*;

/**
 * @author Eugene Zhuravlev
*/
public class ModuleDescriptor {
  private String myName;
  private final MultiMap<File, DetectedSourceRoot> myContentToSourceRoots = new MultiMap<>();
  private final Set<File> myLibraryFiles = new HashSet<>();
  private final Set<ModuleDescriptor> myDependencies = new HashSet<>();
  private static final Set<String> ourModuleNameStopList = new THashSet<>(
    Arrays.asList("java", "src", "source", "sources", "C:", "D:", "E:", "F:", "temp", "tmp"),
    CaseInsensitiveStringHashingStrategy.INSTANCE
  );

  private boolean myReuseExistingElement;
  private final List<ModuleBuilder.ModuleConfigurationUpdater> myConfigurationUpdaters = new SmartList<>();
  private final ModuleType myModuleType;

  public ModuleDescriptor(final File contentRoot, final ModuleType moduleType, final Collection<? extends DetectedSourceRoot> sourceRoots) {
    myName = suggestModuleName(contentRoot);
    myContentToSourceRoots.putValues(contentRoot, sourceRoots);
    myModuleType = moduleType;
  }

  public ModuleDescriptor(final File contentRoot, final ModuleType moduleType,
                          final DetectedSourceRoot sourceRoot) {
    this(contentRoot, moduleType, Collections.singletonList(sourceRoot));
  }

  public void reuseExisting(boolean reuseExistingElement) {
    myReuseExistingElement = reuseExistingElement;
  }

  public void addConfigurationUpdater(ModuleBuilder.ModuleConfigurationUpdater updater) {
    myConfigurationUpdaters.add(updater);
  }

  public void updateModuleConfiguration(Module module, ModifiableRootModel rootModel) {
    for (ModuleBuilder.ModuleConfigurationUpdater updater : myConfigurationUpdaters) {
      updater.update(module, rootModel);
    }
  }

  public boolean isReuseExistingElement() {
    return myReuseExistingElement;
  }

  public ModuleType getModuleType() {
    return myModuleType;
  }

  private static String suggestModuleName(final File contentRoot) {
    for (File dir = contentRoot; dir != null; dir = dir.getParentFile()) {
      final String suggestion = dir.getName();
      if (!ourModuleNameStopList.contains(suggestion)) {
        return suggestion;
      }
    }

    return contentRoot.getName();
  }

  public String getName() {
    return myName;
  }

  public void setName(final String name) {
    myName = name;
  }

  public Set<File> getContentRoots() {
    return Collections.unmodifiableSet(myContentToSourceRoots.keySet());
  }

  public Collection<? extends DetectedProjectRoot> getSourceRoots() {
    return myContentToSourceRoots.values();
  }

  public Collection<DetectedSourceRoot> getSourceRoots(File contentRoot) {
    return myContentToSourceRoots.get(contentRoot);
  }

  public void addContentRoot(File contentRoot) {
    myContentToSourceRoots.put(contentRoot, new HashSet<>());
  }

  public Collection<DetectedSourceRoot> removeContentRoot(File contentRoot) {
    return myContentToSourceRoots.remove(contentRoot);
  }

  public void addSourceRoot(final File contentRoot, DetectedSourceRoot sourceRoot) {
    myContentToSourceRoots.putValue(contentRoot, sourceRoot);
  }

  public void addDependencyOn(ModuleDescriptor dependence) {
    myDependencies.add(dependence);
  }

  public void removeDependencyOn(ModuleDescriptor module) {
    myDependencies.remove(module);
  }

  public void addLibraryFile(File libFile) {
    myLibraryFiles.add(libFile);
  }

  public Set<File> getLibraryFiles() {
    return myLibraryFiles;
  }

  public Set<ModuleDescriptor> getDependencies() {
    return Collections.unmodifiableSet(myDependencies);
  }

  /**
   * For debug purposes only
   */
  public String toString() {
    @NonNls final StringBuilder builder = new StringBuilder();
    builder.append("[Module: ").append(getContentRoots()).append(" | ");
    for (DetectedProjectRoot sourceRoot : getSourceRoots()) {
      builder.append(sourceRoot.getDirectory().getName()).append(",");
    }
    builder.append("]");
    return builder.toString();
  }

  public void clearModuleDependencies() {
    myDependencies.clear();
  }

  public void clearLibraryFiles() {
    myLibraryFiles.clear();
  }

  @NotNull
  public String computeModuleFilePath() throws InvalidDataException {
    final String name = getName();
    final Set<File> contentRoots = getContentRoots();
    if (contentRoots.size() > 0) {
      return contentRoots.iterator().next().getPath() + File.separator + name + ModuleFileType.DOT_DEFAULT_EXTENSION;
    }
    else {
      throw new InvalidDataException("Module " + name + " has no content roots and will not be created.");
    }
  }
}


text:
declare module 'xhr' {
  interface Options {
    url: string
    json: boolean
  }

  interface Response {
    statusCode: number
    body: string
  }

  export default function xhr(
    options: Options,
    callback: (error: Error | null, response: Response, body: Object) => void
  ): XMLHttpRequest
}


text:
Basic Information

          <button data-widget="collapse" data-toggle="tooltip" title="Collapse" class="btn btn-box-tool"></button>

      <form method="post" ng-submit="updateUser(userProfile.user)">

Drop Profile Image Here

             Display Name
            <input ng-if="!editUser" type="text" ng-model="userProfile.user.displayName" class="form-control"/>
            <input ng-if="editUser" type="text" ng-model="userProfile.user.displayName" readonly="" class="form-control"/>

             Email Address
            <input ng-if="!editUser" type="email" ng-model="userProfile.user.email" class="form-control"/>
            <input ng-if="editUser" type="email" ng-model="userProfile.user.email" readonly="" class="form-control"/>

             Roles

            <multiselect ng-model="userProfile.user_roles" options="r.display_name for r in roles" data-multiple="true" scroll-after-rows="5" data-compare-by="id" change="selected()"></multiselect>

             Roles

{{role.display_name}}

            <button type="submit" class="btn btn-danger">Submit</button>

      </form>

About me

          <button data-widget="collapse" data-toggle="tooltip" title="Collapse" class="btn btn-box-tool"></button>

      <form method="post">

          <input type="hidden" ng-model="userProfile.about.user_id" class="form-control"/>

             Job position
            <input ng-if="!editUser" type="text" ng-model="userProfile.about.position" class="form-control"/>
            <input ng-if="editUser" type="text" ng-model="userProfile.about.position" readonly="" class="form-control"/>

             Education
            <input ng-if="!editUser" type="text" ng-model="userProfile.about.education" class="form-control"/>
            <input ng-if="editUser" type="text" ng-model="userProfile.about.education" readonly="" class="form-control"/>

             About me
            <textarea ng-if="!editUser" type="text" ng-model="userProfile.about.about_me" class="form-control"></textarea>
            <textarea ng-if="editUser" type="text" ng-model="userProfile.about.about_me" readonly="" class="form-control"></textarea>

            <button ng-if="!userProfile.about.user_id" type="submit" ng-click="storeProfile(userProfile.about)" class="btn btn-danger">Submit</button>
            <button ng-if="userProfile.about.user_id" type="submit" ng-click="updateProfile(userProfile.about)" class="btn btn-danger">Submit</button>

      </form>

Your Location

          <button data-widget="collapse" data-toggle="tooltip" title="Collapse" class="btn btn-box-tool"></button>

              Full Street
              City
              Post Code
              Country
              Actions

            {{loc.address}}
            {{loc.city}}
            {{loc.postCode}}
            {{loc.country}}
            Edit
              Delete

        <form method="post" ng-show="!address.Id">

             Insert your address
            <google-places address="address" ng-model="address" required="" placeholder="Street" value="Street" class="form-control"></google-places>

        </form>

          <form method="post">
            <input type="hidden" ng-model="address.Latitude" class="form-control"/>
            <input type="hidden" ng-model="address.Longitude" class="form-control"/>
            <input type="hidden" ng-model="address.Id" class="form-control"/>

               Full Address
              <input type="text" ng-model="address.FormattedAddress" placeholder="Full Address" class="form-control"/>

               Street
              <input type="text" ng-model="address.Street" placeholder="Street" class="form-control"/>

               City
              <input type="text" ng-model="address.City" placeholder="City" class="form-control"/>

               Country
              <input type="text" ng-model="address.Country" placeholder="Country" class="form-control"/>

               Postal Code
              <input type="text" ng-model="address.PostCode" placeholder="Postal Code" class="form-control"/>

              <button ng-show="!address.Id" type="submit" ng-click="storeLocation(address)" class="btn btn-danger">Submit</button>
              <button ng-show="address.Id" type="submit" ng-click="updateLocation(address)" class="btn btn-danger">Submit</button>

          </form>


text:
class ResponsesController < ApplicationController
  def create
    @query = Query.friendly.find(params[:query_id])
    if @query.responses.create(response_params)
      redirect_to query_path(@query), notice: 'Thanks for your feedback'
    else
      render 'queries/show'
    end
  end

  private

  def response_params
    params.require(:response).permit(:text)
  end
end


text:
<?php

namespace spec\LdapTools\Event;

use LdapTools\Connection\LdapConnection;
use LdapTools\DomainConfiguration;
use LdapTools\Operation\AddOperation;
use PhpSpec\ObjectBehavior;

class LdapOperationEventSpec extends ObjectBehavior
{
    function let()
    {
        $config = new DomainConfiguration('foo.bar');
        $config->setLazyBind(true);
        $connection = new LdapConnection($config);
        $operation = new AddOperation('dc=foo,dc=bar');
        $this->beConstructedWith('foo', $operation, $connection);
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('LdapTools\Event\LdapOperationEvent');
    }

    function it_should_have_type_Event()
    {
        $this->shouldHaveType('LdapTools\Event\Event');
    }

    function it_should_implement_EventInterface()
    {
        $this->shouldImplement('LdapTools\Event\EventInterface');
    }

    function it_should_get_the_event_name()
    {
        $this->getName()->shouldBeEqualTo('foo');
    }

    function it_should_get_the_operation_for_the_event()
    {
        $this->getOperation()->shouldReturnAnInstanceOf('LdapTools\Operation\LdapOperationInterface');
    }

    function it_should_get_the_connection_for_the_event()
    {
        $this->getConnection()->shouldReturnAnInstanceOf('LdapTools\Connection\LdapConnectionInterface');
    }
}


text:
<input
  telefoneMask
  type="tel"
  class="form-control"
  maxlength="16"
  [id]="id"
  [disabled]="disabled"
  [placeholder]="placeholder"
  [(ngModel)]="value"
  (ngModelChange)="notifyChanges($event)">


text:
"""pandora URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('news.urls')),
    path('news/', include('news.urls')),
    path('photo/', include('photo.urls')),
    path('download/', include('download.urls')),
    path('guestbook/', include('guestbook.urls')),
    path('video/', include('video.urls')),
    path('membership/', include('membership.urls')),
    path('score/', include('score.urls')),
    path('survey/', include('survey.urls')),
    path('exam/', include('exam.urls')),
    path('salary/', include('salary.urls')),
    path('repairs/', include('repairs.urls')),
]


text:
import React from 'react';
import CardExampleControlled from './ExpandCards';

class SpeedDeskDemo extends React.Component {
  render() {
    return (
          <div className='compact'>
            <CardExampleControlled />
              <CardExampleControlled />
                <CardExampleControlled />
                  <CardExampleControlled />
                    <CardExampleControlled />

            </div>

    );
  }
}

export default SpeedDeskDemo;


text:
layout: layouts/shell.html
section: page
---

{{ title }}

    {{ '/src/includes/assets/svg/404.svg' | svgContents("w-full") | safe }}


text:
<?php

namespace Cothema\OpeningHours\Model\Tag;

/**
 * Tag ByAgreement means that the business is opened by unspecified agreement
 * between customer and business owner.
 *
 * @author Milos Havlicek <miloshavlicek@gmail.com>
 */
class ByAgreement extends A\Tag
{

}


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraCharacter : MonoBehaviour {

	private Transform m_currentTarget;
	[SerializeField] private float m_distance = 2f;
	[SerializeField] private float m_height = 30;
	[SerializeField] private float m_lookAtAroundAngle = 0;

	[SerializeField] private List<Transform> m_targets;
	private int m_currentIndex;

	private void Start () {
		if(m_targets.Count > 0)
		{
			m_currentIndex = 0;
			m_currentTarget = m_targets[m_currentIndex];
		}
	}

	private void SwitchTarget(int step)
	{
		if(m_targets.Count == 0) { return; }
		m_currentIndex+=step;
		if (m_currentIndex > m_targets.Count-1) { m_currentIndex = 0; }
		if (m_currentIndex < 0) { m_currentIndex = m_targets.Count - 1; }
		m_currentTarget = m_targets[m_currentIndex];
	}

	public void NextTarget() { SwitchTarget(1); }
	public void PreviousTarget() { SwitchTarget(-1); }

	private void Update () {
		if (m_targets.Count == 0) { return; }
	}

	private void LateUpdate()
	{
		if(m_currentTarget == null) { return; }

		float targetHeight = m_currentTarget.position.y + m_height;
		float currentRotationAngle = m_lookAtAroundAngle;

		Quaternion currentRotation = Quaternion.Euler(0, currentRotationAngle, 0);

		Vector3 position = m_currentTarget.position;
		position -= currentRotation * Vector3.forward * m_distance;
		position -= Vector3.forward * m_distance;
		position.y = targetHeight;

		transform.position = position;
		transform.LookAt(m_currentTarget.position + new Vector3(0, m_height, 0));

	}
}


text:
Template.Layout.rendered = function() {
    // Materialize binds
    $(".button-collapse").sideNav();
    //$('.collapsible').collapsible();
    $('.modal-trigger').leanModal();
    $('.dropdown-button').dropdown({
        constrain_width: false,
        hover: false,
        alignment: 'right',
        belowOrigin: true
    });
};


text:
namespace scm {
namespace data {

volume_data::volume_data(const gl::render_device_ptr& device,
                         const std::string&           file_name,
                         const color_map_type&        cmap,
                         const alpha_map_type&        amap)
  : _transform(math::mat4f::identity())
  , _color_map(new color_map_type(cmap))
  , _alpha_map(new alpha_map_type(amap))
  , _selected_lod(0.0f)
{
    using namespace scm::gl;
    using namespace scm::math;

    out() << log::info << "volume_data::volume_data(): loading raw volume..." << log::end;
    _volume_raw = load_volume(device, file_name);
    if (!_volume_raw) {
        throw std::runtime_error("volume_data::volume_data(): error loading volume data from file: " + file_name);
    }
    _sstate_linear = device->create_sampler_state(FILTER_MIN_MAG_LINEAR, WRAP_CLAMP_TO_EDGE);
    out() << log::info << "volume_data::volume_data(): loading raw volume done." << log::end;

    out() << log::info << "volume_data::volume_data(): generating color map..." << log::end;
    _color_alpha_map = create_color_alpha_map(device, 256);
    if (!_color_alpha_map) {
        throw std::runtime_error("volume_data::volume_data(): error creating color alpha map texture.");
    }
    if (!update_color_alpha_map(device->main_context())) {
        throw std::runtime_error("volume_data::volume_data(): error upating color alpha map texture.");
    }
    _color_alpha_map_dirty = false;
    out() << log::info << "volume_data::volume_data(): generating color map done." << log::end;

    _data_dimensions = _volume_raw->descriptor()._size;
    _max_lod         = static_cast<float>(gl::util::max_mip_levels(_data_dimensions)) - 1.0f;
    unsigned max_dim = max(max(_data_dimensions.x,
                               _data_dimensions.y),
                               _data_dimensions.z);
    _extends         = vec3f(_volume_raw->descriptor()._size) / max_dim;
    _bbox            = box(math::vec3f(0.0f), _extends);
    _transform       = make_translation(-_extends / 2.0f);

    out() << log::info << "volume_data::volume_data(): generating render resources..." << log::end;
    try {
        _bbox_geometry = make_shared<box_volume_geometry>(device, _bbox.min_vertex(), _bbox.max_vertex());
        _volume_block  = make_uniform_block<volume_uniform_data>(device);
    }
    catch (const std::exception& e) {
        throw std::runtime_error(std::string("volume_data::volume_data(): error creating geometry objects: ") + e.what());
    }
    out() << log::info << "volume_data::volume_data(): generating render resources done." << log::end;

    out() << log::info << "volume_data::volume_data(): successfully loaded volume file: " << file_name << log::end;

#if SCM_TEXT_NV_BINDLESS_TEXTURES == 1
    if (   !device->main_context()->make_resident(_volume_raw, _sstate_linear)
        || !device->main_context()->make_resident(_color_alpha_map, _sstate_linear)) {
        out() << log::info << "volume_data::volume_data(): unable to make texture resident." << log::end;
    }
    else {
        _texture_handles = device->create_texture_buffer(FORMAT_RG_32UI, USAGE_STATIC_DRAW, 2 * sizeof(uint64));

        if (!_texture_handles) {
            throw std::runtime_error(std::string("volume_data::volume_data(): error creating texture_handles buffer."));
        }
        scoped_buffer_map th_map(device->main_context(), _texture_handles->descriptor()._buffer, ACCESS_WRITE_INVALIDATE_BUFFER);

        if (!th_map) {
            throw std::runtime_error(std::string("volume_data::volume_data(): error mapping texture_handles buffer."));
        }

        uint64*const th_data = reinterpret_cast<uint64*const>(th_map.data_ptr());
        th_data[0] = _volume_raw->native_handle();
        th_data[1] = _color_alpha_map->native_handle();
    }
#endif // SCM_TEXT_NV_BINDLESS_TEXTURES == 1

    sample_distance_factor(0.5f);
    sample_distance_ref_factor(0.5f);
}

volume_data::~volume_data()
{
    _bbox_geometry.reset();

    _volume_raw.reset();
    _color_alpha_map.reset();

    _volume_block.reset();
}

const math::vec3f&
volume_data::extends() const
{
    return _extends;
}

const math::vec3ui&
volume_data::data_dimensions() const
{
    return _data_dimensions;
}

const math::mat4f&
volume_data::transform() const
{
    return _transform;
}

void
volume_data::transform(const math::mat4f& m)
{
    _transform = m;
}

float
volume_data::sample_distance() const
{
    return _sample_distance;
}

void
volume_data::sample_distance_factor(float d)
{
    using namespace scm::math;

    unsigned max_dim = max(max(_data_dimensions.x,
                               _data_dimensions.y),
                               _data_dimensions.z);

    _sample_distance = d / max_dim;
}

float
volume_data::sample_distance_factor() const
{
    using namespace scm::math;

    unsigned max_dim = max(max(_data_dimensions.x,
                               _data_dimensions.y),
                               _data_dimensions.z);

    return _sample_distance * max_dim;
}

float
volume_data::sample_distance_ref() const
{
    return _sample_distance_ref;
}

void
volume_data::sample_distance_ref_factor(float d)
{
    using namespace scm::math;

    unsigned max_dim = max(max(_data_dimensions.x,
                               _data_dimensions.y),
                               _data_dimensions.z);

    _sample_distance_ref = d / max_dim;
}

float
volume_data::sample_distance_ref_factor() const
{
    using namespace scm::math;

    unsigned max_dim = max(max(_data_dimensions.x,
                               _data_dimensions.y),
                               _data_dimensions.z);

    return _sample_distance_ref * max_dim;
}

float
volume_data::min_value() const
{
    return _min_value;
}

float
volume_data::max_value() const
{
    return _max_value;
}

float
volume_data::selected_lod() const
{
    return _selected_lod;
}

void
volume_data::selected_lod(float l)
{
    _selected_lod = math::clamp(l, 0.0f, _max_lod);
}

const gl::box&
volume_data::bbox() const
{
    return _bbox;
}

const gl::box_volume_geometry_ptr&
volume_data::bbox_geometry() const
{
    return _bbox_geometry;
}

const gl::texture_buffer_ptr&
volume_data::texture_handles() const
{
    return _texture_handles;
}

const gl::texture_3d_ptr&
volume_data::volume_raw() const
{
    return _volume_raw;
}

const gl::texture_1d_ptr&
volume_data::color_alpha_map() const
{
    return _color_alpha_map;
}

const volume_data::color_map_ptr&
volume_data::color_map() const
{
    return _color_map;
}

const volume_data::alpha_map_ptr&
volume_data::alpha_map() const
{
    return _alpha_map;
}

void
volume_data::update_color_alpha_maps()
{
    _color_alpha_map_dirty = true;
}

gl::texture_3d_ptr
volume_data::load_volume(const gl::render_device_ptr& in_device,
                         const std::string&           in_file_name)
{
    using namespace scm::gl;
    using namespace scm::math;
    using namespace boost::filesystem;

    path                    file_path(in_file_name);
    std::string             file_name       = file_path.filename().string();
    std::string             file_extension  = file_path.extension().string();

    boost::algorithm::to_lower(file_extension);

    vec3ui      data_dimensions = vec3ui(0u);
    data_format data_format     = FORMAT_NULL;
    scm::shared_array<unsigned char> read_buffer;
    scm::size_t                      read_buffer_size = 0;

    scoped_ptr<gl::volume_reader> vol_reader;

    out() << log::indent;
    time::high_res_timer timer;

    if (file_extension == ".raw") {
        vol_reader.reset(new volume_reader_raw(file_path.string(), false));
    }
    else if (file_extension == ".vol") {
        vol_reader.reset(new volume_reader_vgeo(file_path.string(), true));
    }
    else if (file_extension == ".segy" || file_extension == ".sgy") {
        vol_reader.reset(new volume_reader_segy(file_path.string(), true));
    }
    else {
        err() << log::error
              << "volume_data::load_volume(): unable to open file ('" << in_file_name << "')." << log::end;
        return texture_3d_ptr();
    }

    if (!(*vol_reader)) {
        err() << log::error
                << "volume_data::load_volume(): unable to open file ('" << in_file_name << "')." << log::end;
        return texture_3d_ptr();
    }
    out() << "source data dimensions: " << vol_reader->dimensions() << log::end;

#if 0
    vec3ui data_offset = vec3ui(0u, vol_reader->dimensions().y / 2, vol_reader->dimensions().z / 2);//vol_reader->dimensions() / vec3ui(2, 2, 2);
    data_dimensions    = vol_reader->dimensions() / vec3ui(1, 20, 10);
#else
    vec3ui data_offset = vec3ui(0);
    data_dimensions    = vol_reader->dimensions();
#endif
    //data_dimensions.x  = 2048;
    data_format        = vol_reader->format();

    read_buffer_size =   static_cast<scm::size_t>(data_dimensions.x) * data_dimensions.y * data_dimensions.z
                        * size_of_format(data_format);

    read_buffer.reset(new unsigned char[read_buffer_size]);

    out() << "reading volume data "
          << "(dimensions: " << data_dimensions
          << ", size : " << std::fixed << std::setprecision(3) << static_cast<double>(read_buffer_size) / (1024.0*1024.0) << "MiB)..."
          << log::end;
    timer.start();
    if (!vol_reader->read(data_offset, data_dimensions, read_buffer.get())) {
        err() << log::error
                << "volume_data::load_volume(): unable to read data from file ('" << in_file_name << "')." << log::end;
        return texture_3d_ptr();
    }
    timer.stop();
    out() << "reading volume data done"
          << " (elapsed time: " << std::fixed << std::setprecision(3)
          << time::to_seconds(timer.get_time()) << "s, "
          << (static_cast<double>(read_buffer_size) / (1024.0*1024.0)) / time::to_seconds(timer.get_time()) << "MiB/s)" << log::end;

    _min_value = 0.0f;
    _max_value = 1.0f;
    if (is_float_type(data_format)) {
        out() << "determining floating point value range..." << log::end;
        timer.start();

        float* fp_data = reinterpret_cast<float*>(read_buffer.get());
        size_t dcount  = static_cast<scm::size_t>(data_dimensions.x) * data_dimensions.y * data_dimensions.z * channel_count(data_format);
        _min_value = boost::numeric::bounds<float>::highest();//(std::numeric_limits<float>::max)();
        _max_value = boost::numeric::bounds<float>::lowest();//(std::numeric_limits<float>::min)();

        for (size_t i = 0; i < dcount; ++i) {
            _min_value = min(_min_value, fp_data[i]);
            _max_value = max(_max_value, fp_data[i]);
        }

        if (abs(_min_value) > abs(_max_value)) {
            _max_value = abs(_min_value);
        }
        else {
            _min_value = -abs(_max_value);
        }

        timer.stop();
        out() << "etermining floating point value range"
              << " (elapsed time: " << std::fixed << std::setprecision(3)
              << time::to_seconds(timer.get_time()) << "s)" << log::end;

    }
    out() << "min_value: " << _min_value << ", max_value: " << _max_value << log::end;

    std::vector<uint8*> mip_data;
    std::vector<void*>  mip_init_data;

    out() << "generating mip map hierarchy..." << log::end;
    timer.start();
    gl::util::generate_mipmaps(data_dimensions, data_format, read_buffer.get(), mip_data);
    timer.stop();
    out() << "generating mip map hierarchy done"
          << " (elapsed time: " << std::fixed << std::setprecision(3)
          << time::to_seconds(timer.get_time()) << "s)" << log::end;

    std::for_each(mip_data.begin(), mip_data.end(), [&mip_init_data](uint8* v) {mip_init_data.push_back(v);});
    //for (std::vector<uint8*>::iterator v = mip_data.begin(); v != mip_data.end(); ++v) {
    //    mip_init_data.push_back(*v);
    //}

    unsigned mip_count = gl::util::max_mip_levels(data_dimensions);

    assert(mip_count == mip_init_data.size());

    out() << "allocating texture storage ("
          << "dimensions: " << data_dimensions << ", format: " << format_string(data_format)
          << ", mip-level: " << mip_count
          << ", size : " << std::fixed << std::setprecision(3) << static_cast<double>(read_buffer_size) / (1024.0*1024.0) << "MiB)..."
          << log::end;
    timer.start();
    texture_3d_ptr new_volume_tex = in_device->create_texture_3d(data_dimensions, data_format, mip_count, data_format, mip_init_data);
    timer.stop();
    out() << "allocating texture storage done."
          << " (elapsed time: " << std::fixed << std::setprecision(3)
          << time::to_seconds(timer.get_time()) << "s)" << log::end;

    std::for_each(mip_data.begin() + 1, mip_data.end(), [&mip_init_data](uint8* v) {delete [] v; });

    out() << log::outdent;

    return new_volume_tex;
}

gl::texture_1d_ptr
volume_data::create_color_alpha_map(const gl::render_device_ptr& in_device,
                                          unsigned               in_size) const
{
    using namespace scm::gl;
    using namespace scm::math;

    log::logger_format_saver out_save(out().associated_logger());

    out() << log::indent;
    time::high_res_timer timer;

    out() << "allocating texture storage ("
          << "dimensions: " << in_size << ", format: " << format_string(FORMAT_RGBA_8)
          << ", mip-level: " << 1
          << ", size : " << std::fixed << std::setprecision(3) << static_cast<double>(in_size * size_of_format(FORMAT_RGBA_8)) / (1024.0) << "KiB)..."
          << log::end;
    timer.start();
    texture_1d_ptr new_tex = in_device->create_texture_1d(in_size, FORMAT_RGBA_8, 1, 1);
    timer.stop();
    out() << "allocating texture storage done."
          << " (elapsed time: " << std::fixed << std::setprecision(3)
          << time::to_seconds(timer.get_time()) << "s)" << log::end;

    if (!new_tex) {
        err() << log::error
              << "volume_data::create_color_map(): error during color map texture generation." << log::end;
        return texture_1d_ptr();
    }

    return new_tex;
}

bool
volume_data::update_color_alpha_map(const gl::render_context_ptr& context) const
{
    using namespace scm::gl;
    using namespace scm::math;

    scm::scoped_array<scm::math::vec3f>  color_lut;
    scm::scoped_array<float>             alpha_lut;

    log::logger_format_saver out_save(out().associated_logger());

    out() << log::indent;
    time::high_res_timer timer;

    out() << "generating color map texture data..." << log::end;
    timer.start();

    unsigned in_size = _color_alpha_map->descriptor()._size;

    color_lut.reset(new vec3f[in_size]);
    alpha_lut.reset(new float[in_size]);

    if (   !scm::data::build_lookup_table(color_lut, *_color_map, in_size)
        || !scm::data::build_lookup_table(alpha_lut, *_alpha_map, in_size)) {
        err() << log::error
              << "volume_data::update_color_alpha_map(): error during lookuptable generation" << log::end;
        return false;
    }
    scm::scoped_array<float> combined_lut;

    combined_lut.reset(new float[in_size * 4]);

    for (unsigned i = 0; i < in_size; ++i) {
        combined_lut[i*4   ] = color_lut[i].x;
        combined_lut[i*4 +1] = color_lut[i].y;
        combined_lut[i*4 +2] = color_lut[i].z;
        combined_lut[i*4 +3] = alpha_lut[i];
    }
    timer.stop();
    out() << "generating color map texture data done."
          << " (elapsed time: " << std::fixed << std::setprecision(3)
          << time::to_seconds(timer.get_time()) << "s)" << log::end;

    out() << "uploading texture data ("
          << "dimensions: " << in_size << ", format: " << format_string(FORMAT_RGBA_8)
          << ", mip-level: " << 1
          << ", size : " << std::fixed << std::setprecision(3) << static_cast<double>(in_size * size_of_format(FORMAT_RGBA_8)) / (1024.0) << "KiB)..."
          << log::end;
    timer.start();

    texture_region ur(vec3ui(0u), vec3ui(in_size, 1, 1));
    bool res = context->update_sub_texture(_color_alpha_map, ur, 0u, FORMAT_RGBA_32F, combined_lut.get());
    timer.stop();
    out() << "uploading texture data done."
          << " (elapsed time: " << std::fixed << std::setprecision(3)
          << time::to_seconds(timer.get_time()) << "s)" << log::end;

    if (!res) {
        err() << log::error
              << "volume_data::update_color_alpha_map(): error during color map texture generation." << log::end;
        return false;
    }

    return true;
}

void
volume_data::update(const gl::render_context_ptr& context,
                    const gl::camera&             cam)
{
    using namespace scm::gl;
    using namespace scm::math;

    if (_color_alpha_map_dirty) {
        update_color_alpha_map(context);
        _color_alpha_map_dirty = false;
    }

    float max_dim = static_cast<float>(max(max(_data_dimensions.x,
                                               _data_dimensions.y),
                                               _data_dimensions.z));

    mat4f mv_matrix     = cam.view_matrix() * transform();
    mat4f mv_matrix_inv = inverse(mv_matrix);

    _volume_block.begin_manipulation(context); {
        _volume_block->_volume_extends              = vec4f(extends(), 0.0);
        _volume_block->_scale_obj_to_tex            = vec4f(1.0f) / vec4f(extends(), 1.0);
        _volume_block->_sampling_distance           = vec4f(sample_distance(), sample_distance() / sample_distance_ref(), 0.0, 0.0);
        _volume_block->_os_camera_position          = mv_matrix_inv.column(3) / mv_matrix_inv.column(3).w;
        _volume_block->_value_range                 = vec4f(min_value(), max_value(), max_value() - min_value(), 1.0f / (max_value() - min_value()));

        _volume_block->_m_matrix                     = transform();
        _volume_block->_m_matrix_inverse             = inverse(transform());
        _volume_block->_m_matrix_inverse_transpose   = transpose(_volume_block->_m_matrix_inverse);
        _volume_block->_mv_matrix                    = mv_matrix;
        _volume_block->_mv_matrix_inverse            = mv_matrix_inv;
        _volume_block->_mv_matrix_inverse_transpose  = transpose(mv_matrix_inv);
        _volume_block->_mvp_matrix                   = cam.projection_matrix() * mv_matrix;
        _volume_block->_mvp_matrix_inverse           = inverse(_volume_block->_mvp_matrix);

#if SCM_TEXT_NV_BINDLESS_TEXTURES == 1
        _volume_block->_volume_texture              = _volume_raw->native_handle();
        _volume_block->_color_map                   = _color_alpha_map->native_handle();
#endif // SCM_TEXT_NV_BINDLESS_TEXTURES == 1

    } _volume_block.end_manipulation();

}

const volume_data::volume_uniform_block&
volume_data::volume_block() const
{
    return _volume_block;
}
} // namespace data
} // namespace scm


text:
import django.db.models.deletion
from django.db import migrations, models

import wagtailmetadata.models

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('wagtailimages', '0013_make_rendition_upload_callable'),
        ('wagtailcore', '0029_unicode_slugfield_dj19'),
    ]

    operations = [
        migrations.CreateModel(
            name='TestPage',
            fields=[
                ('page_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='wagtailcore.Page')),
                ('search_image', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='wagtailimages.Image')),
            ],
            options={
                'abstract': False,
            },
            bases=('wagtailcore.page', models.Model),
        ),
        migrations.CreateModel(
            name='TestModel',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
            ],
            bases=(wagtailmetadata.models.MetadataMixin, models.Model),
        ),
    ]


text:
/*LOGIN JS*/
var users = [
  "Example.1@example.net",
  "Example.2@example.net",
  "Guest"
];
function upperCaseUserName(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}
function login() {
  var userName = document.getElementById("usrnme").value;
  userName = upperCaseUserName(userName);
  users.forEach(function(x) {
    if(userName === x) {
      window.open("HomePage.html",'_self',false);
    }
  });
}

/*HomePage JS*/
$(document).ready(function () {
  $("#sidebar").mCustomScrollbar({
    theme: "minimal"
  });

  $('#sidebarCollapse').on('click', function () {
    $('#sidebar, #content').toggleClass('active');
    $('.collapse.in').toggleClass('in');
    $('a[aria-expanded=true]').attr('aria-expanded', 'false');
  });

  $('a').on('click', function() {
    $('.selected').removeClass('selected');
    $(this).addClass('selected');
  });

  $('.aLink').on('click', function() {
    var x = $(this).attr("href");
    x = x.slice( 1 );
    $('.switch').hide(600, 'linear');
    $('div#'+x).show(600, 'linear');
  });
  var clipboard = new Clipboard('.sub');
  clipboard.on('success', function(e) {
      console.log(e);
  });
  clipboard.on('error', function(e) {
      console.log(e);
      alert("Error");
  });
});


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     Ce code a été généré par un outil.
//     Version du runtime :4.0.30319.17929
//
//     Les modifications apportées à ce fichier peuvent provoquer un comportement incorrect et seront perdues si
//     le code est régénéré.
// </auto-generated>
//------------------------------------------------------------------------------

namespace SOURCE.Services.Services.Implementations.CompteWeb {

    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
    [System.ServiceModel.ServiceContractAttribute(Namespace="http://ws.afnor.org", ConfigurationName="CompteWeb.AACompteWeb_ServiceReadSoap")]
    public interface AACompteWeb_ServiceReadSoap {

        // CODEGEN : La génération du contrat de message depuis le nom d'élément strEMAIL de l'espace de noms http://ws.afnor.org n'est pas marqué nillable
        [System.ServiceModel.OperationContractAttribute(Action="http://ws.afnor.org/AccountExist", ReplyAction="*")]
        SOURCE.Services.Services.Implementations.CompteWeb.AccountExistResponse AccountExist(SOURCE.Services.Services.Implementations.CompteWeb.AccountExistRequest request);

        // CODEGEN : La génération du contrat de message depuis le nom d'élément strEMAIL de l'espace de noms http://ws.afnor.org n'est pas marqué nillable
        [System.ServiceModel.OperationContractAttribute(Action="http://ws.afnor.org/GetData", ReplyAction="*")]
        SOURCE.Services.Services.Implementations.CompteWeb.GetDataResponse GetData(SOURCE.Services.Services.Implementations.CompteWeb.GetDataRequest request);

        // CODEGEN : La génération du contrat de message depuis le nom d'élément strEMAIL de l'espace de noms http://ws.afnor.org n'est pas marqué nillable
        [System.ServiceModel.OperationContractAttribute(Action="http://ws.afnor.org/GetDataFull", ReplyAction="*")]
        SOURCE.Services.Services.Implementations.CompteWeb.GetDataFullResponse GetDataFull(SOURCE.Services.Services.Implementations.CompteWeb.GetDataFullRequest request);
    }

    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
    [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
    [System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
    public partial class AccountExistRequest {

        [System.ServiceModel.MessageBodyMemberAttribute(Name="AccountExist", Namespace="http://ws.afnor.org", Order=0)]
        public SOURCE.Services.Services.Implementations.CompteWeb.AccountExistRequestBody Body;

        public AccountExistRequest() {
        }

        public AccountExistRequest(SOURCE.Services.Services.Implementations.CompteWeb.AccountExistRequestBody Body) {
            this.Body = Body;
        }
    }

    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
    [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
    [System.Runtime.Serialization.DataContractAttribute(Namespace="http://ws.afnor.org")]
    public partial class AccountExistRequestBody {

        [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=0)]
        public string strEMAIL;

        public AccountExistRequestBody() {
        }

        public AccountExistRequestBody(string strEMAIL) {
            this.strEMAIL = strEMAIL;
        }
    }

    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
    [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
    [System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
    public partial class AccountExistResponse {

        [System.ServiceModel.MessageBodyMemberAttribute(Name="AccountExistResponse", Namespace="http://ws.afnor.org", Order=0)]
        public SOURCE.Services.Services.Implementations.CompteWeb.AccountExistResponseBody Body;

        public AccountExistResponse() {
        }

        public AccountExistResponse(SOURCE.Services.Services.Implementations.CompteWeb.AccountExistResponseBody Body) {
            this.Body = Body;
        }
    }

    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
    [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
    [System.Runtime.Serialization.DataContractAttribute(Namespace="http://ws.afnor.org")]
    public partial class AccountExistResponseBody {

        [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=0)]
        public System.Xml.Linq.XElement AccountExistResult;

        public AccountExistResponseBody() {
        }

        public AccountExistResponseBody(System.Xml.Linq.XElement AccountExistResult) {
            this.AccountExistResult = AccountExistResult;
        }
    }

    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
    [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
    [System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
    public partial class GetDataRequest {

        [System.ServiceModel.MessageBodyMemberAttribute(Name="GetData", Namespace="http://ws.afnor.org", Order=0)]
        public SOURCE.Services.Services.Implementations.CompteWeb.GetDataRequestBody Body;

        public GetDataRequest() {
        }

        public GetDataRequest(SOURCE.Services.Services.Implementations.CompteWeb.GetDataRequestBody Body) {
            this.Body = Body;
        }
    }

    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
    [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
    [System.Runtime.Serialization.DataContractAttribute(Namespace="http://ws.afnor.org")]
    public partial class GetDataRequestBody {

        [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=0)]
        public string strEMAIL;

        public GetDataRequestBody() {
        }

        public GetDataRequestBody(string strEMAIL) {
            this.strEMAIL = strEMAIL;
        }
    }

    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
    [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
    [System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
    public partial class GetDataResponse {

        [System.ServiceModel.MessageBodyMemberAttribute(Name="GetDataResponse", Namespace="http://ws.afnor.org", Order=0)]
        public SOURCE.Services.Services.Implementations.CompteWeb.GetDataResponseBody Body;

        public GetDataResponse() {
        }

        public GetDataResponse(SOURCE.Services.Services.Implementations.CompteWeb.GetDataResponseBody Body) {
            this.Body = Body;
        }
    }

    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
    [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
    [System.Runtime.Serialization.DataContractAttribute(Namespace="http://ws.afnor.org")]
    public partial class GetDataResponseBody {

        [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=0)]
        public System.Xml.Linq.XElement GetDataResult;

        public GetDataResponseBody() {
        }

        public GetDataResponseBody(System.Xml.Linq.XElement GetDataResult) {
            this.GetDataResult = GetDataResult;
        }
    }

    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
    [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
    [System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
    public partial class GetDataFullRequest {

        [System.ServiceModel.MessageBodyMemberAttribute(Name="GetDataFull", Namespace="http://ws.afnor.org", Order=0)]
        public SOURCE.Services.Services.Implementations.CompteWeb.GetDataFullRequestBody Body;

        public GetDataFullRequest() {
        }

        public GetDataFullRequest(SOURCE.Services.Services.Implementations.CompteWeb.GetDataFullRequestBody Body) {
            this.Body = Body;
        }
    }

    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
    [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
    [System.Runtime.Serialization.DataContractAttribute(Namespace="http://ws.afnor.org")]
    public partial class GetDataFullRequestBody {

        [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=0)]
        public string strEMAIL;

        public GetDataFullRequestBody() {
        }

        public GetDataFullRequestBody(string strEMAIL) {
            this.strEMAIL = strEMAIL;
        }
    }

    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
    [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
    [System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
    public partial class GetDataFullResponse {

        [System.ServiceModel.MessageBodyMemberAttribute(Name="GetDataFullResponse", Namespace="http://ws.afnor.org", Order=0)]
        public SOURCE.Services.Services.Implementations.CompteWeb.GetDataFullResponseBody Body;

        public GetDataFullResponse() {
        }

        public GetDataFullResponse(SOURCE.Services.Services.Implementations.CompteWeb.GetDataFullResponseBody Body) {
            this.Body = Body;
        }
    }

    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
    [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
    [System.Runtime.Serialization.DataContractAttribute(Namespace="http://ws.afnor.org")]
    public partial class GetDataFullResponseBody {

        [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false, Order=0)]
        public System.Xml.Linq.XElement GetDataFullResult;

        public GetDataFullResponseBody() {
        }

        public GetDataFullResponseBody(System.Xml.Linq.XElement GetDataFullResult) {
            this.GetDataFullResult = GetDataFullResult;
        }
    }

    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
    public interface AACompteWeb_ServiceReadSoapChannel : SOURCE.Services.Services.Implementations.CompteWeb.AACompteWeb_ServiceReadSoap, System.ServiceModel.IClientChannel {
    }

    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
    public partial class AACompteWeb_ServiceReadSoapClient : System.ServiceModel.ClientBase<SOURCE.Services.Services.Implementations.CompteWeb.AACompteWeb_ServiceReadSoap>, SOURCE.Services.Services.Implementations.CompteWeb.AACompteWeb_ServiceReadSoap {

        public AACompteWeb_ServiceReadSoapClient() {
        }

        public AACompteWeb_ServiceReadSoapClient(string endpointConfigurationName) :
                base(endpointConfigurationName) {
        }

        public AACompteWeb_ServiceReadSoapClient(string endpointConfigurationName, string remoteAddress) :
                base(endpointConfigurationName, remoteAddress) {
        }

        public AACompteWeb_ServiceReadSoapClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
                base(endpointConfigurationName, remoteAddress) {
        }

        public AACompteWeb_ServiceReadSoapClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
                base(binding, remoteAddress) {
        }

        [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
        SOURCE.Services.Services.Implementations.CompteWeb.AccountExistResponse SOURCE.Services.Services.Implementations.CompteWeb.AACompteWeb_ServiceReadSoap.AccountExist(SOURCE.Services.Services.Implementations.CompteWeb.AccountExistRequest request) {
            return base.Channel.AccountExist(request);
        }

        public System.Xml.Linq.XElement AccountExist(string strEMAIL) {
            SOURCE.Services.Services.Implementations.CompteWeb.AccountExistRequest inValue = new SOURCE.Services.Services.Implementations.CompteWeb.AccountExistRequest();
            inValue.Body = new SOURCE.Services.Services.Implementations.CompteWeb.AccountExistRequestBody();
            inValue.Body.strEMAIL = strEMAIL;
            SOURCE.Services.Services.Implementations.CompteWeb.AccountExistResponse retVal = ((SOURCE.Services.Services.Implementations.CompteWeb.AACompteWeb_ServiceReadSoap)(this)).AccountExist(inValue);
            return retVal.Body.AccountExistResult;
        }

        [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
        SOURCE.Services.Services.Implementations.CompteWeb.GetDataResponse SOURCE.Services.Services.Implementations.CompteWeb.AACompteWeb_ServiceReadSoap.GetData(SOURCE.Services.Services.Implementations.CompteWeb.GetDataRequest request) {
            return base.Channel.GetData(request);
        }

        public System.Xml.Linq.XElement GetData(string strEMAIL) {
            SOURCE.Services.Services.Implementations.CompteWeb.GetDataRequest inValue = new SOURCE.Services.Services.Implementations.CompteWeb.GetDataRequest();
            inValue.Body = new SOURCE.Services.Services.Implementations.CompteWeb.GetDataRequestBody();
            inValue.Body.strEMAIL = strEMAIL;
            SOURCE.Services.Services.Implementations.CompteWeb.GetDataResponse retVal = ((SOURCE.Services.Services.Implementations.CompteWeb.AACompteWeb_ServiceReadSoap)(this)).GetData(inValue);
            return retVal.Body.GetDataResult;
        }

        [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
        SOURCE.Services.Services.Implementations.CompteWeb.GetDataFullResponse SOURCE.Services.Services.Implementations.CompteWeb.AACompteWeb_ServiceReadSoap.GetDataFull(SOURCE.Services.Services.Implementations.CompteWeb.GetDataFullRequest request) {
            return base.Channel.GetDataFull(request);
        }

        public System.Xml.Linq.XElement GetDataFull(string strEMAIL) {
            SOURCE.Services.Services.Implementations.CompteWeb.GetDataFullRequest inValue = new SOURCE.Services.Services.Implementations.CompteWeb.GetDataFullRequest();
            inValue.Body = new SOURCE.Services.Services.Implementations.CompteWeb.GetDataFullRequestBody();
            inValue.Body.strEMAIL = strEMAIL;
            SOURCE.Services.Services.Implementations.CompteWeb.GetDataFullResponse retVal = ((SOURCE.Services.Services.Implementations.CompteWeb.AACompteWeb_ServiceReadSoap)(this)).GetDataFull(inValue);
            return retVal.Body.GetDataFullResult;
        }
    }
}


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>Support Real Russia 2014, in Moscow</title>
  <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
  <link rel="stylesheet" href="stylesheets/normalize.css" type="text/css" />
  <link rel="stylesheet" href="stylesheets/style.css" type="text/css" />

Support Real Russia

        Donate now

    Donate

Help us reach our goal

          $1,000.21
          raised so far

          $14,000
          our goal

          $12,999.79
          remaining

        Donate

We have started "Real Russia" in September, 2012 as just a videoblog about our real life in Ufa, Russia in September.

In the beginning we never knew if our channel will be interesting enough for a lot of people all over the World. Nobody could give us an answer because we were the first ones who tried this concept. So we just gave it a try and since that moment never stopped.

Recently since September, 2012 we've filmed 71 episodes of "Real Russia", Sergey Baklykov got his gall bladder removed and Sergey Grom got married and his wife already bore him a son.

But another important thing is that we became more important for our audience as we ever could imagine. It's absolutely obvious we are making the right thing and you're always expect more from us and more about Russia for burning more bridges between our country and the rest of the World.

It's a fact that we've filmed a lot of good episodes in our homecity Ufa, the capital of Bashkortostan Republic of Russia, but it's time to move forward and relocate to Moscow, the heart and capital of Russia where we can meet everything and everyone - from illegal immigrants to President of Russia.

Moscow is where you can be on a pulse of Russian Life and it's the better way to start making coverage of all over Russia starting from it.

So we had two choices - to keep filming a local episodes in Ufa or to move to Moscow to start a great coverage of Russia. We've bet on a second choice!

For this reason, right now it's a historical moment when we are, Sergey Baklykov and Sergey Grom, making a serious step - we place everything on a map! We leave everything we have in Ufa and move to Moscow. Yes, we move to Moscow. Not just going to visit as we did at spring of 2013.

For this purpose we've got a loan in amount of $14,000.

We need this money to move to Moscow, find an apartment for rent there, to buy a new equpment like new camera Blackmagic that film in 2.5K format and gives absolutely great quality of the picture, lenses, steadycam and other.

All of this we do special and only for "Real Russia" and as a fact for you as for our audience.

And we'll be more than happy if you'll help us and support our channel with your donations. All money will go to return the money we loaned.

Thank you for watching and supporting us!

Everything just begins! Moscow is forward!


text:
package com.desmond.demo.box.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;
import android.widget.TextView;

import com.desmond.demo.BR;
import com.desmond.demo.R;
import com.desmond.demo.base.view.EmptyView;
import com.desmond.demo.box.model.Drug;
import com.desmond.demo.box.view.DrugItemView;
import com.desmond.demo.base.view.RecyclerViewHolder;

import java.util.List;

/**
 * Created by WIN10 on 2016/2/1.
 */
public class DrugRecyclerAdapter extends RecyclerView.Adapter<RecyclerViewHolder> {
    final int defaultType = 1;
    final int emptyType = 0;

    private List<Drug> items;
    private Context context;

    private DrugItemView.ClickListener listener;

    public DrugRecyclerAdapter(Context context, List<Drug> items, DrugItemView.ClickListener listener){
        this.items = items;
        this.context = context;
        this.listener = listener;
    }

    @Override
    public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == emptyType){
            EmptyView v = new EmptyView(context, parent);
            v.setHintText(R.mipmap.empty_pill, R.string.empty_pill);
            return new RecyclerViewHolder(v);
        }

        return new RecyclerViewHolder(new DrugItemView(context, parent));
    }

    @Override
    public void onBindViewHolder(RecyclerViewHolder holder, int position) {
        if (holder.getItemViewType() == emptyType)
            return;

        Drug drug = items.get(position);
        DrugItemView view = (DrugItemView)holder.getIView();
        view.setDrugOtc(drug.getOtc());
        view.setDrugIcon(drug.getIcon());
        view.setOnClick(drug, listener);

        holder.getBinding().setVariable(BR.drug, drug);
        holder.getBinding().executePendingBindings();
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    @Override
    public int getItemViewType(int position) {
        if (items.get(position).getId() == 0)
            return emptyType;

        return defaultType;
    }
}


text:
**Variables:** `variables/_wireframe.scss`

**Styles:** `partials/_wireframe.scss`

## Containers

You can create a generic container by adding a `.container` class to any block-level element. For example:

```html
<div class="container"></div>
```

The container is built to be responsive. We have a max-width variable -- `$container-width`. The container will hang in the middle of the window when the display is larger than the max width.

### No Container

Content does not need to live within a container, in which case the bounds become the width of the `<body>`, which is set to `100%`.

### Multiple Containers

The container was designed as though it would be the main container in your template/layout. We've made it a class so you could add more containers if you wanted to, although its not necessary, as we've provided you with a `.content` selector to use for grouping or laying out content within a container.

Therefore, this is the recommended markup:

```html
<div class="container">
  <div class="content"></div>
</div>
```

However, additional containers within the main container are possible, and would simply stretch to `100%` of their allowable width:

```html
<div class="container">
  <div class="container">
    <!-- stretches to its max allowable width -->
  </div>
</div>
```

## Grid

The grid, like all of Bones, is young, but its easy to use and is working nicely. Everything within the grid is based on one value applied to the `$grid-cols` variable:

```scss
$grid-cols: 12; // number of columns as base of building grid -- any number is permitted
```

Like the comment says, any number is permitted here. `12` is the default, but if you need more, use more! From here, we have the following basic structure:

```html
<div class="row">
  <div class="column-12"></div>
</div>
```

The concept is that the number following `column-` is the **number of columns (out of the total number of columns) you'd like this column to span**. This means, in most cases, your numbers within a `.row` will add up to the number you've chose for the `$grid-cols` variable.

In other words, the example above would be one full-width spanning row (which is usually pointless). But if you wanted a sidebar, for example, you might do something like this:

```html
<div class="row">
  <div class="column-4">
    <!-- sidebar -->
  </div>
  <div class="column-8">
    <!-- main content -->
  </div>
</div>
```

### Rows

The widths of the columns are calculated such that you don't *need* the `.row` container, but you'll likely run into some issues without it. For example, because the columns are floated, they don't hold physical height. The row container realizes the height of its columns and will help push all subsequent content to its desired position on the page.


text:
(function() {
	'use strict';
	angular.module('app')
	.factory('UserFactory', UserFactory);
	function UserFactory($http, $q) {
		var o = {};
		o.setUser = setUser;
		o.setToken = setToken;
		o.status = {};
		o.removeToken = removeToken;
		o.getToken = getToken;
		var token = '';

		o.registerUser = function(user) {
			var q = $q.defer();
			$http.post('/api/reset/register', user).then(function(res) {
				//setToken(res.data);
				//setUser();
				q.resolve(res.data);
			});
			return q.promise;
		};
		o.loginUser = function(user) {
			var q = $q.defer();
			$http.post('/api/users/login', user).then(function(res) {
				setToken(res.data);
				setUser();
				q.resolve(res.data);
			});
			return q.promise;
		};
		o.logout = function() {
			removeToken();
			removeUser();
		};
		function setUser() {
			var user = JSON.parse(urlBase64Decode(getToken().split('.')[1]));
			o.status.username = user.username;
			o.status._id = user._id;
			o.status.id = user._id;
			o.status.location = user.location;
			o.status.email = user.email;
			o.status.photo = user.photo;
			o.status.exp = user.experience;
			o.status.currency = user.currency;
			o.status.rating = user.rating;
		}
		function removeUser() {
			o.status.username = null;
			o.status._id = null;
		}
		function getToken() {
			return localStorage.getItem('token');
		}
		function setToken(token) {
			return localStorage.setItem('token', token);
		}
		function removeToken() {
			return localStorage.removeItem('token');
		}
		function urlBase64Decode(token) {
			// token = getToken();
			if(token ===  undefined){
				console.log("token is undefined");
				return;
			}
			else {
				var output = token.replace(/-/g, '+').replace(/_/g, '/');
				switch (output.length % 4) {
					case 0:
					{
						break;
					}
					case 2:
					{
						output += '==';
						break;
					}
					case 3:
					{
						output += '=';
						break;
					}
					default:
					{
						throw 'Illegal base64url string!';
					}
				}
				return decodeURIComponent(escape(window.atob(output))); //polifyll https://github.com/davidchambers/Base64.js
			}
		}
		if (getToken()) setUser();
		o.getAllByUser = function(id) {
			var q = $q.defer();
			$http.get('/api/users/dashboard/' + id).then(function(res) {
				q.resolve(res.data);
			});
			return q.promise;
		};
		o.getUserInfo = function(id) {
			var q = $q.defer();
			$http.get('/api/users/userinfo/' + id).then(function(res) {
				q.resolve(res.data);
			});
			return q.promise;
		};
		o.getAllUser = function(){
			var q = $q.defer();
			$http.get('/api/users/leaderboard').then(function(res){
				q.resolve(res.data);
			});
			return q.promise;
		};
		function getAuth() {
			var auth = {
				headers: {
					Authorization: "Bearer " +
					localStorage.getItem("token")
				}
			};
			return auth ;
		}
		o.forgot = function(user) {
			var q = $q.defer() ;
			$http.post('/api/reset/forgot', user).success(function(res) {
				q.resolve() ;
			});
			return q.promise ;
		};
		o.resetPassword = function(editedUser) {
			var q = $q.defer() ;
			$http.put('/api/reset/resetPassword/' , editedUser).success(
				function(res) {
					q.resolve(res) ;
				}) ;
				return q.promise ;
			};
			o.jobExp = function(e){
				var q = $q.defer();
				$http.put('/api/users/jobExp/' + e).then(function(res){
					q.resolve();
				});
				return q.promise;
			};
			o.jobCurrency = function(posterID, appID , currency, rating){
				var q  = $q.defer();
				$http.put('/api/users/jobCurrency/', {posterID , appID, currency, rating}).then(function(res){
					q.resolve();
				});
				return q.promise;
			};
			o.jobCurrency = function(posterID, appID , currency){
				var q  = $q.defer();
				$http.put('/api/users/jobCurrency/', {posterID , appID, currency}).then(function(res){
					q.resolve();
				});
				return q.promise;
			};
			o.sendpPic = function(pic,id){
				var q = $q.defer();
				$http.put('/api/users/' +id, pic).then(function(res){
					q.resolve(res.data);
				});
				return q.promise;
			};
			o.infoEdit = function(e, id){
				var q = $q.defer();
				$http.put('/api/users/infoedit/' + id, e).then(function(res){
					q.resolve(res.data);
				});
				return q.promise;
			};
			o.addRating = function(appID, rating, newRating) {
				var q = $q.defer();
				$http.put('/api/users/computedRating', {appID, rating, newRating}).then(function(res){
					q.resolve();
				});
				return q.promise;
			};
			o.getAllUsers = function() {
				var q = $q.defer();
				$http.get('/api/users/getall/').then(function(res) {
					q.resolve(res.data);
				});
				return q.promise;
			};

			return o;
		}
	})();


text:
class CommandLine;

namespace base {

// A MultiProcessTest is a test class which makes it easier to
// write a test which requires code running out of process.
//
// To create a multiprocess test simply follow these steps:
//
// 1) Derive your test from MultiProcessTest. Example:
//
//    class MyTest : public MultiProcessTest {
//    };
//
//    TEST_F(MyTest, TestCaseName) {
//      ...
//    }
//
// 2) Create a mainline function for the child processes and include
//    testing/multiprocess_func_list.h.
//    See the declaration of the MULTIPROCESS_TEST_MAIN macro
//    in that file for an example.
// 3) Call SpawnChild("foo"), where "foo" is the name of
//    the function you wish to run in the child processes.
// That's it!
class MultiProcessTest : public PlatformTest {
 public:
  MultiProcessTest();

 protected:
  // Run a child process.
  // 'procname' is the name of a function which the child will
  // execute.  It must be exported from this library in order to
  // run.
  //
  // Example signature:
  //    extern "C" int __declspec(dllexport) FooBar() {
  //         // do client work here
  //    }
  //
  // Returns the handle to the child, or NULL on failure
  ProcessHandle SpawnChild(const std::string& procname, bool debug_on_start);

#if defined(OS_POSIX)
  // TODO(evan): see if we can delete this via more refactoring.
  // SpawnChild() should just take a base::LaunchOptions so that we don't
  // need multiple versions of it.
  ProcessHandle SpawnChild(const std::string& procname,
                           const FileHandleMappingVector& fds_to_map,
                           bool debug_on_start);
#endif

  // Set up the command line used to spawn the child process.
  virtual CommandLine MakeCmdLine(const std::string& procname,
                                  bool debug_on_start);

 private:
  // Shared implementation of SpawnChild.
  // TODO: |fds_to_map| is unused on Windows; see above TODO about
  // further refactoring.
  ProcessHandle SpawnChildImpl(const std::string& procname,
                               const FileHandleMappingVector& fds_to_map,
                               bool debug_on_start);

  DISALLOW_COPY_AND_ASSIGN(MultiProcessTest);
};

}  // namespace base

#endif  // BASE_TEST_MULTIPROCESS_TEST_H_