text:
function visualizeSentence(xml_text) {
	clearVizArtifacts();
	clearAlertMessage();

	displayAlert('Visualizing...', 'alert-info');

	if (xml_text) {
		d3_graph = parseXmlDMRS(xml_text)

		if (d3_graph) {
			showGraphs(d3_graph);
			clearAlertMessage();
		}
	} else {
		displayAlert('Error: No XML provided.', 'alert-danger');
	}
}

function clearAlertMessage() {
	$("#alert_placeholder").html("");
}

function resetVisualizer() {
	clearVizArtifacts();
	clearAlertMessage();
	$("#dmrsinput").val("");
}

function parseXmlDMRS(xml_text) {
	// Remove line breaks
	xml_text = xml_text.replace(/(\r\n|\n|\r)/gm,"");

	// Parse XML
	try {
		xmlDoc = $.parseXML(xml_text);
	}
	catch(err) {
		displayAlert('Error parsing XML. ', 'alert-danger');
		return null
	}

	xml = $(xmlDoc);

	// Parse nodes into objects
	nodes = xml.find('node');
	d3_nodes = [];

	node_map = {};

	for (i = 0; i < nodes.length; i++) {
		node = nodes[i];

		node_map[node.getAttribute('nodeid')] = i;

		sortinfo = node.getElementsByTagName('sortinfo')[0];

		d3_node = {
			id: node.getAttribute('nodeid'),
			pred: parseNodePred(node),
			cfrom: node.getAttribute('cfrom'),
			cto: node.getAttribute('cto'),
			cvarsort: sortinfo.getAttribute('cvarsort'),
			carg: node.getAttribute('carg'),
			varprops: parseNodeProperties(node)
		};

		d3_nodes.push(d3_node);
	}

	// Parse links into objects
	links = xml.find('link');
	d3_links = [];
	for (i = 0; i < links.length; i++) {
		link = links[i];
		rargname = link.getElementsByTagName('rargname')[0];
		post = link.getElementsByTagName('post')[0];

		d3_link = {
			source: node_map[link.getAttribute('from')],
			target: node_map[link.getAttribute('to')],
			start: link.getAttribute('from'),
			end: link.getAttribute('to'),
			rargname: rargname.textContent,
			post: post.textContent
		};

		d3_links.push(d3_link);
	}

	d3_graph = {
		nodes: d3_nodes,
		links: d3_links
	};

	return d3_graph;
}

function parseNodePred(node) {
	realpred = node.getElementsByTagName('realpred');

	if (realpred.length > 0) {
		pred_elements = [
			'',
			realpred[0].getAttribute('lemma'),
			realpred[0].getAttribute('pos'),
			realpred[0].getAttribute('sense')
		];
		pred = pred_elements.filter(function(val) { return val !== null;}).join('_')
	}
	else {
		gpred = node.getElementsByTagName('gpred')[0].textContent;
		pred = gpred.replace('_rel', '')
	}

	return pred;
}

function parseNodeProperties(node) {

	sortinfo = node.getElementsByTagName('sortinfo')[0];

	property_names = ['ind', 'pers', 'num', 'gend', 'sf', 'mood', 'tense', 'prog', 'perf', 'pt'];
	properties = {};

	for (j = 0; j < property_names.length; j++) {
		property_name = property_names[j];
		if (sortinfo.getAttribute(property_name) != null) {
			properties[property_name.toUpperCase()] = sortinfo.getAttribute(property_name);
		};
	}

	return properties;
}

function displayAlert(errorMessage, type) {
	bootstrap_alert = function() {}
	bootstrap_alert.warning = function(message) {
            $('#alert_placeholder').html('
'+message+'
')
        }

	bootstrap_alert.warning(errorMessage);
}

function showGraphs(graph) {

	var svg = d3.select("#visualizations")
		.selectAll('.result')
		.data([graph])
		.enter()
		.append("svg")
		.attr("id", "dmrs")
		.attr("width", "100%")
		.attr("height", "100%")
		.attr("cursor", "grab")
		.call(d3.behavior.zoom().on("zoom", function () {
        svg.attr("transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")")
		}))
		.append("g")

	svg.attr("id", function(d, i) { return "dmrs" + i; })
		.each(function(d, i) { dmrsDisplay(this, d); });
}


text:
namespace NorthwindWindowsStore.ViewModel
{

    using System.Collections.Generic;

    public partial class CategoryViewModel
    {
        public CategoryViewModel()
        {
            Products = new HashSet<ProductViewModel>();
        }
        public int CategoryID { get; set; }
        public string CategoryName { get; set; }
        public string Description { get; set; }
        public byte[] Picture { get; set; }
        public virtual ICollection<ProductViewModel> Products { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

const Ana = require('./ana_log');

/**
 * Service for just logging theoretical communication with catalog servers.
 */
class DebugCatalog {

  /**
   * Logs response data and attributes to the console.
   * @param {Object} data the response data to send back.
   * @param {Object} attributes original request attributes to send with response.
   * @return {Promise} a promise for determining success.
   */
  postResponse(data, attributes) {
    return new Promise((resolve, reject) => {
      Ana.log("catalog/postResponse");
      Ana.log("catalog/postResponse/debug attributes ", JSON.stringify(attributes));
      Ana.log("catalog/postResponse/debug data ", JSON.stringify(data, null, '\t'));
      resolve();
      return;
    });
  }
}

module.exports = DebugCatalog;


text:
/* vim:set ts=3 sw=3 sts=3 et: */
/**
 * Copyright © 2008-2013 Last.fm Limited
 *
 * This file is part of libmoost.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, sublicense, and/or sell copies of the Software,
 * and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

#ifndef MOOST_ALGORITHM_INPLACE_SET_INTERSECTION_HPP__
#define MOOST_ALGORITHM_INPLACE_SET_INTERSECTION_HPP__

namespace moost { namespace algorithm {

// just like stl set_intersection, these two algorithms have the precondition
// that their input ranges are sorted
// i've looked through gcc's include and it seems like we shouldn't need our own in-place version,
// and that this would be safe:
// std::set_intersection(foo.begin(), foo.end(), bar.begin(), bar.end(), foo.begin());
// however, the preconditions of set_intersection (http://www.sgi.com/tech/stl/set_intersection.html)
// explicitly state that the output range and input ranges should not overlap
// so just to be safe, we'll write our own
template <class ForwardIterator, class InputIterator>
ForwardIterator inplace_set_intersection(ForwardIterator first1, ForwardIterator last1,
                                         InputIterator first2, InputIterator last2)
{
  ForwardIterator result = first1;
  while (   first1 != last1
         && first2 != last2)
  {
    if (*first1 < *first2)
      ++first1;
    else if (*first2 < *first1)
      ++first2;
    else
    {
      *result = *first1;
      ++first1;
      ++first2;
      ++result;
    }
  }
  return result;
}

template <class ForwardIterator, class InputIterator, class StrictWeakOrdering>
ForwardIterator inplace_set_intersection(ForwardIterator first1, ForwardIterator last1,
                                         InputIterator first2, InputIterator last2,
                                         StrictWeakOrdering comp)
{
  ForwardIterator result = first1;
  while (   first1 != last1
         && first2 != last2)
  {
    if (comp(*first1, *first2))
      ++first1;
    else if (comp(*first2, *first1))
      ++first2;
    else
    {
      *result = *first1;
      ++first1;
      ++first2;
      ++result;
    }
  }
  return result;
}

}} // moost::algorithm

#endif // MOOST_ALGORITHM_INPLACE_SET_INTERSECTION_HPP__


text:
{-# OPTIONS_GHC -Wno-name-shadowing #-}

-------------------------------------------------------------------------------
-- | This module defines a function to solve NNF constraints,
--   by reducing them to the standard FInfo.
-------------------------------------------------------------------------------

module Language.Fixpoint.Horn.Solve (solveHorn, solve) where

import System.Exit ( ExitCode )
import Control.DeepSeq ( NFData )
import Control.Monad (when)
import qualified Language.Fixpoint.Misc         as Misc
import qualified Language.Fixpoint.Utils.Files  as Files
import qualified Language.Fixpoint.Solver       as Solver
import qualified Language.Fixpoint.Parse        as Parse
import qualified Language.Fixpoint.Types        as F
import qualified Language.Fixpoint.Types.Config as F
import qualified Language.Fixpoint.Horn.Types   as H
import qualified Language.Fixpoint.Horn.Parse   as H
import qualified Language.Fixpoint.Horn.Transformations as Tx
import Text.PrettyPrint.HughesPJ.Compat ( render )
import Language.Fixpoint.Horn.Info ( hornFInfo )

import System.Console.CmdArgs.Verbosity ( whenLoud )

-- import Debug.Trace (traceM)

----------------------------------------------------------------------------------
solveHorn :: F.Config -> IO ExitCode
----------------------------------------------------------------------------------
solveHorn cfg = do
  (q, opts) <- parseQuery cfg

  -- If you want to set --eliminate=none, you better make it a pragma
  cfg <- if F.eliminate cfg == F.None
           then pure (cfg { F.eliminate =  F.Some })
           else pure cfg

  cfg <- F.withPragmas cfg opts

  when (F.save cfg) (saveHornQuery cfg q)

  r <- solve cfg q
  Solver.resultExitCode cfg r

parseQuery :: F.Config -> IO (H.Query H.Tag, [String])
parseQuery cfg
  | F.stdin cfg = Parse.parseFromStdIn H.hornP
  | otherwise   = Parse.parseFromFile H.hornP (F.srcFile cfg)

saveHornQuery :: F.Config -> H.Query H.Tag -> IO ()
saveHornQuery cfg q = do
  let hq   = F.queryFile Files.HSmt2 cfg
  putStrLn $ "Saving Horn Query: " ++ hq ++ "\n"
  Misc.ensurePath hq
  writeFile hq $ render (F.pprint q)

----------------------------------------------------------------------------------
eliminate :: (F.PPrint a) => F.Config -> H.Query a -> IO (H.Query a)
----------------------------------------------------------------------------------
eliminate cfg q
  | F.eliminate cfg == F.Existentials = do
    Tx.solveEbs cfg q
  | F.eliminate cfg == F.Horn = do
    let c = Tx.elim $ H.qCstr q
    whenLoud $ putStrLn "Horn Elim:"
    whenLoud $ putStrLn $ F.showpp c
    pure $ q { H.qCstr = c }
  | otherwise = pure q

----------------------------------------------------------------------------------
solve :: (F.PPrint a, NFData a, F.Loc a, Show a, F.Fixpoint a) => F.Config -> H.Query a
       -> IO (F.Result (Integer, a))
----------------------------------------------------------------------------------
solve cfg q = do
  let c = Tx.uniq $ Tx.flatten $ H.qCstr q
  whenLoud $ putStrLn "Horn Uniq:"
  whenLoud $ putStrLn $ F.showpp c
  q <- eliminate cfg ({- void $ -} q { H.qCstr = c })
  Solver.solve cfg (hornFInfo cfg q)


text:
namespace lldb {

class LLDB_API SBInputReader {
public:
  SBInputReader() = default;
  ~SBInputReader() = default;

  SBError Initialize(lldb::SBDebugger &,
                     unsigned long (*)(void *, lldb::SBInputReader *,
                                       lldb::InputReaderAction, char const *,
                                       unsigned long),
                     void *, lldb::InputReaderGranularity, char const *,
                     char const *, bool);
  void SetIsDone(bool);
  bool IsActive() const;
};

class LLDB_API SBDebugger {
public:
  SBDebugger();

  SBDebugger(const lldb::SBDebugger &rhs);

  SBDebugger(const lldb::DebuggerSP &debugger_sp);

  ~SBDebugger();

  lldb::SBDebugger &operator=(const lldb::SBDebugger &rhs);

  static void Initialize();

  static void Terminate();

  // Deprecated, use the one that takes a source_init_files bool.
  static lldb::SBDebugger Create();

  static lldb::SBDebugger Create(bool source_init_files);

  static lldb::SBDebugger Create(bool source_init_files,
                                 lldb::LogOutputCallback log_callback,
                                 void *baton);

  static void Destroy(lldb::SBDebugger &debugger);

  static void MemoryPressureDetected();

  bool IsValid() const;

  void Clear();

  void SetAsync(bool b);

  bool GetAsync();

  void SkipLLDBInitFiles(bool b);

  void SkipAppInitFiles(bool b);

  void SetInputFileHandle(FILE *f, bool transfer_ownership);

  void SetOutputFileHandle(FILE *f, bool transfer_ownership);

  void SetErrorFileHandle(FILE *f, bool transfer_ownership);

  FILE *GetInputFileHandle();

  FILE *GetOutputFileHandle();

  FILE *GetErrorFileHandle();

  void SaveInputTerminalState();

  void RestoreInputTerminalState();

  lldb::SBCommandInterpreter GetCommandInterpreter();

  void HandleCommand(const char *command);

  lldb::SBListener GetListener();

  void HandleProcessEvent(const lldb::SBProcess &process,
                          const lldb::SBEvent &event, FILE *out, FILE *err);

  lldb::SBTarget CreateTarget(const char *filename, const char *target_triple,
                              const char *platform_name,
                              bool add_dependent_modules, lldb::SBError &error);

  lldb::SBTarget CreateTargetWithFileAndTargetTriple(const char *filename,
                                                     const char *target_triple);

  lldb::SBTarget CreateTargetWithFileAndArch(const char *filename,
                                             const char *archname);

  lldb::SBTarget CreateTarget(const char *filename);

  lldb::SBTarget GetDummyTarget();

  // Return true if target is deleted from the target list of the debugger.
  bool DeleteTarget(lldb::SBTarget &target);

  lldb::SBTarget GetTargetAtIndex(uint32_t idx);

  uint32_t GetIndexOfTarget(lldb::SBTarget target);

  lldb::SBTarget FindTargetWithProcessID(pid_t pid);

  lldb::SBTarget FindTargetWithFileAndArch(const char *filename,
                                           const char *arch);

  uint32_t GetNumTargets();

  lldb::SBTarget GetSelectedTarget();

  void SetSelectedTarget(SBTarget &target);

  lldb::SBPlatform GetSelectedPlatform();

  void SetSelectedPlatform(lldb::SBPlatform &platform);

  /// Get the number of currently active platforms.
  uint32_t GetNumPlatforms();

  /// Get one of the currently active platforms.
  lldb::SBPlatform GetPlatformAtIndex(uint32_t idx);

  /// Get the number of available platforms.
  ///
  /// The return value should match the number of entries output by the
  /// "platform list" command.
  uint32_t GetNumAvailablePlatforms();

  /// Get the name and description of one of the available platforms.
  ///
  /// @param[in] idx
  ///     Zero-based index of the platform for which info should be retrieved,
  ///     must be less than the value returned by GetNumAvailablePlatforms().
  lldb::SBStructuredData GetAvailablePlatformInfoAtIndex(uint32_t idx);

  lldb::SBSourceManager GetSourceManager();

  // REMOVE: just for a quick fix, need to expose platforms through
  // SBPlatform from this class.
  lldb::SBError SetCurrentPlatform(const char *platform_name);

  bool SetCurrentPlatformSDKRoot(const char *sysroot);

  // FIXME: Once we get the set show stuff in place, the driver won't need
  // an interface to the Set/Get UseExternalEditor.
  bool SetUseExternalEditor(bool input);

  bool GetUseExternalEditor();

  bool SetUseColor(bool use_color);

  bool GetUseColor() const;

  static bool GetDefaultArchitecture(char *arch_name, size_t arch_name_len);

  static bool SetDefaultArchitecture(const char *arch_name);

  lldb::ScriptLanguage GetScriptingLanguage(const char *script_language_name);

  static const char *GetVersionString();

  static const char *StateAsCString(lldb::StateType state);

  static SBStructuredData GetBuildConfiguration();

  static bool StateIsRunningState(lldb::StateType state);

  static bool StateIsStoppedState(lldb::StateType state);

  bool EnableLog(const char *channel, const char **categories);

  void SetLoggingCallback(lldb::LogOutputCallback log_callback, void *baton);

  // DEPRECATED
  void DispatchInput(void *baton, const void *data, size_t data_len);

  void DispatchInput(const void *data, size_t data_len);

  void DispatchInputInterrupt();

  void DispatchInputEndOfFile();

  void PushInputReader(lldb::SBInputReader &reader);

  const char *GetInstanceName();

  static SBDebugger FindDebuggerWithID(int id);

  static lldb::SBError SetInternalVariable(const char *var_name,
                                           const char *value,
                                           const char *debugger_instance_name);

  static lldb::SBStringList
  GetInternalVariableValue(const char *var_name,
                           const char *debugger_instance_name);

  bool GetDescription(lldb::SBStream &description);

  uint32_t GetTerminalWidth() const;

  void SetTerminalWidth(uint32_t term_width);

  lldb::user_id_t GetID();

  const char *GetPrompt() const;

  void SetPrompt(const char *prompt);

  lldb::ScriptLanguage GetScriptLanguage() const;

  void SetScriptLanguage(lldb::ScriptLanguage script_lang);

  bool GetCloseInputOnEOF() const;

  void SetCloseInputOnEOF(bool b);

  SBTypeCategory GetCategory(const char *category_name);

  SBTypeCategory GetCategory(lldb::LanguageType lang_type);

  SBTypeCategory CreateCategory(const char *category_name);

  bool DeleteCategory(const char *category_name);

  uint32_t GetNumCategories();

  SBTypeCategory GetCategoryAtIndex(uint32_t);

  SBTypeCategory GetDefaultCategory();

  SBTypeFormat GetFormatForType(SBTypeNameSpecifier);

#ifndef LLDB_DISABLE_PYTHON
  SBTypeSummary GetSummaryForType(SBTypeNameSpecifier);
#endif

  SBTypeFilter GetFilterForType(SBTypeNameSpecifier);

#ifndef LLDB_DISABLE_PYTHON
  SBTypeSynthetic GetSyntheticForType(SBTypeNameSpecifier);
#endif

  void RunCommandInterpreter(bool auto_handle_events, bool spawn_thread);

  void RunCommandInterpreter(bool auto_handle_events, bool spawn_thread,
                             SBCommandInterpreterRunOptions &options,
                             int &num_errors, bool &quit_requested,
                             bool &stopped_for_crash);

  SBError RunREPL(lldb::LanguageType language, const char *repl_options);

private:
  friend class SBCommandInterpreter;
  friend class SBInputReader;
  friend class SBListener;
  friend class SBProcess;
  friend class SBSourceManager;
  friend class SBTarget;

  lldb::SBTarget FindTargetWithLLDBProcess(const lldb::ProcessSP &processSP);

  void reset(const lldb::DebuggerSP &debugger_sp);

  lldb_private::Debugger *get() const;

  lldb_private::Debugger &ref() const;

  const lldb::DebuggerSP &get_sp() const;

  lldb::DebuggerSP m_opaque_sp;

}; // class SBDebugger

} // namespace lldb

#endif // LLDB_SBDebugger_h_


text:
use std::os;
use std::collections::{HashSet, HashMap};
use std::env;
use std::fs;
use std::fs::File;
use std::io::{self, BufRead, BufReader, Write};
use std::iter::FromIterator;
use std::path::Path;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use cargo::ops;
use cargo::core::Workspace;
use cargo::util::errors::CargoError;
use cargo::util::process_builder::process;

use config::AndroidConfig;
use Options;

pub struct BuildResult {
    /// The absolute path where the apk is located.
    pub apk_path: PathBuf,
}

pub fn build(workspace: &Workspace, config: &AndroidConfig, options: &Options)
            -> Result<BuildResult, CargoError>
{
    // First we detect whether `gradle` works.
    match Command::new(&config.gradle_command).arg("-v").stdout(Stdio::null()).status() {
        Ok(s) if s.success() => (),
        _ => {
            return Err(CargoError::from(r#"Could not execute `gradle`. Did you
                install it? (If already installed on windows with `gradle.bat`
                in your path, you must customise the gradle command to
                `gradle.bat` with the CARGO_APK_GRADLE_COMMAND environment
                variable)."#));
        }
    }

    // Building the `android-artifacts` directory that will contain all the artifacts.
    // FIXME: don't use into_path_unlocked() but pass a Cargo::Filesystem everywhere
    let android_artifacts_dir = workspace.target_dir().join("android-artifacts").into_path_unlocked();
    build_android_artifacts_dir(workspace, &android_artifacts_dir, &config)?;

    let mut abi_libs: HashMap<&str, Vec<String>> = HashMap::new();

    for build_target in config.build_targets.iter() {
        assert_ne!(build_target, "app");
        let build_target_dir = android_artifacts_dir.join(build_target);

        // Finding the tools in the NDK.
        let (gcc_path, gxx_path, ar_path) = {
            let host_os = if cfg!(target_os = "windows") { "windows" }
                       else if cfg!(target_os = "linux") { "linux" }
                       else if cfg!(target_os = "macos") { "darwin" }
                       else { panic!("Unknown or incompatible host OS") };

            let target_arch = if build_target.starts_with("arm") { "arm-linux-androideabi" }
                       else if build_target.starts_with("aarch64") { "aarch64-linux-android" }
                       else if build_target.starts_with("i") { "x86" }
                       else if build_target.starts_with("x86_64") { "x86_64" }
                       else if build_target.starts_with("mipsel") { "mipsel-linux-android" }
                       // TODO: mips64
                       else { panic!("Unknown or incompatible build target: {}", build_target) };

            // Looks like the tools don't always share the prefix of the target arch
            // Just a macos issue?
            let tool_prefix = if build_target.starts_with("arm") { "arm-linux-androideabi" }
                       else if build_target.starts_with("aarch64") { "aarch64-linux-android" }
                       else if build_target.starts_with("i") { "i686-linux-android" }
                       else if build_target.starts_with("x86_64") { "x86_64-linux-android" }
                       else if build_target.starts_with("mipsel") { "mipsel-linux-android" }
                       // TODO: mips64
                       else { panic!("Unknown or incompatible build target: {}", build_target) };

            let base = config.ndk_path.join(format!("toolchains/{}-4.9/prebuilt/{}-x86_64", target_arch, host_os));
            (base.join(format!("bin/{}-gcc", tool_prefix)),
             base.join(format!("bin/{}-g++", tool_prefix)),
             base.join(format!("bin/{}-ar", tool_prefix)))
        };

        let gcc_sysroot = {
            let arch = if build_target.starts_with("arm") { "arm" }
                       else if build_target.starts_with("aarch64") { "arm64" }
                       else if build_target.starts_with("i") { "x86" }
                       else if build_target.starts_with("x86_64") { "x86_64" }
                       else if build_target.starts_with("mips") { "mips" }
                       // TODO: mips64
                       else { panic!("Unknown or incompatible build target: {}", build_target) };
            config.ndk_path.join(format!("platforms/android-{v}/arch-{a}",
                                         v = config.android_version, a = arch))
        };

        // Create android cpu abi name
        let abi = if build_target.starts_with("arm") { "armeabi" }
                  // TODO: armeabi-v7a
                  else if build_target.starts_with("aarch64") { "arm64-v8a" }
                  else if build_target.starts_with("i") { "x86" }
                  else if build_target.starts_with("x86_64") { "x86_64" }
                  else if build_target.starts_with("mips") { "mips" }
                  // TODO: mips64
                  else { panic!("Unknown or incompatible build target: {}", build_target) };

        // Compiling android_native_app_glue.c
        {
            workspace.config().shell().say("Compiling android_native_app_glue.c", 10)?;
            let mut cmd = process(&gcc_path);
            cmd.arg(config.ndk_path.join("sources/android/native_app_glue/android_native_app_glue.c"))
               .arg("-c");
            if config.release {
                cmd.arg("-O3");
            }
            cmd.arg("-o").arg(build_target_dir.join("android_native_app_glue.o"))
               .arg("--sysroot").arg(&gcc_sysroot)
               .exec()?;
        }

        // Compiling injected-glue
        let injected_glue_lib = {
            workspace.config().shell().say("Compiling injected-glue", 10)?;
            let mut cmd = workspace.config().rustc()?.process();
            cmd.arg(android_artifacts_dir.join("injected-glue/lib.rs"))
               .arg("--crate-type").arg("rlib");
            if config.release {
                cmd.arg("-C")
                   .arg("opt-level=3");
            }
            cmd.arg("--crate-name").arg("cargo_apk_injected_glue")
               .arg("--target").arg(build_target)
               .arg("--out-dir").arg(&build_target_dir);

            cmd.exec()?;

            let stdout = cmd.arg("--print").arg("file-names")
                            .exec_with_output()?;
            let stdout = String::from_utf8(stdout.stdout).unwrap();

            build_target_dir.join(stdout.lines().next().unwrap())
        };

        // Compiling glue_obj.rs
        {
            let mut file = File::create(build_target_dir.join("glue_obj.rs")).unwrap();
            file.write_all(&include_bytes!("../../glue_obj.rs")[..]).unwrap();
        }

        {
            workspace.config().shell().say("Compiling glue_obj", 10)?;
            let mut cmd = workspace.config().rustc()?.process();
            cmd.arg(build_target_dir.join("glue_obj.rs"))
               .arg("--crate-type").arg("staticlib");
            if config.release {
                cmd.arg("-C")
                   .arg("opt-level=3");
            }
            cmd.arg("--target").arg(build_target)
               .arg("--extern").arg(format!("cargo_apk_injected_glue={}", injected_glue_lib.to_string_lossy()))
               .arg("--emit").arg("obj")
               .arg("-o").arg(build_target_dir.join("glue_obj.o"))
               .exec()?;
        }

        // Directory where we will put the native libraries for gradle to pick them up.
        let native_libraries_dir = android_artifacts_dir.join(format!("app/lib/{}", abi));

        if fs::metadata(&native_libraries_dir).is_err() {
            fs::DirBuilder::new().recursive(true).create(&native_libraries_dir).unwrap();
        }

        // Compiling the crate thanks to `cargo rustc`. We set the linker to `linker_exe`, a hacky
        // linker that will tweak the options passed to `gcc`.
        {
            workspace.config().shell().say("Compiling crate", 10)?;

            // Set the current environment variables so that they are picked up by gcc-rs when
            // compiling.
            env::set_var(&format!("CC_{}", build_target), gcc_path.as_os_str());
            env::set_var(&format!("CXX_{}", build_target), gxx_path.as_os_str());
            env::set_var(&format!("AR_{}", build_target), ar_path.as_os_str());
            env::set_var(&format!("CFLAGS_{}", build_target), &format!("--sysroot {}", gcc_sysroot.to_string_lossy()));
            env::set_var(&format!("CXXFLAGS_{}", build_target), &format!("--sysroot {}", gcc_sysroot.to_string_lossy()));

            let extra_args = vec![
                "-C".to_owned(), format!("linker={}", android_artifacts_dir.join(if cfg!(target_os = "windows") { "linker_exe.exe" } else { "linker_exe" }).to_string_lossy()),
                "--extern".to_owned(), format!("cargo_apk_injected_glue={}", injected_glue_lib.to_string_lossy()),
                "-C".to_owned(),"link-arg=--cargo-apk-gcc".to_owned(),
                "-C".to_owned(), format!("link-arg={}", gcc_path.as_os_str().to_str().unwrap().to_owned()),
                "-C".to_owned(),"link-arg=--cargo-apk-gcc-sysroot".to_owned(),
                "-C".to_owned(), format!("link-arg={}", gcc_sysroot.as_os_str().to_str().unwrap().to_owned()),
                "-C".to_owned(), "link-arg=--cargo-apk-native-app-glue".to_owned(),
                "-C".to_owned(), format!("link-arg={}", build_target_dir.join("android_native_app_glue.o").into_os_string().into_string().unwrap()),
                "-C".to_owned(), "link-arg=--cargo-apk-glue-obj".to_owned(),
                "-C".to_owned(), format!("link-arg={}", build_target_dir.join("glue_obj.o").into_os_string().into_string().unwrap()),
                "-C".to_owned(), "link-arg=--cargo-apk-glue-lib".to_owned(),
                "-C".to_owned(), format!("link-arg={}", injected_glue_lib.into_os_string().into_string().unwrap()),
                "-C".to_owned(), "link-arg=--cargo-apk-linker-output".to_owned(),
                "-C".to_owned(), format!("link-arg={}", native_libraries_dir.join("libmain.so").into_os_string().into_string().unwrap()),
                "-C".to_owned(), "link-arg=--cargo-apk-libs-path-output".to_owned(),
                "-C".to_owned(), format!("link-arg={}", build_target_dir.join("lib_paths").into_os_string().into_string().unwrap()),
                "-C".to_owned(), "link-arg=--cargo-apk-libs-output".to_owned(),
                "-C".to_owned(), format!("link-arg={}", build_target_dir.join("libs").into_os_string().into_string().unwrap()),
            ];

            let packages = Vec::from_iter(options.flag_package.iter().cloned());
            let spec = ops::Packages::Packages(&packages);

            let (mut examples, mut bins) = (Vec::new(), Vec::new());
            if let Some(ref s) = options.flag_bin {
                bins.push(s.clone());
            }
            if let Some(ref s) = options.flag_example {
                examples.push(s.clone());
            }
            if !bins.is_empty() && !examples.is_empty() {
                return Err(CargoError::from("You can only specify either a --bin or an --example but not both"));
            }

            let pkg = match spec {
                ops::Packages::All => unreachable!("cargo apk supports single package only"),
                ops::Packages::OptOut(_) => unreachable!("cargo apk supports single package only"),
                ops::Packages::Packages(xs) => match xs.len() {
                    0 => workspace.current()?,
                    1 => workspace.members()
                        .find(|pkg| pkg.name() == xs[0])
                        .ok_or_else(||
                            CargoError::from(
                                format!("package `{}` is not a member of the workspace", xs[0]))
                        )?,
                    _ => unreachable!("cargo apk supports single package only"),
                }
            };

            if bins.is_empty() && examples.is_empty() {
                bins = pkg.manifest().targets().iter().filter(|a| {
                    !a.is_lib() && !a.is_custom_build() && a.is_bin()
                }).map(|a| a.name().to_owned()).collect();
                if bins.len() >= 2 {
                    return Err(CargoError::from("`cargo apk` can run at most one executable, but \
                        multiple exist"));
                } else if bins.is_empty() {
                    return Err(CargoError::from("a bin target must be available for `cargo apk`"));
                }
            }

            let opts = ops::CompileOptions {
                config: workspace.config(),
                jobs: options.flag_jobs,
                target: Some(build_target),
                features: &options.flag_features,
                all_features: options.flag_all_features,
                no_default_features: options.flag_no_default_features,
                spec: spec,
                mode: ops::CompileMode::Build,
                release: options.flag_release,
                filter: ops::CompileFilter::new(false,
                                            &bins, false,
                                            &[], false,
                                            &examples, false,
                                            &[], false),
                message_format: options.flag_message_format,
                target_rustdoc_args: None,
                target_rustc_args: Some(&extra_args),
            };

            ops::compile(workspace, &opts)?;
        }

        // Determine the list of library paths and libraries, and copy them to the right location.
        let shared_objects_to_load = {
            let lib_paths: Vec<String> = {
                if let Ok(f) = File::open(build_target_dir.join("lib_paths")) {
                    let l = BufReader::new(f);
                    l.lines().map(|l| l.unwrap()).collect()
                } else {
                    vec![]
                }
            };

            let libs_list: HashSet<String> = {
                if let Ok(f) = File::open(build_target_dir.join("libs")) {
                    let l = BufReader::new(f);
                    l.lines().map(|l| l.unwrap()).collect()
                } else {
                    HashSet::new()
                }
            };

            let mut shared_objects_to_load = Vec::new();

            for dir in lib_paths.iter() {
                fs::read_dir(&dir).and_then(|paths| {
                    for path in paths {
                        let path = path.unwrap().path();
                        match (path.file_name(), path.extension()) {
                            (Some(filename), Some(ext)) => {
                                let filename = filename.to_str().unwrap();
                                if filename.starts_with("lib") && ext == "so" &&
                                   libs_list.contains(filename)
                                {
                                    shared_objects_to_load.push(filename.to_owned());
                                    fs::copy(&path, native_libraries_dir.join(filename)).unwrap();
                                }
                            }
                            _ => {}
                        }
                    }

                    Ok(())
                }).ok();
            }

            shared_objects_to_load
        };

        abi_libs.insert(abi, shared_objects_to_load);
    }

    // Write the Java source
    build_java_src(workspace, &android_artifacts_dir, &config, &abi_libs)?;

    // Invoking `gradle` from within `android-artifacts` in order to compile the project.
    workspace.config().shell().say("Invoking gradle", 10)?;
    let mut cmd = process(&config.gradle_command);
    if config.release {
        cmd.arg("assembleRelease");
    } else {
        cmd.arg("assembleDebug");
    }
    cmd.cwd(&android_artifacts_dir)
       .exec()?;

    Ok(BuildResult {
        apk_path: {
            let apk_name = if options.flag_release {
                "app/build/outputs/apk/app-release-unsigned.apk"
            } else {
                "app/build/outputs/apk/app-debug.apk"
            };

            android_artifacts_dir.join(apk_name)
        },
    })
}

fn build_android_artifacts_dir(workspace: &Workspace, path: &Path, config: &AndroidConfig) -> Result<(), CargoError> {
    fs::create_dir_all(path.join("app").join("src").join("main")).unwrap();

    {
        fs::create_dir_all(path.join("injected-glue")).unwrap();

        let mut lib = File::create(path.join("injected-glue/lib.rs")).unwrap();
        lib.write_all(&include_bytes!("../../injected-glue/lib.rs")[..]).unwrap();

        let mut ffi = File::create(path.join("injected-glue/ffi.rs")).unwrap();
        ffi.write_all(&include_bytes!("../../injected-glue/ffi.rs")[..]).unwrap();
    }

    build_linker(workspace, path)?;
    build_manifest(workspace, path, config)?;
    build_build_gradle_root(workspace, path, config)?;
    build_build_gradle_proj(workspace, path, config)?;
    build_settings_dot_gradle(workspace, path, config)?;
    build_gradle_properties(workspace, path, config)?;
    build_local_properties(workspace, path, config)?;
    build_assets(workspace, path, config)?;
    build_res(workspace, path, config)?;

    for target in config.build_targets.iter() {
        if fs::metadata(path.join(target)).is_err() {
            fs::DirBuilder::new().recursive(true).create(path.join(target)).unwrap();
        }
    }

    Ok(())
}

fn build_linker(workspace: &Workspace, path: &Path) -> Result<(), CargoError> {
    let exe_file = path.join(if cfg!(target_os = "windows") { "linker_exe.exe" } else { "linker_exe" });

    /*if fs::metadata(&exe_file).is_ok() {
        return;
    }*/

    let mut command = workspace.config().rustc()?.process().arg("-").arg("-o").arg(&exe_file).build_command();

    let mut child = command.stdin(Stdio::piped())
        .spawn()?;
    child.stdin.take().unwrap().write_all(&include_bytes!("../../linker.rs")[..])?;

    let status = child.wait()?;
    assert!(status.success());

    assert!(fs::metadata(&exe_file).is_ok());

    Ok(())
}

fn build_java_src(_: &Workspace, path: &Path, config: &AndroidConfig, abi_libs: &HashMap<&str, Vec<String>>) -> Result<(), CargoError>
{
    let file = path.join("app/src/main/java/rust").join(config.project_name.replace("-", "_"))
                   .join("MainActivity.java");
    fs::create_dir_all(file.parent().unwrap())?;
    //if fs::metadata(&file).is_ok() { return; }
    let mut file = File::create(&file)?;

    let mut libs_string = String::new();

    for (abi, libs) in abi_libs {

        libs_string.push_str(format!("            if (abi.equals(\"{}\")) {{\n",abi).as_str());
        libs_string.push_str(format!("                matched_an_abi = true;\n").as_str());

        for name in libs {
            // Strip off the 'lib' prefix and ".so" suffix.
            let line = format!("                System.loadLibrary(\"{}\");\n",
                name.trim_left_matches("lib").trim_right_matches(".so"));
            libs_string.push_str(&*line);
        }

        libs_string.push_str(format!("                break;\n").as_str());
        libs_string.push_str(format!("            }}\n").as_str());
    }

    write!(file, r#"package rust.{package_name};

import java.lang.UnsupportedOperationException;
import android.os.Build;
import android.util.Log;

public class MainActivity extends android.app.NativeActivity {{

    static {{

        String[] supported_abis;

        try {{
            supported_abis = (String[]) Build.class.getField("SUPPORTED_ABIS").get(null);
        }} catch (Exception e) {{
            // Assume that this is an older phone; use backwards-compatible targets.
            supported_abis = new String[]{{Build.CPU_ABI, Build.CPU_ABI2}};
        }}

        boolean matched_an_abi = false;

        for (String abi : supported_abis) {{
{libs}
        }}

        if (!matched_an_abi) {{
            throw new UnsupportedOperationException("Could not find a native abi target to load");
        }}

    }}
}}"#, libs = libs_string, package_name = config.project_name.replace("-", "_"))?;
    Ok(())
}

fn build_manifest(_: &Workspace, path: &Path, config: &AndroidConfig) -> Result<(), CargoError> {
    fs::create_dir_all(path.join("app/src/main")).unwrap();
    let file = path.join("app/src/main/AndroidManifest.xml");
    //if fs::metadata(&file).is_ok() { return; }
    let mut file = File::create(&file)?;

    // Building application attributes
    let application_attrs = format!(r#"
            android:label="{0}"{1}{2}{3}"#,
        config.package_label,
        config.package_icon.as_ref().map_or(String::new(), |a| format!(r#"
            android:icon="{}""#, a)),
        if config.fullscreen { r#"
            android:theme="@android:style/Theme.DeviceDefault.NoActionBar.Fullscreen""#
        } else { "" },
        config.application_attributes.as_ref().map_or(String::new(), |a| a.replace("\n","\n            "))
    );

    // Buidling activity attributes
    let activity_attrs = format!(r#"
                android:name="rust.{1}.MainActivity"
                android:label="{0}"
                android:configChanges="orientation|keyboardHidden|screenSize" {2}"#,
        config.package_label,
        config.project_name.replace("-", "_"),
        config.activity_attributes.as_ref().map_or(String::new(), |a| a.replace("\n","\n                "))
    );

    // Write final AndroidManifest
    write!(
        file, r#"<?xml version="1.0" encoding="utf-8"?>
<!-- BEGIN_INCLUDE(manifest) -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="{package}"
        android:versionCode="1"
        android:versionName="1.0">

    <uses-sdk android:minSdkVersion="{minSdkVersion}" />

    <uses-feature android:glEsVersion="{glEsVersion}" android:required="true"></uses-feature>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application {application_attrs} >
        <activity {activity_attrs} >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
<!-- END_INCLUDE(manifest) -->
"#,
        package = config.package_name.replace("-", "_"),
        minSdkVersion = config.android_version,
        glEsVersion = format!("0x{:04}{:04}", config.opengles_version_major, config.opengles_version_minor),
        application_attrs = application_attrs,
        activity_attrs = activity_attrs
    )?;
    Ok(())
}

fn build_assets(_: &Workspace, path: &Path, config: &AndroidConfig) -> Result<(), CargoError> {
    let src_path = match config.assets_path {
        None => return Ok(()),
        Some(ref p) => p,
    };
    let dst_path = path.join("app").join("src").join("main").join("assets");
    if !dst_path.exists() {
        create_dir_symlink(&src_path, &dst_path)?;
    }
    Ok(())
}

fn build_res(_: &Workspace, path: &Path, config: &AndroidConfig) -> Result<(), CargoError> {
    let src_path = match config.res_path {
        None => return Ok(()),
        Some(ref p) => p,
    };

    if !src_path.exists() {
        return Err(CargoError::from("Resources directory doesn't exist"));
    }

    let dst_path = path.join("app").join("src").join("main").join("res");
    if !dst_path.exists() {
        create_dir_symlink(&src_path, &dst_path)?;
    }

    Ok(())
}

#[cfg(target_os = "windows")]
fn create_dir_symlink(src_path: &Path, dst_path: &Path) -> io::Result<()> {
    os::windows::fs::symlink_dir(&src_path, &dst_path)
}

#[cfg(not(target_os = "windows"))]
fn create_dir_symlink(src_path: &Path, dst_path: &Path) -> io::Result<()> {
    os::unix::fs::symlink(&src_path, &dst_path)
}

fn build_build_gradle_root(_: &Workspace, path: &Path, config: &AndroidConfig) -> Result<(), CargoError> {
    let file = path.join("build.gradle");
    //if fs::metadata(&file).is_ok() { return; }
    let mut file = File::create(&file).unwrap();

    write!(file, r#"
buildscript {{
    repositories {{
        jcenter()
    }}
    dependencies {{
        classpath 'com.android.tools.build:gradle:2.3.3'
    }}
}}
allprojects {{
    repositories {{
        jcenter()
    }}
}}
ext {{
    compileSdkVersion = {android_version}
    buildToolsVersion = "{build_tools_version}"
}}
"#, android_version = config.android_version,
    build_tools_version = config.build_tools_version)?;
    Ok(())
}

fn build_build_gradle_proj(_: &Workspace, path: &Path, _config: &AndroidConfig) -> Result<(), CargoError> {
    let file = path.join("app/build.gradle");
    //if fs::metadata(&file).is_ok() { return; }
    let mut file = File::create(&file).unwrap();

    write!(file, r#"
apply plugin: 'com.android.application'

android {{
    compileSdkVersion rootProject.ext.compileSdkVersion
    buildToolsVersion rootProject.ext.buildToolsVersion

    sourceSets {{
        main {{
            jniLibs.srcDirs 'lib/'
        }}
    }}
}}
"#)?;
    Ok(())
}

fn build_settings_dot_gradle(_: &Workspace, path: &Path, _: &AndroidConfig) -> Result<(), CargoError> {
    let file = path.join("settings.gradle");
    //if fs::metadata(&file).is_ok() { return; }
    let mut file = File::create(&file)?;
    write!(file, r"include ':app'")?;
    Ok(())
}

fn build_gradle_properties(_: &Workspace, path: &Path, _: &AndroidConfig) -> Result<(), CargoError> {
    let file = path.join("gradle.properties");
    //if fs::metadata(&file).is_ok() { return; }
    let mut file = File::create(&file)?;
    write!(file, r"android.builder.sdkDownload=false")?;
    Ok(())
}

fn build_local_properties(_: &Workspace, path: &Path, config: &AndroidConfig) -> Result<(), CargoError> {
    let file = path.join("local.properties");
    //if fs::metadata(&file).is_ok() { return; }
    let mut file = File::create(&file)?;

    let sdk_abs_dir = if config.sdk_path.is_absolute() {
        config.sdk_path.clone()
    } else {
        env::current_dir()?.join(&config.sdk_path)
    };

    let ndk_abs_dir = if config.ndk_path.is_absolute() {
        config.ndk_path.clone()
    } else {
        env::current_dir()?.join(&config.ndk_path)
    };

    if cfg!(target_os = "windows") {
        writeln!(file, r"sdk.dir={}", sdk_abs_dir.to_str().unwrap().replace("\\", "\\\\"))?;
    } else {
        writeln!(file, r"sdk.dir={}", sdk_abs_dir.to_str().unwrap())?;
    }

    if cfg!(target_os = "windows") {
        writeln!(file, r"ndk.dir={}", ndk_abs_dir.to_str().unwrap().replace("\\", "\\\\"))?;
    } else {
        writeln!(file, r"ndk.dir={}", ndk_abs_dir.to_str().unwrap())?;
    }

    Ok(())
}


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    style="@style/ChatList.Badge.TextView"
    android:layout_width="21sp"
    android:layout_height="21sp"
    android:background="@drawable/style_total_unread_messages"
    android:visibility="gone"
    tools:text="1"
    tools:visibility="visible" />


text:
package com.enikolas.bot.commands;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.api.objects.Chat;
import org.telegram.telegrambots.api.objects.User;
import org.telegram.telegrambots.bots.AbsSender;
import org.telegram.telegrambots.bots.commands.BotCommand;

import com.enikolas.bot.dtos.PasswordDto;
import com.enikolas.bot.dtos.SimpleLogWorkTime;
import com.enikolas.bot.services.BotService;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class LogTodayAtCommand extends BotCommand {
    @Autowired
    private BotService botService;

    public LogTodayAtCommand() {
        super("logtodayat", "Log your daily work at a giving arrived time for today");
    }

    @Override
    public void execute(AbsSender absSender, User user, Chat chat, String[] strings) {
        try {
            botService.sendMessage(absSender, chat, botService.startJobMessage());

            ResponseEntity<PasswordDto> response = botService.getPassword(user.getUserName());

            if (response == null) {
                return;
            }

            String arrivedAt = strings[0];
            arrivedAt += ":00";

            PasswordDto userData = response.getBody();
            SimpleLogWorkTime logWorkTime = SimpleLogWorkTime.builder()
                    .username(userData.getUsername())
                    .password(userData.getPassword())
                    .arrivedAt(arrivedAt)
                    .build();

            botService.logTime(logWorkTime);
            botService.sendMessage(absSender, chat, botService.succeedMessage());
        } catch (Exception e) {
            log.error("Oh-oh, something bag happened...", e);
            botService.sendMessage(absSender, chat, botService.errorMessage(false));
        }
    }
}


text:
		<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
		<title>PerfStat Tool: Perfomance Monitoring & Status Notification</title>
		<link type="text/css" rel="stylesheet" href="../../appRez/styleSheets/navigationFrame.css">

		% if ($sessionObj->param("userName") eq "perfstat" || $sessionObj->param("role") eq "admin") {

		% if ($sessionObj->param("userName") eq "perfstat") {

				<form action="index.pl" method="post">
				Admin:

					<select name="adminName" size="1" onChange="submit();">
						% foreach my $adminNameTemp (sort (keys(%$adminList))) {
						<option value="<%$adminNameTemp%>" <%$adminNameTemp eq $sessionObj->param("selectedAdmin") ? "selected" : "";%>><%$adminNameTemp%></option>
						% }
					</select>

				</form>

			%}
			% if ($sessionObj->param("role") eq "admin") {

				<form action="index.pl" method="post">
				<input type="hidden" name="adminName" value="<%$sessionObj->param("selectedAdmin")%>">
				User:

					<select name="userName" size="1" onChange="submit();">
						% foreach my $userNameTemp (sort (keys(%$userList))) {
						<option value="<%$userNameTemp%>" <%$userNameTemp eq $sessionObj->param("selectedUser")  ? "selected" : "";%>><%$userNameTemp%></option>
						% }
					</select>

				</form>

			%}

		%}

			Status Monitor

						open all

						close all

						Perfstat Server

					%if ($sessionObj->param('showAllHosts')) {

						All Hosts

					%}

						My Host Groups

						Shared Host Groups


text:
package utils;

import java.util.List;

import org.apache.commons.lang3.builder.ToStringBuilder;

public class GridViewModel {

    public int page;
    public int total;
    public int records;
    public List<RowViewModel> rows;

    public GridViewModel(int page, int total, int records, List<RowViewModel> rows) {
        this.page = page;
        this.total = total;
        this.records = records;
        this.rows = rows;
    }

    public GridViewModel(Paging pageData, int totalEntries, List<RowViewModel> rows) {
        this(pageData.pageIndex(), totalPagesFrom(totalEntries,pageData.rowsPerPage()), totalEntries, rows);
    }

    public static int totalPagesFrom(int totalEntries, int rowsPerPage) {
        double pages = (double)totalEntries/(double)rowsPerPage;
        if(pages == 0d) {
            return 1;
        }
        return (int) Math.ceil(pages);
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }

    public static class RowViewModel {
        public int id;
        public List<String> cell;

        public RowViewModel(int id, List<String> cell) {
            this.id = id;
            this.cell = cell;
        }

        @Override
        public String toString() {
            return ToStringBuilder.reflectionToString(this);
        }
    }

    public static class PageData implements Paging {
        // The names of the fields are in line with the URL parameters sent by jQGrid.
        private int rows;
        private int page;

        public PageData() { // required for the Spring MVC data binding
        }

        public PageData(int rows, int page) {
            this.rows = rows;
            this.page = page;
        }

        public void setRows(int rows) {
            this.rows = rows;
        }

        public void setPage(int page) {
            this.page = page;
        }

        @Override
        public int rowsPerPage() {
            return rows;
        }

        @Override
        public int pageIndex() {
            return page;
        }
    }

    public static class SortData implements Sorting {
        // The names of the fields are in line with the URL parameters sent by jQGrid.
        private String sidx;
        private String sord;

        public void setSidx(String sidx) {
            this.sidx = sidx;
        }

        public void setSord(String sord) {
            this.sord = sord;
        }

        @Override
        public String sortBy() {
            return sidx;
        }

        @Override
        public SortOrder sortOrder() {
            return "desc".equals(sord) ? SortOrder.DESCENDING: SortOrder.ASCENDING;
        }
    }
}


text:
namespace ash {

namespace {

base::LazyInstance<SyncedPrintersManagerFactory>::DestructorAtExit
    g_printers_manager = LAZY_INSTANCE_INITIALIZER;

}  // namespace

// static
SyncedPrintersManager* SyncedPrintersManagerFactory::GetForBrowserContext(
    content::BrowserContext* context) {
  return static_cast<SyncedPrintersManager*>(
      GetInstance()->GetServiceForBrowserContext(context, true));
}

// static
SyncedPrintersManagerFactory* SyncedPrintersManagerFactory::GetInstance() {
  return g_printers_manager.Pointer();
}

content::BrowserContext* SyncedPrintersManagerFactory::GetBrowserContextToUse(
    content::BrowserContext* context) const {
  return chrome::GetBrowserContextRedirectedInIncognito(context);
}

SyncedPrintersManagerFactory::SyncedPrintersManagerFactory()
    : BrowserContextKeyedServiceFactory(
          "SyncedPrintersManager",
          BrowserContextDependencyManager::GetInstance()) {
  DependsOn(ModelTypeStoreServiceFactory::GetInstance());
}

SyncedPrintersManagerFactory::~SyncedPrintersManagerFactory() = default;

SyncedPrintersManager* SyncedPrintersManagerFactory::BuildServiceInstanceFor(
    content::BrowserContext* browser_context) const {
  Profile* profile = Profile::FromBrowserContext(browser_context);

  syncer::OnceModelTypeStoreFactory store_factory =
      ModelTypeStoreServiceFactory::GetForProfile(profile)->GetStoreFactory();

  std::unique_ptr<PrintersSyncBridge> sync_bridge =
      std::make_unique<PrintersSyncBridge>(
          std::move(store_factory),
          base::BindRepeating(&syncer::ReportUnrecoverableError,
                              chrome::GetChannel()));

  return SyncedPrintersManager::Create(std::move(sync_bridge)).release();
}

}  // namespace ash


text:
      {% include site_nav.html page=page %}

      © 2010 - {{ site.time | date: '%Y' }}
      ENSIME Contributors

      Content Licence: CC BY-SA 3.0

      Theme Licence: Apache 2.0

      Code of Conduct: Typelevel


text:
RM_DIR=${PREFIX}/share/RepeatMasker
RM_OTHER_PROGRAMS="DateRepeats ProcessRepeats RepeatProteinMask DupMasker util/queryRepeatDatabase.pl util/queryTaxonomyDatabase.pl util/rmOutToGFF3.pl util/rmToUCSCTables.pl util/buildRMLibFromEMBL.pl"
RM_PROGRAMS="RepeatMasker $RM_OTHER_PROGRAMS"

mkdir -p ${PREFIX}/bin
mkdir -p ${RM_DIR}
cp -r * ${RM_DIR}
for name in ${RM_PROGRAMS} ; do
  sed -i 's$^#!.*perl.*$#!/usr/bin/env perl$g;' ${RM_DIR}/${name}
done

cp ${RECIPE_DIR}/RepeatMaskerConfig.pm ${RM_DIR}/RepeatMaskerConfig.pm
# pvanheus - disabled this because the library included with RepeatMasker is too old to be usable
# users will have to provide their own library and point to it using the REPEATMASKER_LIB_DIR environment variable

${RM_DIR}/util/buildRMLibFromEMBL.pl ${RM_DIR}/Libraries/RepeatMaskerLib.embl > ${RM_DIR}/Libraries/RepeatMasker.lib 2>/dev/null
makeblastdb -dbtype nucl -in ${RM_DIR}/Libraries/RepeatMasker.lib
makeblastdb -dbtype prot -in ${RM_DIR}/Libraries/RepeatPeps.lib

cat <<END >>${PREFIX}/bin/RepeatMasker
#!/bin/bash

REPEATMASKER_DIR=\${REPEATMASKER_DIR:-\${CONDA_PREFIX}/share/RepeatMasker}
REPEATMASKER_MATRICES_DIR=\${REPEATMASKED_MATRICES_DIR:-\${CONDA_PREFIX}/share/RepeatMasker/Matrices}
REPEATMASKER_LIB_DIR=\${REPEATMASKER_LIB_DIR:-\${CONDA_PREFIX}/share/RepeatMasker/Libraries}
TRF_DIR=${PREFIX}/bin
RMBLAST_DIR=${PREFIX}/bin
HMMER_DIR=${PREFIX}/bin
export REPEATMASKER_DIR REPEATMASKER_LIB_DIR REPEATMASKER_MATRICES_DIR TRF_DIR RMBLAST_DIR HMMER_DIR

NAME=\$(basename \$0)

perl ${RM_DIR}/\${NAME} \$@
END

chmod a+x ${PREFIX}/bin/RepeatMasker
for name in ${RM_OTHER_PROGRAMS} ; do
  ln -s ${PREFIX}/bin/RepeatMasker ${PREFIX}/bin/$(basename $name)
done


text:
package org.locationtech.geogig.api.plumbing;

import java.util.Collection;
import java.util.Map;
import java.util.Set;

import org.locationtech.geogig.api.AbstractGeoGigOp;
import org.locationtech.geogig.api.ObjectId;
import org.locationtech.geogig.api.Ref;
import org.locationtech.geogig.api.SymRef;

import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableSet;

/**
 * Resolve a ref name to the stored {@link Ref reference} object
 */
public class RefParse extends AbstractGeoGigOp<Optional<Ref>> {

    private static final Set<String> STANDARD_REFS = ImmutableSet.of(Ref.HEAD, Ref.MASTER,
            Ref.ORIGIN, Ref.STAGE_HEAD, Ref.WORK_HEAD);

    private String refSpec;

    /**
     * @param name the name of the ref to parse
     * @return {@code this}
     */
    public RefParse setName(String name) {
        this.refSpec = name;
        return this;
    }

    /**
     * Parses a geogig reference string (possibly abbreviated) and return the resolved {@link Ref}
     * or {@code absent} if the ref spec didn't resolve to any actual reference.
     *
     * Combinations of these operators are supported:
     *

     *
HEAD, MERGE_HEAD, FETCH_HEAD, STAGE_HEAD, WORK_HEAD

     *
refs/...: a complete reference name

     *
short-name: a short reference name under {@code refs/heads}, {@code refs/tags}, or
     * {@code refs/remotes} namespace, in that order of precedence

     *

     *
     * @return an {@code Optional} that contains a {@link Ref reference} or
     *         {@link Optional#absent()} if revstr can't be resolved to any {@link ObjectId}
     * @throws IllegalArgumentException if {@code refSpec} resolves to more than one ref on the same
     *         namespace
     */
    @Override
    protected Optional<Ref> _call() {
        Preconditions.checkState(refSpec != null, "name has not been set");

        if (STANDARD_REFS.contains(refSpec) || refSpec.startsWith("refs/")) {
            return getRef(refSpec);
        }

        // is it a top level ref?
        if (!refSpec.startsWith("refs/")) {
            Optional<Ref> ref = getRef(refSpec);
            if (ref.isPresent()) {
                return ref;
            }
        }

        Map<String, String> allRefs = refDatabase().getAll();

        class PrePostfixPredicate implements Predicate<String> {

            private String prefix;

            private String suffix;

            public PrePostfixPredicate(String prefix, String suffix) {
                this.prefix = prefix;
                this.suffix = suffix;
            }

            @Override
            public boolean apply(String refName) {
                boolean applies = refName.startsWith(prefix) && refName.endsWith(suffix);
                return applies;
            }

        }
        Collection<String> heads = Collections2.filter(allRefs.keySet(), new PrePostfixPredicate(
                "refs/heads", "/" + refSpec));
        Collection<String> tags = Collections2.filter(allRefs.keySet(), new PrePostfixPredicate(
                "refs/tags", "/" + refSpec));
        Collection<String> remotes = Collections2.filter(allRefs.keySet(), new PrePostfixPredicate(
                "refs/remotes", "/" + refSpec));

        String refName;
        refName = resolveSingle(heads);
        if (refName == null) {
            refName = resolveSingle(tags);
        }
        if (refName == null) {
            refName = resolveSingle(remotes);
        }
        if (refName == null) {
            return Optional.absent();
        }
        return getRef(refName);
    }

    private String resolveSingle(Collection<String> refNames) {
        if (refNames.isEmpty()) {
            return null;
        }
        if (refNames.size() == 1) {
            return refNames.iterator().next();
        }
        throw new IllegalArgumentException(refSpec + " resolves to more than one ref: " + refNames);
    }

    private Optional<Ref> getRef(final String name) {
        String storedValue;
        boolean sym = false;
        try {
            storedValue = refDatabase().getRef(name);
        } catch (IllegalArgumentException notARef) {
            storedValue = refDatabase().getSymRef(name);
            if (null == storedValue) {
                return Optional.absent();
            }
            sym = true;
        }
        if (null == storedValue) {
            storedValue = refDatabase().getSymRef(name);
            if (null == storedValue) {
                return Optional.absent();
            }
            sym = true;
        }

        if (sym) {
            Optional<Ref> target = getRef(storedValue);
            if (!target.isPresent()) {
                throw new RuntimeException("target '" + storedValue
                        + "' was not present for symref " + name + " -> '" + storedValue + "'");
            }
            Ref resolved = new SymRef(name, target.get());
            return Optional.of(resolved);
        }
        ObjectId objectId = ObjectId.valueOf(storedValue);
        return Optional.of(new Ref(name, objectId));
    }

}