text:
<?php
namespace net\authorize\util;

use net\authorize\util\ANetSensitiveFields;

define ("ANET_LOG_FILES_APPEND",true);

define("ANET_LOG_DEBUG_PREFIX","DEBUG");
define("ANET_LOG_INFO_PREFIX","INFO");
define("ANET_LOG_WARN_PREFIX","WARN");
define("ANET_LOG_ERROR_PREFIX","ERROR");

//log levels
define('ANET_LOG_DEBUG',1);
define("ANET_LOG_INFO",2);
define("ANET_LOG_WARN",3);
define("ANET_LOG_ERROR",4);

//set level
define("ANET_LOG_LEVEL",ANET_LOG_DEBUG);

/**
 * A class to implement logging.
 *
 * @package    AuthorizeNet
 * @subpackage net\authorize\util
 */

class Log
{
    private $sensitiveXmlTags = NULL;
    private $logFile = '';

	/**
	* Takes a regex pattern (string) as argument and adds the forward slash delimiter.
	* Also adds the u flag to enable Unicode mode regex.
	*
	* @param string $regexPattern
	*
	* @return string
	*/
	private function addDelimiterFwdSlash($regexPattern)
	{
		return '/'.$regexPattern.'/u';
	}

	/**
	* Takes an xml as string and masks the sensitive fields.
	*
	* @param string $rawString		The xml as a string.
	*
	* @return string 		The xml as a string after masking sensitive fields
	*/
    private function maskSensitiveXmlString($rawString){
        $patterns=array();
        $replacements=array();

        foreach ($this->sensitiveXmlTags as $i => $sensitiveTag){
            $tag = $sensitiveTag->tagName;
            $inputPattern = "(.+)"; //no need to mask null data
            $inputReplacement = "xxxx";

            if(trim($sensitiveTag->pattern)) {
                $inputPattern = $sensitiveTag->pattern;
            }
            $pattern = "<" . $tag . ">(?:.*)". $inputPattern ."(?:.*)<\/" . $tag . ">";
			$pattern = $this->addDelimiterFwdSlash($pattern);

            if(trim($sensitiveTag->replacement)) {
                $inputReplacement = $sensitiveTag->replacement;
            }
            $replacement = "<" . $tag . ">" . $inputReplacement . "</" . $tag . ">";

            $patterns [$i] = $pattern;
            $replacements[$i]  = $replacement;
        }
        $maskedString = preg_replace($patterns, $replacements, $rawString);
        return $maskedString;
    }

    /**
     * Takes a string and masks credit card regex matching parts.
     *
     * @param string $rawString		The string.
     *
     * @return string 		The string after masking credit card regex matching parts.
     */
    private function maskCreditCards($rawString){
        $patterns=array();
        $replacements=array();

        foreach ($this->sensitiveStringRegexes as $i => $creditCardRegex){
            $pattern = $creditCardRegex;
			$pattern = $this->addDelimiterFwdSlash($pattern);

            $replacement = "xxxx";
            $patterns [$i] = $pattern;
            $replacements[$i]  = $replacement;
        }
        $maskedString = preg_replace($patterns, $replacements, $rawString);
        return $maskedString;
    }

	/**
	* Object data masking related functions START
	*/

	/**
	* private function getPropertiesInclBase($reflClass).
	*
	* Receives a ReflectionObject, ...
	* iteratively fetches the properties of the object (including from the base classes up the hierarchy), ...
	* collects them in an array of ReflectionProperty and returns the array.
	*
	* @param ReflectionObject $reflClass
	*
	* @return \ReflectionProperty[]
	*/
	private function getPropertiesInclBase($reflClass)
	{
		$properties = array();
		try {
			do {
				$curClassPropList = $reflClass->getProperties();
				foreach ($curClassPropList as $p) {
					$p->setAccessible(true);
				}
				$properties = array_merge($curClassPropList, $properties);
			} while ($reflClass = $reflClass->getParentClass());
		} catch (\ReflectionException $e) { }
		return $properties;
	}

	/**
	* private function checkPropertyAndMask($prop, $obj).
	*
	* Receives a ReflectionProperty and an object, and returns a masked object if the ReflectionProperty corresponds to a sensitive field, else returns false.
	*
	* @param ReflectionProperty $prop
	* @param object $obj
	*
	* @return string|bool
	*/
	private function checkPropertyAndMask($prop, $obj){
		foreach($this->sensitiveXmlTags as $i => $sensitiveField)
		{
			$inputPattern = "(.+)";
			$inputReplacement = "xxxx";

            if(trim($sensitiveField->pattern)) {
                $inputPattern = $sensitiveField->pattern;
            }
			$inputPattern = $this->addDelimiterFwdSlash($inputPattern);

            if(trim($sensitiveField->replacement)) {
                $inputReplacement = $sensitiveField->replacement;
            }

			if(strcmp($prop->getName(),$sensitiveField->tagName)==0)
			{
				$prop->setValue($obj,preg_replace($inputPattern,$inputReplacement,$prop->getValue($obj)));
				return $prop->getValue($obj);
			}
		}
		return false;
	}

	/**
	* called by getMasked() to mask sensitive fields of an object.
	*
	* @param object $obj
	*
	* @return object
	*/
    private function maskSensitiveProperties ($obj)
    {
		// first retrieve all properties of the passed object
        $reflectObj = new \ReflectionObject($obj);
        $props = $this->getPropertiesInclBase($reflectObj);

		// for composite property recursively execute; for scalars, do a check and mask
        foreach($props as $i => $prop){
			$propValue=$prop->getValue($obj);

			// for object and arrays, recursively call for inner elements
			if(is_object($propValue)){
				$prop->setValue($obj, $this->maskSensitiveProperties($propValue));
            }
			else if(is_array($propValue)){
				$newVals=array();
				foreach($propValue as $i=>$arrEle)
				{
					$newVals[]=$this->maskSensitiveProperties($arrEle);
				}
				$prop->setValue($obj, $newVals);
            }
			// else check if the property represents a sensitive field. If so, mask.
            else{
				$res=$this->checkPropertyAndMask($prop, $obj);
				if($res)
					$prop->setValue($obj, $res);
            }
        }

        return $obj;
    }

	/**
	* Object data masking related functions END
	*/

	/**
	* private function getMasked($raw).
	*
	* called by log()
	*
	* @param mixed $raw
	*
	* @return string
	*/
    private function getMasked($raw)
    { //always returns string
        $messageType = gettype($raw);
        $message="";
        if($messageType == "object"){
			$obj = unserialize(serialize($raw)); // deep copying the object
			$message = print_r($this->maskSensitiveProperties($obj), true); //object to string
        }
        else if($messageType == "array"){
            $copyArray = unserialize(serialize($raw));
            foreach($copyArray as $i => $element){
                $copyArray[$i] = $this->getMasked($element);
            }
            $message = print_r($copyArray, true); // returns string
        }
        else { //$messageType == "string")
            $primtiveTypeAsString = strval($raw);

            $maskedXml = $primtiveTypeAsString;
            if($messageType == "string") {
                $maskedXml = $this->maskSensitiveXmlString($primtiveTypeAsString);
            }
            //mask credit card numbers
            $message = $this->maskCreditCards($maskedXml);
        }
        return $message;
    }

	private function log($logLevelPrefix, $logMessage, $flags){
        if (!$this->logFile) return;
        //masking
        $logMessage = $this->getMasked($logMessage);

        //debug_backtrace
        $fileName = 'n/a';
        $methodName = 'n/a';
        $lineNumber = 'n/a';
        $debugTrace = debug_backtrace();
        if (isset($debugTrace[1])) {
            $fileName = $debugTrace[1]['file'] ? $debugTrace[1]['file'] : 'n/a';
            $lineNumber = $debugTrace[1]['line'] ? $debugTrace[1]['line'] : 'n/a';
        }
        if (isset($debugTrace[2])) $methodName = $debugTrace[2]['function'] ? $debugTrace[2]['function'] : 'n/a';

        //Add timestamp, log level, method, file, line
        $logString = sprintf("\n %s %s : [%s] (%s : %s) - %s", \net\authorize\util\Helpers::now(), $logLevelPrefix,
            $methodName, $fileName, $lineNumber, $logMessage);
        file_put_contents($this->logFile, $logString, $flags);
    }

    public function debug($logMessage, $flags=FILE_APPEND)
    {
        if(ANET_LOG_DEBUG >= ANET_LOG_LEVEL){
            $this->log(ANET_LOG_DEBUG_PREFIX, $logMessage,$flags);
        }
    }

    public function info($logMessage, $flags=FILE_APPEND){
        if(ANET_LOG_INFO >= ANET_LOG_LEVEL) {
            $this->log(ANET_LOG_INFO_PREFIX, $logMessage,$flags);
        }
    }

	public function warn($logMessage, $flags=FILE_APPEND){
        if(ANET_LOG_WARN >= ANET_LOG_LEVEL) {
            $this->log(ANET_LOG_WARN_PREFIX, $logMessage,$flags);
        }
    }

    public function error($logMessage, $flags=FILE_APPEND){
        if(ANET_LOG_ERROR >= ANET_LOG_LEVEL) {
            $this->log(ANET_LOG_ERROR_PREFIX, $logMessage,$flags);
        }
    }

	private function logFormat($logLevelPrefix, $format, $objects, $flags){
        try {
            foreach($objects as $i => $testObject){
                $objects[$i] = $this->getMasked($testObject);
            }
            $logMessage = vsprintf($format, $objects);
            $this->log($logLevelPrefix, $logMessage, $flags);
        }
        catch(\Exception $e){
            $this->debug("Incorrect log message format: " . $e->getMessage());
        }
    }

	public function debugFormat($format, $args=array(),  $flags=FILE_APPEND)
    {
        if(ANET_LOG_DEBUG >= ANET_LOG_LEVEL){
            $this->logFormat(ANET_LOG_DEBUG_PREFIX, $format, $args , $flags);
        }
    }

	public function infoFormat($format, $args=array(),  $flags=FILE_APPEND){
        if(ANET_LOG_INFO >= ANET_LOG_LEVEL) {
            $this->logFormat(ANET_LOG_INFO_PREFIX, $format, $args , $flags);
        }
    }

	public function warnFormat($format, $args=array(),  $flags=FILE_APPEND){
        if(ANET_LOG_WARN >= ANET_LOG_LEVEL) {
            $this->logFormat(ANET_LOG_WARN_PREFIX, $format, $args , $flags);
        }
    }

    public function errorFormat($format, $args=array(),  $flags=FILE_APPEND){
        if(ANET_LOG_ERROR >= ANET_LOG_LEVEL) {
			$this->logFormat(ANET_LOG_ERROR_PREFIX, $format, $args , $flags);
        }
    }

    /**
     * @param string $logFile
     */
    public function setLogFile($logFile){
        $this->logFile = $logFile;
    }

    /**
     * @return string
     */
    public function getLogFile(){
        return $this->logFile;
    }

    public function __construct(){
        $this->sensitiveXmlTags = ANetSensitiveFields::getSensitiveXmlTags();
        $this->sensitiveStringRegexes = ANetSensitiveFields::getSensitiveStringRegexes();
    }
}
?>


text:
namespace CodingStyleHacker
{
    partial class Form1
    {
        /// <summary>
        /// 設計工具所需的變數。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清除任何使用中的資源。
        /// </summary>
        /// <param name="disposing">如果應該處置 Managed 資源則為 true,否則為 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form 設計工具產生的程式碼

        /// <summary>
        /// 此為設計工具支援所需的方法 - 請勿使用程式碼編輯器
        /// 修改這個方法的內容。
        /// </summary>
        private void InitializeComponent()
        {
            this.metroButton1 = new MetroFramework.Controls.MetroButton();
            this.splitContainer1 = new System.Windows.Forms.SplitContainer();
            this.metroLabel1 = new MetroFramework.Controls.MetroLabel();
            this.metroLabel2 = new MetroFramework.Controls.MetroLabel();
            this.richTextBox1 = new System.Windows.Forms.RichTextBox();
            this.richTextBox2 = new System.Windows.Forms.RichTextBox();
            this.splitContainer1.Panel1.SuspendLayout();
            this.splitContainer1.Panel2.SuspendLayout();
            this.splitContainer1.SuspendLayout();
            this.SuspendLayout();
            //
            // metroButton1
            //
            this.metroButton1.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.metroButton1.Location = new System.Drawing.Point(20, 383);
            this.metroButton1.Name = "metroButton1";
            this.metroButton1.Size = new System.Drawing.Size(475, 23);
            this.metroButton1.TabIndex = 6;
            this.metroButton1.Text = "Source Code 混淆";
            this.metroButton1.UseSelectable = true;
            this.metroButton1.Click += new System.EventHandler(this.metroButton1_Click);
            //
            // splitContainer1
            //
            this.splitContainer1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.splitContainer1.Location = new System.Drawing.Point(20, 30);
            this.splitContainer1.Name = "splitContainer1";
            //
            // splitContainer1.Panel1
            //
            this.splitContainer1.Panel1.Controls.Add(this.richTextBox1);
            this.splitContainer1.Panel1.Controls.Add(this.metroLabel2);
            //
            // splitContainer1.Panel2
            //
            this.splitContainer1.Panel2.Controls.Add(this.richTextBox2);
            this.splitContainer1.Panel2.Controls.Add(this.metroLabel1);
            this.splitContainer1.Size = new System.Drawing.Size(475, 353);
            this.splitContainer1.SplitterDistance = 226;
            this.splitContainer1.TabIndex = 7;
            //
            // metroLabel1
            //
            this.metroLabel1.Dock = System.Windows.Forms.DockStyle.Top;
            this.metroLabel1.Location = new System.Drawing.Point(0, 0);
            this.metroLabel1.Name = "metroLabel1";
            this.metroLabel1.Size = new System.Drawing.Size(243, 23);
            this.metroLabel1.TabIndex = 0;
            this.metroLabel1.Text = "混淆後Source Code";
            this.metroLabel1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            //
            // metroLabel2
            //
            this.metroLabel2.Dock = System.Windows.Forms.DockStyle.Top;
            this.metroLabel2.Location = new System.Drawing.Point(0, 0);
            this.metroLabel2.Name = "metroLabel2";
            this.metroLabel2.Size = new System.Drawing.Size(224, 23);
            this.metroLabel2.TabIndex = 1;
            this.metroLabel2.Text = "原始版本Source Code";
            this.metroLabel2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            //
            // richTextBox1
            //
            this.richTextBox1.BorderStyle = System.Windows.Forms.BorderStyle.None;
            this.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.richTextBox1.Location = new System.Drawing.Point(0, 23);
            this.richTextBox1.Name = "richTextBox1";
            this.richTextBox1.Size = new System.Drawing.Size(224, 328);
            this.richTextBox1.TabIndex = 2;
            this.richTextBox1.Text = "#include <iostream>\nusing namespace std;\n\nint main()\n{\n    int i,sum=0;\n    for (" +
    "i=0;i<101;i++)\n    {\n        sum+=i;\n    }\n    cout << sum << \"\\n\";\n    system(\"" +
    "pause\");\n    return 0;\n}";
            //
            // richTextBox2
            //
            this.richTextBox2.BorderStyle = System.Windows.Forms.BorderStyle.None;
            this.richTextBox2.Dock = System.Windows.Forms.DockStyle.Fill;
            this.richTextBox2.Location = new System.Drawing.Point(0, 23);
            this.richTextBox2.Name = "richTextBox2";
            this.richTextBox2.Size = new System.Drawing.Size(243, 328);
            this.richTextBox2.TabIndex = 3;
            this.richTextBox2.Text = "";
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(515, 426);
            this.Controls.Add(this.splitContainer1);
            this.Controls.Add(this.metroButton1);
            this.DisplayHeader = false;
            this.Name = "Form1";
            this.Padding = new System.Windows.Forms.Padding(20, 30, 20, 20);
            this.ShadowType = MetroFramework.Forms.MetroFormShadowType.DropShadow;
            this.Text = "Form1";
            this.splitContainer1.Panel1.ResumeLayout(false);
            this.splitContainer1.Panel2.ResumeLayout(false);
            this.splitContainer1.ResumeLayout(false);
            this.ResumeLayout(false);

        }

        #endregion

        private MetroFramework.Controls.MetroButton metroButton1;
        private System.Windows.Forms.SplitContainer splitContainer1;
        private System.Windows.Forms.RichTextBox richTextBox1;
        private MetroFramework.Controls.MetroLabel metroLabel2;
        private System.Windows.Forms.RichTextBox richTextBox2;
        private MetroFramework.Controls.MetroLabel metroLabel1;
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TheAionProject
{
    /// <summary>
    /// the character class the player uses in the game
    /// </summary>
    public class Traveler : Character
    {
        #region ENUMERABLES
        public enum StartingItem
        {
            None,
            Berry,
            HealthPak,
            StimPak
        }
        #endregion

        #region FIELDS
        private string _homePlanet;
        private bool _isTerrorist;
        private Enum _startingItem;
        #endregion

        #region PROPERTIES

        public string HomePlanet
        {
            get { return _homePlanet; }
            set { _homePlanet = value; }
        }
        public bool IsTerrorist
        {
            get { return _isTerrorist; }
            set { _isTerrorist = value; }
        }

        #endregion

        #region CONSTRUCTORS

        public Traveler()
        {

        }

        public Traveler(string name, RaceType race, int spaceTimeLocationID) : base(name, race, spaceTimeLocationID)
        {

        }

        #endregion

        #region METHODS

        public override string Greeting()
        {
            return $"Greetings, I am {base.Name}, and I am {base.Race}, and I am from {HomePlanet}";
        }
        #endregion
    }
}


text:
package alluxio.fuse;

import alluxio.Configuration;
import alluxio.PropertyKey;
import alluxio.client.file.FileSystem;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.concurrent.ThreadSafe;

/**
 * Main entry point to Alluxio-FUSE.
 */
@ThreadSafe
public final class AlluxioFuse {
  private static final Logger LOG = LoggerFactory.getLogger(AlluxioFuse.class);

  // prevent instantiation
  private AlluxioFuse() {
  }

  /**
   * Running this class will mount the file system according to
   * the options passed to this function {@link #parseOptions(String[])}.
   * The user-space fuse application will stay on the foreground and keep
   * the file system mounted. The user can unmount the file system by
   * gracefully killing (SIGINT) the process.
   *
   * @param args arguments to run the command line
   */
  public static void main(String[] args) {
    final AlluxioFuseOptions opts = parseOptions(args);
    if (opts == null) {
      System.exit(1);
    }

    final FileSystem tfs = FileSystem.Factory.get();
    final AlluxioFuseFileSystem fs = new AlluxioFuseFileSystem(tfs, opts);
    final List<String> fuseOpts = opts.getFuseOpts();
    // Force direct_io in FUSE: writes and reads bypass the kernel page
    // cache and go directly to alluxio. This avoids extra memory copies
    // in the write path.
    fuseOpts.add("-odirect_io");

    try {
      fs.mount(Paths.get(opts.getMountPoint()), true, opts.isDebug(),
          fuseOpts.toArray(new String[0]));
    } finally {
      fs.umount();
    }
  }

  /**
   * Parses CLI options.
   *
   * @param args CLI args
   * @return Alluxio-FUSE configuration options
   */
  private static AlluxioFuseOptions parseOptions(String[] args) {
    final Options opts = new Options();
    final Option mntPoint = Option.builder("m")
        .hasArg()
        .required(false)
        .longOpt("mount-point")
        .desc("Desired local mount point for alluxio-fuse.")
        .build();

    final Option alluxioRoot = Option.builder("r")
        .hasArg()
        .required(false)
        .longOpt("alluxio-root")
        .desc("Path within alluxio that will be used as the root of the FUSE mount "
            + "(e.g., /users/foo; defaults to /)")
        .build();

    final Option help = Option.builder("h")
        .required(false)
        .desc("Print this help")
        .build();

    final Option fuseOption = Option.builder("o")
        .valueSeparator(',')
        .required(false)
        .hasArgs()
        .desc("FUSE mount options")
        .build();

    opts.addOption(mntPoint);
    opts.addOption(alluxioRoot);
    opts.addOption(help);
    opts.addOption(fuseOption);

    final CommandLineParser parser = new DefaultParser();
    try {
      CommandLine cli = parser.parse(opts, args);

      if (cli.hasOption("h")) {
        final HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp(AlluxioFuse.class.getName(), opts);
        return null;
      }

      String mntPointValue = cli.getOptionValue("m");
      String alluxioRootValue = cli.getOptionValue("r");

      List<String> fuseOpts = new ArrayList<>();
      boolean noUserMaxWrite = true;
      if (cli.hasOption("o")) {
        String[] fopts = cli.getOptionValues("o");
        // keep the -o
        for (final String fopt: fopts) {
          fuseOpts.add("-o" + fopt);
          if (noUserMaxWrite && fopt.startsWith("max_write")) {
            noUserMaxWrite = false;
          }
        }
      }
      // check if the user has specified his own max_write, otherwise get it
      // from conf
      if (noUserMaxWrite) {
        final long maxWrite = Configuration.getLong(PropertyKey.FUSE_MAXWRITE_BYTES);
        fuseOpts.add(String.format("-omax_write=%d", maxWrite));
      }

      if (mntPointValue == null) {
        mntPointValue = Configuration.get(PropertyKey.FUSE_MOUNT_DEFAULT);
        LOG.info("Mounting on default {}", mntPointValue);
      }

      if (alluxioRootValue == null) {
        alluxioRootValue = Configuration.get(PropertyKey.FUSE_FS_ROOT);
        LOG.info("Using default alluxio root {}", alluxioRootValue);
      }

      final boolean fuseDebug = Configuration.getBoolean(PropertyKey.FUSE_DEBUG_ENABLED);

      return new AlluxioFuseOptions(mntPointValue, alluxioRootValue, fuseDebug, fuseOpts);
    } catch (ParseException e) {
      System.err.println("Error while parsing CLI: " + e.getMessage());
      final HelpFormatter fmt = new HelpFormatter();
      fmt.printHelp(AlluxioFuse.class.getName(), opts);
      return null;
    }
  }
}


text:
/*
 *  The "markdown" plugin. It's indented to enhance the
 *  "sourcearea" editing mode, convert to markdown mode and highlight syntax.
 * Licensed under the MIT license
 * CodeMirror Plugin: http://codemirror.net/ (MIT License)
 * Markdown Parser:
 * HTML to Markdown Parser:
 */
'use strict';
(function() {
    CKEDITOR.plugins.add('markdown', {
        // lang: 'en,zh', // %REMOVE_LINE_CORE%
        icons: 'markdown',
        hidpi: true, // %REMOVE_LINE_CORE%
        init: function(editor) {
            // Source mode in inline editors is only available through the "sourcedialog" plugin.
            if (editor.elementMode == CKEDITOR.ELEMENT_MODE_INLINE)
                return;

            var markdown = CKEDITOR.plugins.markdown,
                rootPath = this.path,
                defaultConfig = {
                    mode: 'gfm',
                    lineNumbers: true,
                    theme: 'default'
                };
            editor.config.markdown = CKEDITOR.tools.extend(defaultConfig, editor.config.markdown || {}, true);

            editor.addMode('markdown', function(callback) {
                var contentsSpace = editor.ui.space('contents'),
                    textarea = contentsSpace.getDocument().createElement('textarea'),
                    config = editor.config.markdown;

                textarea.setStyles(
                    CKEDITOR.tools.extend({
                            // IE7 has overflow the <textarea> from wrapping table cell.
                            width: CKEDITOR.env.ie7Compat ? '99%' : '100%',
                            height: '100%',
                            resize: 'none',
                            outline: 'none',
                            'text-align': 'left'
                        },
                        CKEDITOR.tools.cssVendorPrefix('tab-size', editor.config.sourceAreaTabSize || 4)));

                // Make sure that source code is always displayed LTR,
                // regardless of editor language (#10105).
                textarea.setAttribute('dir', 'ltr');

                textarea.addClass('cke_source').addClass('cke_reset').addClass('cke_enable_context_menu');  // fix issue #2

                editor.ui.space('contents').append(textarea);

                var editable = editor.editable(new sourceEditable(editor, textarea)),
                    htmlData = editor.getData(1).replace(/(\r\n|\n|\r)/gm,""); // remove all linebreaks to prevent some parsing issues

                // Convert to Markdown and Fill the textarea.
                if (typeof(toMarkdown) == 'undefined') {
                    CKEDITOR.scriptLoader.load(rootPath + 'js/to-markdown.js', function() {
                        editable.setData(toMarkdown(htmlData));
                    });
                } else {
                    editable.setData(toMarkdown(htmlData));
                }

                if (typeof (CodeMirror) == 'undefined' || typeof (CodeMirror.modes.gfm) == 'undefined') {
                    CKEDITOR.document.appendStyleSheet(rootPath + 'css/codemirror.min.css');

                    if (config.theme.length && config.theme != 'default') {
                        CKEDITOR.document.appendStyleSheet(rootPath + 'theme/' + config.theme + '.css');
                    }

                    CKEDITOR.scriptLoader.load(rootPath + 'js/codemirror-gfm-min.js', function() {
                        loadCodeMirror(editor, editable);
                    });
                } else {
                    loadCodeMirror(editor, editable);
                }
                if (typeof(marked) == 'undefined') {
                    CKEDITOR.scriptLoader.load(rootPath + 'js/marked.js');
                }
                // Having to make <textarea> fixed sized to conquer the following bugs:
                // 1. The textarea height/width='100%' doesn't constraint to the 'td' in IE6/7.
                // 2. Unexpected vertical-scrolling behavior happens whenever focus is moving out of editor
                // if text content within it has overflowed. (#4762)
                if (CKEDITOR.env.ie) {
                    editable.attachListener(editor, 'resize', onResize, editable);
                    editable.attachListener(CKEDITOR.document.getWindow(), 'resize', onResize, editable);
                    CKEDITOR.tools.setTimeout(onResize, 0, editable);
                }

                editor.fire('ariaWidget', this);
                editor.commands.maximize.modes.markdown = 1;
                callback();
            });

            function loadCodeMirror(editor, editable){
                window["codemirror_" + editor.id] = CodeMirror.fromTextArea(editable.$, editor.config.markdown);
                window["codemirror_" + editor.id].setSize(null, '100%');
            }

            editor.addCommand('markdown', markdown.commands.markdown);

            if (editor.ui.addButton) {
                editor.ui.addButton('Markdown', {
                    label: 'Markdown',
                    command: 'markdown'
                    // toolbar: 'mode,10'
                });
            }
            CKEDITOR.document.appendStyleText('.cke_button__markdown_label {display: inline;}'); // display button Label
            editor.on('mode', function() {
                editor.getCommand('markdown').setState(editor.mode == 'markdown' ? CKEDITOR.TRISTATE_ON : CKEDITOR.TRISTATE_OFF);
            });

            var needsFocusHack = CKEDITOR.env.ie && CKEDITOR.env.version == 9;

            function onResize() {
                // We have to do something with focus on IE9, because if sourcearea had focus
                // before being resized, the caret ends somewhere in the editor UI (#11839).
                var wasActive = needsFocusHack && this.equals(CKEDITOR.document.getActive());

                // Holder rectange size is stretched by textarea,
                // so hide it just for a moment.
                this.hide();
                this.setStyle('height', this.getParent().$.clientHeight + 'px');
                this.setStyle('width', this.getParent().$.clientWidth + 'px');
                // When we have proper holder size, show textarea again.
                this.show();

                if (wasActive)
                    this.focus();
            }
        }
    });

    var sourceEditable = CKEDITOR.tools.createClass({
        base: CKEDITOR.editable,
        proto: {
            setData: function(data) {
                this.setValue(data);
                this.status = 'ready';
                this.editor.fire('dataReady');
            },

            getData: function() {
                return this.getValue();
            },

            // Insertions are not supported in source editable.
            insertHtml: function() {},
            insertElement: function() {},
            insertText: function() {},

            // Read-only support for textarea.
            setReadOnly: function(isReadOnly) {
                this[(isReadOnly ? 'set' : 'remove') + 'Attribute']('readOnly', 'readonly');
            },

            detach: function() {
                var editor = this.editor;

                window["codemirror_" + editor.id].toTextArea(); // Remove codemirror and restore Data to origin textarea
                window["codemirror_" + editor.id] = null; // Free Memory on destroy

                var markdownSource = editor.getData();
                editor.setData(marked(markdownSource, {langPrefix: 'language-'}));

                sourceEditable.baseProto.detach.call(this);

                this.clearCustomData();
                this.remove();
            }
        }
    });
})();
CKEDITOR.plugins.markdown = {
    commands: {
        markdown: {
            modes: {
                wysiwyg: 1,
                markdown: 1
            },
            editorFocus: false,
            readOnly: 1,
            exec: function(editor) {
                if (editor.mode == 'wysiwyg')
                    editor.fire('saveSnapshot');
                editor.getCommand('markdown').setState(CKEDITOR.TRISTATE_DISABLED);
                editor.setMode(editor.mode == 'markdown' ? 'wysiwyg' : 'markdown');
            },
            canUndo: false
        }
    }
};


text:
.PHONY: build configure doc install linecount nodefault pinstall lib_clean relib fast test_c test lib_doc lib_doc_clean user_doc_html user_doc_pdf user_docs

include config.mk
-include custom.mk

ifdef CI
CABALFLAGS += -f CI
endif

install:
	$(CABAL) install $(CABALFLAGS)

pinstall: CABALFLAGS += --enable-executable-profiling
pinstall: dist/setup-config
	$(CABAL) install $(CABALFLAGS)

build: dist/setup-config
	$(CABAL) build $(CABALFLAGS)

test: doc test_c

test_c:
	$(MAKE) -C test IDRIS=../dist/build/idris/idris test

test_js:
	$(MAKE) -C test IDRIS=../dist/build/idris/idris test_js

test_timed:
	$(MAKE) -C test IDRIS=../dist/build/idris/idris time

lib_clean:
	$(MAKE) -C libs IDRIS=../../dist/build/idris/idris RTS=../../dist/build/rts/libidris_rts clean

relib: lib_clean
	$(CABAL) install $(CABALFLAGS)

linecount:
	wc -l src/Idris/*.hs src/Idris/Elab/*.hs src/Idris/Core/*.hs src/IRTS/*.hs src/Pkg/*.hs src/Util/*.hs

#Note: this doesn't yet link to Hackage properly
doc: dist/setup-config
	$(CABAL) haddock --hyperlink-source --html --hoogle --html-location="http://hackage.haskell.org/packages/archive/\$$pkg/latest/doc/html" --haddock-options="--title Idris"

lib_doc:
	$(MAKE) -C libs IDRIS=../../dist/build/idris/idris doc

lib_doc_clean:
	$(MAKE) -C libs IDRIS=../../dist/build/idris/idris doc_clean

user_docs: user_doc_html user_doc_pdf

user_doc_clean:
	$(MAKE) -C docs clean

user_doc_html:
	$(MAKE) -C docs html

user_doc_pdf:
	$(MAKE) -C docs latexpdf

fast:
	$(CABAL) install $(CABALFLAGS) --ghc-option=-O0

dist/setup-config:
	$(CABAL) configure $(CABALFLAGS)


text:
#include "condor_common.h"
#include <math.h>
#include "jobqueuecollection.h"
#include "get_daemon_name.h"
#include "condor_config.h"
#include "misc_utils.h"
#include "jobqueuedatabase.h"
#include "condor_ttdb.h"
#include "jobqueuedbmanager.h"
#include "dbms_utils.h"

//! constructor
JobQueueCollection::JobQueueCollection(int iBucketNum)
{
	int i;
	char *tmp;

	_iBucketSize = iBucketNum;
	typedef ClassAdBucket* ClassAdBucketPtr;
	_ppProcAdBucketList = new ClassAdBucketPtr[_iBucketSize];
	_ppClusterAdBucketList = new ClassAdBucketPtr[_iBucketSize];
	for (i = 0; i < _iBucketSize; i++) {
		_ppProcAdBucketList[i] = NULL;
		_ppClusterAdBucketList[i] = NULL;
	}

	procAdNum = clusterAdNum = 0;
	curClusterAdIterateIndex = 0;
	curProcAdIterateIndex = 0;

	m_pCurBucket = NULL;
	bChained = false;

	tmp = param( "SCHEDD_NAME" );
	if( tmp ) {
		scheddname = build_valid_daemon_name( tmp );
		free(tmp);
	} else {
		scheddname = default_daemon_name();
	}

	DBObj = NULL;
	dt = T_PGSQL;
}

//! destructor
JobQueueCollection::~JobQueueCollection()
{
	int i;

	ClassAdBucket *pCurBucket;
	ClassAdBucket *pPreBucket;
	for (i = 0; i < _iBucketSize; i++) {
		pCurBucket = _ppProcAdBucketList[i];
		while (pCurBucket != NULL) {
			pPreBucket = pCurBucket;
			pCurBucket = pCurBucket->pNext;
			delete pPreBucket;
		}

		pCurBucket = _ppClusterAdBucketList[i];
		while (pCurBucket != NULL) {
			pPreBucket = pCurBucket;
			pCurBucket = pCurBucket->pNext;
			delete pPreBucket;
		}
	}

	delete[] _ppClusterAdBucketList;
	delete[] _ppProcAdBucketList;
	delete[] scheddname;
}

void JobQueueCollection::setDBObj(JobQueueDatabase *_DBObj)
{
	this->DBObj = _DBObj;
}

void JobQueueCollection::setDBtype(dbtype _dt)
{
	this->dt = _dt;
}

//! find a ProcAd
/*! \param cid Cluster Id
 *  \param pid Proc Id
 *  \return Proc ClassAd
 */
ClassAd*
JobQueueCollection::findProcAd(char* cid, char* pid)
{
	return find(cid, pid);
}

//! find a ClusterAd
/*! \param cid Cluster Id
 *  \return Cluster ClassAd
 */
ClassAd*
JobQueueCollection::findClusterAd(char* cid)
{
	return find(cid);
}

//! find a ClassAd - if pid == NULL return ProcAd, else return ClusterAd
/*! \param cid Cluster Id
 *  \param pid Proc Id (default is NULL)
 *  \return Cluster or Proc Ad
 */
ClassAd*
JobQueueCollection::find(char* cid, char* pid)
{
	int cid_len, pid_len;
	char* id = NULL;
	int	ad_type;
	int index;
	int len;

	cid_len = pid_len = 0;

	if (pid == NULL) { // need to find ClusterAd
		ad_type = ClassAdBucket::CLUSTER_AD;
		index = hashfunction(cid); // hash function invoked
		cid_len = strlen(cid);
	}
	else { // need to find ProcAd
		ad_type = ClassAdBucket::PROC_AD;
		cid_len = strlen(cid);
		pid_len = strlen(pid);
		len = cid_len + pid_len + 2;
		id = (char*)malloc(len * sizeof(char));
		snprintf(id, len, "%s%s", pid,cid);
		index = hashfunction(id); // hash function invoked
		free(id);
	}

	// find a bucket with a index
	ClassAdBucket *pCurBucket;
	if (ad_type == ClassAdBucket::CLUSTER_AD)
		pCurBucket = _ppClusterAdBucketList[index];
	else
		pCurBucket = _ppProcAdBucketList[index];

	// find ClassAd
	// if there is a chain, follow it
	while(pCurBucket != NULL)
	{
		if (
			((ad_type == ClassAdBucket::CLUSTER_AD) &&
		    (strcmp(cid, pCurBucket->cid) == 0))
			||
			((ad_type == ClassAdBucket::PROC_AD) &&
		     (strcmp(cid, pCurBucket->cid) == 0) &&
		     (strcmp(pid, pCurBucket->pid) == 0))
		   )
		{
			return pCurBucket->ad;
		}
		else {
			pCurBucket = pCurBucket->pNext;
		}
	}

	return NULL;
}

//! insert a ProcAd
/*! \param cid Cluster Id
 *  \param pid Proc Id
 *  \parm procAd ProcAd to be inserted
 *  \return the result status of insert
 */
int
JobQueueCollection::insertProcAd(char* cid, char* pid, ClassAd* procAd)
{
	int st;
	int len = strlen(cid) + strlen(pid) + 2;
	char* id = (char*)malloc(len * sizeof(char));

	ClassAdBucket *pBucket = new ClassAdBucket(cid, pid, procAd);

	snprintf(id, len, "%s%s",pid,cid);
	st = insert(id, pBucket, _ppProcAdBucketList);
	if (st > 0) {
		++procAdNum;
	}

	free(id); // id is just used for hashing purpose,
			  // so it must be freed here.
	return st;
}

//! insert a ClusterAd
/*! \param cid Cluster Id
 *  \parm clusetrAd ClusterAd to be inserted
 *  \return the result status of insert
 */
int
JobQueueCollection::insertClusterAd(char* cid, ClassAd* clusterAd)
{
	int st;
	ClassAdBucket *pBucket = new ClassAdBucket(cid, clusterAd);
	st = insert(cid, pBucket, _ppClusterAdBucketList);
	if (st > 0) {
		++clusterAdNum;
	}

	return st;
}

/*! insert a ClassAd into a hash table
 *  \param id Id
 *	\param pBucket bucket to be inserted
 *	\param ppBucketList Bucket List which this bucket is inserted into
 *  \return the result status of insert
			1: sucess
			0: duplicate
			-1: error
*/
int
JobQueueCollection::insert(char* id, ClassAdBucket* pBucket, ClassAdBucket **ppBucketList)
{
	// hash function invoke

	int index = hashfunction(id);

	// find and delete in a bucket list
	ClassAdBucket *pCurBucket = ppBucketList[index];

	if (pCurBucket == NULL) {
		ppBucketList[index] = pBucket;
		return 1;
	}

	while(1)
	{
		// duplicate check
		if (pCurBucket->pid == NULL && pBucket->pid == NULL) {
			if (strcasecmp(pCurBucket->cid, pBucket->cid) == 0) {
					return 0;
			}
		}
		else if (pCurBucket->pid != NULL && pBucket->pid != NULL) {
			if ((strcasecmp(pCurBucket->cid, pBucket->cid) == 0) &&
				(strcasecmp(pCurBucket->pid, pBucket->pid) == 0)) {
					return 0;
			}
		}

		if (pCurBucket->pNext == NULL) {
			pCurBucket->pNext = pBucket;
			return 1;
		}
		else {
			pCurBucket = pCurBucket->pNext;
		}
	}

	return -1;
}

//! delete a ProcAd
/*! \param cid Cluster Id
 *  \param pid Proc Id
 */
int
JobQueueCollection::removeProcAd(char* cid, char* pid)
{
	return remove(cid, pid);
}

//! delete a ClusterAd
/*! \param cid Cluster Id
 */
int
JobQueueCollection::removeClusterAd(char* cid)
{
	return remove(cid);
}

//! delete a ClassAd from a collection
/*! \param cid Cluter Id
 *  \parma pid Proc Id
 *  \return the result status of deletion
 *			1: sucess
 *			0: not found
 *			-1: other errors
 */
int
JobQueueCollection::remove(char* cid, char* pid)
{
	int 	cid_len, pid_len, ad_type, index;
	char* 	id = NULL;
	int i;
	int len;

	cid_len = pid_len = 0;

	if (pid == NULL) { // need to delete a ClusterAd
		ad_type = ClassAdBucket::CLUSTER_AD;
		index = hashfunction(cid); // hash function invoked
		cid_len = strlen(cid);
	}
	else { // need to delete a ProcAd
		ad_type = ClassAdBucket::PROC_AD;
		cid_len = strlen(cid);
		pid_len = strlen(pid);
		len = cid_len + pid_len + 2;
		id = (char*)malloc(len * sizeof(char));
		snprintf(id, len, "%s%s", pid, cid);
		index = hashfunction(id); // hash function invoked
		free(id);
	}

	// find and delete in a bucket list
	ClassAdBucket *pPreBucket;
	ClassAdBucket *pCurBucket;
	ClassAdBucket **ppBucketList;
	if (ad_type == ClassAdBucket::CLUSTER_AD) {
		pPreBucket = pCurBucket = _ppClusterAdBucketList[index];
		ppBucketList = _ppClusterAdBucketList;
	}
	else {
		pPreBucket = pCurBucket = _ppProcAdBucketList[index];
		ppBucketList = _ppProcAdBucketList;
	}

	for (i = 0; pCurBucket != NULL; i++)
	{
		if (((ad_type == ClassAdBucket::CLUSTER_AD) &&
		    (strcmp(cid, pCurBucket->cid) == 0))
			||
			((ad_type == ClassAdBucket::PROC_AD) &&
		     (strcmp(cid, pCurBucket->cid) == 0) &&
		     (strcmp(pid, pCurBucket->pid) == 0)))
		{
			if (i == 0) {
				ppBucketList[index] = pCurBucket->pNext;
			}
			else {
				pPreBucket->pNext = pCurBucket->pNext;
			}

			delete pCurBucket;
			return 1;
		}
		else {
			pPreBucket = pCurBucket;
			pCurBucket = pCurBucket->pNext;
		}
	}

	return 0;
}

//! hashing function
/*! \return hash value
 */
int
JobQueueCollection::hashfunction(char* str)
{
	int 			str_len = strlen(str);
	int 			i;
	char 			first_char = '.';
	unsigned long 	hash_val = 0;

	for (i = 0; i < str_len; i++) {
		hash_val += (long)(((int)str[i] - (int)first_char) * 6907);
	}

	return (int)(hash_val % _iBucketSize);
}

//! initialize all job ads iteration
void
JobQueueCollection::initAllJobAdsIteration()
{
	curProcAdIterateIndex = 0; // that of ProcAd List
	curClusterAdIterateIndex = 0; // that of ClusterAd List
	m_pCurBucket = NULL;
	bChained = false;
}

// load the next cluster ad
bool JobQueueCollection::loadNextClusterAd(QuillErrCode &errStatus)
{
	return loadNextAd(curClusterAdIterateIndex, _ppClusterAdBucketList,
					  errStatus);
}

// load the next ProcAd
bool JobQueueCollection::loadNextProcAd(QuillErrCode &errStatus)
{
	return loadNextAd(curProcAdIterateIndex, _ppProcAdBucketList,
					  errStatus);
}

bool
JobQueueCollection::loadNextAd(int& index,
							   ClassAdBucket **ppBucketList,
							   QuillErrCode &errStatus)
{
  // index is greater than the last index of bucket list?
  // we cant call it quits if there's another chained ad after this
  // and its the last bucket -- ameet
	if (index == _iBucketSize && !bChained) {
		return FALSE;
	}

	if (bChained == false) {
		m_pCurBucket = ppBucketList[index++];

		while (m_pCurBucket == NULL) {
			if (index == _iBucketSize) {
				return FALSE;
			}
			m_pCurBucket = ppBucketList[index++];
		}
	}
	else { // we are following the chained buckets
		m_pCurBucket = m_pCurBucket->pNext;
	}
		// is there a chaned bucket?
	if (m_pCurBucket->pNext != NULL) {
		bChained = true;
	}
	else {
		bChained = false;
	}

	// load this class ad
	errStatus = loadAd(m_pCurBucket->cid,
					   m_pCurBucket->pid,
					   m_pCurBucket->ad);

	return TRUE;
}

QuillErrCode
JobQueueCollection::loadAd(char* cid,
						   char* pid,
						   ClassAd* ad)
{
	MyString sql_str;
	ExprTree*	expr;		// For Each Attribute in ClassAd
	const char *name = NULL;
	MyString value;
	int len;
	MyString attNameList;
	MyString attValList;
	MyString tmpVal;
	MyString newvalue;
	MyString ts_expr;
	int hor_bndcnt = 0;
	const char* longstr_arr[2];
	QuillAttrDataType typ_arr[2];
	MyString longmystr_arr[2];
	QuillAttrDataType attr_type;

		// first generate the key columns
	if (pid != NULL) {
		attNameList.sprintf("(scheddname, cluster_id, proc_id");
		attValList.sprintf("('%s', %s, %s", scheddname, cid, pid);
	} else {
		attNameList.sprintf("(scheddname, cluster_id");
		attValList.sprintf("('%s', %s", scheddname, cid);
	}

	ad->ResetExpr(); // for iteration initialization

	while(ad->NextExpr(name, expr)) {
		value = ExprTreeToString(expr);

			// procad
		if (pid != NULL) {
			if (isHorizontalProcAttribute(name, attr_type)) {
				attNameList += ", ";
				attNameList += name;

				attValList += ", ";

				switch (attr_type) {
				case CONDOR_TT_TYPE_CLOB:
						// strip double quotes
					if (!stripdoublequotes_MyString(value)) {
						dprintf(D_ALWAYS, "ERROR: string constant not double quoted for attribute %s in JobQueueCollection::loadAd\n", name);
					}

					newvalue = condor_ttdb_fillEscapeCharacters(value.Value(), dt);
					tmpVal.sprintf("'%s'", newvalue.Value());

					break;
				case CONDOR_TT_TYPE_STRING:
						// strip double quotes
					if (!stripdoublequotes_MyString(value)) {
						dprintf(D_ALWAYS, "ERROR: string constant not double quoted for attribute %s in JobQueueCollection::loadAd\n", name);
					}

					newvalue = condor_ttdb_fillEscapeCharacters(value.Value(), dt);
					tmpVal.sprintf("'%s'", newvalue.Value());
					break;
				case CONDOR_TT_TYPE_NUMBER:
					tmpVal.sprintf("%s", value.Value());
					break;
				case CONDOR_TT_TYPE_TIMESTAMP:
					time_t clock;
					clock = atoi(value.Value());

					ts_expr = condor_ttdb_buildts(&clock, dt);

					if (ts_expr.IsEmpty()) {
						dprintf(D_ALWAYS, "ERROR: Timestamp expression not builtin JobQueueCollection::loadAd\n");
						return QUILL_FAILURE;
					}

					tmpVal.sprintf("%s", ts_expr.Value());

						/* the converted timestamp value is longer, so realloc
						   the buffer for attValList
						*/

					break;
				default:
					dprintf(D_ALWAYS, "loadAd: unsupported horizontal proc ad attribute\n");

					return QUILL_FAILURE;
				}
				attValList += tmpVal;
			} else {
					// this is a vertical attribute
				newvalue = condor_ttdb_fillEscapeCharacters(value.Value(), dt);
				len = 1024 + strlen(name) + strlen(scheddname) +
					newvalue.Length() + strlen(cid) + strlen(pid);

				{
					sql_str.sprintf("INSERT INTO ProcAds_Vertical VALUES('%s', %s, %s, '%s', '%s')", scheddname,cid, pid, name, newvalue.Value());

					if (DBObj->execCommand(sql_str.Value()) == QUILL_FAILURE) {
                        dprintf(D_ALWAYS, "JobQueueCollection::loadAd - ERROR [SQL] %s\n", sql_str.Value());
                        return QUILL_FAILURE;
					}
				}
			}
		} else {  // cluster ad
			if (isHorizontalClusterAttribute(name, attr_type)) {
				attNameList += ", ";
				attNameList += name;

				attValList += ", ";

				switch (attr_type) {
				case CONDOR_TT_TYPE_CLOB:
						// strip double quotes
					if (!stripdoublequotes_MyString(value)) {
						dprintf(D_ALWAYS, "ERROR: string constant not double quoted for attribute %s in JobQueueCollection::loadAd\n", name);
					}

					newvalue = condor_ttdb_fillEscapeCharacters(value.Value(), dt);
					tmpVal.sprintf("'%s'", newvalue.Value());

					break;
				case CONDOR_TT_TYPE_STRING:
						// strip double quotes
					if (!stripdoublequotes_MyString(value)) {
						dprintf(D_ALWAYS, "ERROR: string constant not double quoted for attribute %s in JobQueueCollection::loadAd\n", name);
					}

					newvalue = condor_ttdb_fillEscapeCharacters(value.Value(), dt);
					tmpVal.sprintf("'%s'", newvalue.Value());
					break;
				case CONDOR_TT_TYPE_NUMBER:
					tmpVal.sprintf("%s", value.Value());
					break;
				case CONDOR_TT_TYPE_TIMESTAMP:
					time_t clock;
					clock = atoi(value.Value());

					ts_expr = condor_ttdb_buildts(&clock, dt);

					if (ts_expr.IsEmpty()) {
						dprintf(D_ALWAYS, "ERROR: Timestamp expression not builtin JobQueueCollection::loadAd\n");
						return QUILL_FAILURE;
					}

					tmpVal.sprintf("%s", ts_expr.Value());

						/* the converted timestamp value is longer, so realloc
						   the buffer for attValList
						*/

					break;
				default:
					dprintf(D_ALWAYS, "loadAd: unsupported horizontal proc ad attribute\n");
					return QUILL_FAILURE;
				}
				attValList += tmpVal;
			} else {
					// this is a vertical attribute
				newvalue = condor_ttdb_fillEscapeCharacters(value.Value(), dt);
				len = 1024 + strlen(name) + strlen(scheddname) +
					newvalue.Length() + strlen(cid);

				{
					sql_str.sprintf("INSERT INTO ClusterAds_Vertical VALUES('%s', %s, '%s', '%s')", scheddname,cid, name, newvalue.Value());
					if (DBObj->execCommand(sql_str.Value()) == QUILL_FAILURE) {
                        dprintf(D_ALWAYS, "JobQueueCollection::loadAd - ERROR [SQL] %s\n", sql_str.Value());
                        return QUILL_FAILURE;
					}
				}
			}
		}
	}

	attNameList += ")";
    attValList += ")";

		// load the horizontal tuples

		// build the sql
	if (pid != NULL) {
			// procad
		sql_str.sprintf("INSERT INTO ProcAds_Horizontal %s VALUES %s", attNameList.Value(), attValList.Value());
	} else {
			// clusterad
		sql_str.sprintf("INSERT INTO ClusterAds_Horizontal %s VALUES %s", attNameList.Value(), attValList.Value());
	}

		// execute it
	if (hor_bndcnt == 0) {
		if (DBObj->execCommand(sql_str.Value()) == QUILL_FAILURE) {
			dprintf(D_ALWAYS, "JobQueueCollection::loadAd - ERROR [SQL] %s\n", sql_str.Value());
			return QUILL_FAILURE;
		}
	} else {
		if (DBObj->execCommandWithBind(sql_str.Value(), hor_bndcnt,
									   longstr_arr, typ_arr) == QUILL_FAILURE) {
			dprintf(D_ALWAYS, "JobQueueCollection::loadAd - ERROR [SQL] %s\n", sql_str.Value());
			return QUILL_FAILURE;
		}
	}

	return QUILL_SUCCESS;
}


text:
require 'tempfile'

class Resolver
  RESOLVER_DIR = Pathname("/etc/resolver")

  attr_reader :ip, :resolver_file, :amazeeio_cachalot_domain

  def initialize(ip, amazeeio_cachalot_domain = "docker.amazee.io")
    @ip = ip
    self.amazeeio_cachalot_domain = amazeeio_cachalot_domain
  end

  def amazeeio_cachalot_domain=(amazeeio_cachalot_domain)
    @amazeeio_cachalot_domain = amazeeio_cachalot_domain
    @resolver_file = RESOLVER_DIR.join(@amazeeio_cachalot_domain)
  end

  def up
    unless resolver_configured?
      configure_resolver!
    end
  end

  def name
    "DNS"
  end

  def clean?
    puts "Removing resolver file, this may require sudo"
    self.system!("removing resolverfile", "sudo", "rm", "-f", @resolver_file)
    system!("restarting mDNSResponder", "sudo", "killall", "mDNSResponder")
  end

  def configure_resolver!
    puts "setting up DNS resolution, this will require sudo"
    unless RESOLVER_DIR.directory?
      system!("creating #{RESOLVER_DIR}", "sudo", "mkdir", "-p", RESOLVER_DIR)
    end
    Tempfile.open('amazeeio_cachalot-dnsmasq') do |f|
      f.write(resolver_contents)
      f.close
      system!("creating #{@resolver_file}", "sudo", "cp", f.path, @resolver_file)
      system!("creating #{@resolver_file}", "sudo", "chmod", "644", @resolver_file)
    end
    system!("restarting mDNSResponder", "sudo", "killall", "mDNSResponder")
  end

  def resolver_configured?
    @resolver_file.exist? && File.read(@resolver_file) == resolver_contents
  end

  def system!(step, *args)
    system(*args.map(&:to_s)) || raise("Error with the #{name} daemon during #{step}")
  end

  def resolver_contents; <<-EOS.gsub(/^    /, '')
    # Generated by amazeeio_cachalot
    nameserver #{ip}
    port 53
    EOS
  end
end


text:
'use strict';

module.exports = {
  client: {
    lib: {
      css: [
        'public/lib/dcjs/dc.min.css',
        'public/lib/colorbrewer/colorbrewer.min.css',
        'public/lib/bootstrap/dist/css/bootstrap.min.css',
        'public/lib/bootstrap/dist/css/bootstrap-theme.min.css',
      ],
      js: [
        'public/lib/angular/angular.min.js',
        'public/lib/angular-resource/angular-resource.min.js',
        'public/lib/angular-animate/angular-animate.min.js',
        'public/lib/angular-messages/angular-messages.min.js',
        'public/lib/angular-ui-router/release/angular-ui-router.min.js',
        'public/lib/angular-ui-utils/ui-utils.min.js',
        'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js',
        'public/lib/angular-file-upload/angular-file-upload.min.js',
        'public/lib/d3/d3.min.js',
        'public/lib/crossfilter2/crossfilter.min.js',
        'public/lib/dcjs/dc.min.js',
        'public/lib/colorbrewer/colorbrewer.js',
        'public/lib/owasp-password-strength-test/owasp-password-strength-test.js'
      ]
    },
    css: 'public/dist/application.min.css',
    js: 'public/dist/application.min.js'
  }
};


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.6
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.09.20 at 04:07:50 PM CST
//

package org.shaolin.bmdp.datamodel.page;

import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for ComponentParamType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="ComponentParamType">
 *   <complexContent>
 *     <extension base="{http://bmdp.shaolin.org/datamodel/Page}DataParamType">
 *       <attribute name="componentPath" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ComponentParamType")
public class ComponentParamType
    extends DataParamType
    implements Serializable
{

    private final static long serialVersionUID = 1L;
    @XmlAttribute(name = "componentPath", required = true)
    protected String componentPath;

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

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

}


text:
@interface BaoXianViewController : CFBaseViewController

@end


text:
            {% capture page_path %}/{{page.path}}{% endcapture %}
            {% for feature_image in site.feature_image %}
                {% if feature_image.feature_image_url == page_path %}
                    {{ feature_image.output }}
                {% endif %}
            {% endfor %}


text:
package br.com.arbo.steamside.data.load;

import java.util.Optional;

import javax.inject.Inject;

import br.com.arbo.steamside.bootstrap.Bootstrap;
import br.com.arbo.steamside.cloud.CloudSettingsFactory.Missing;
import br.com.arbo.steamside.cloud.LoadCloud;
import br.com.arbo.steamside.cloud.LoadCloud.Disabled;
import br.com.arbo.steamside.cloud.Unavailable;
import br.com.arbo.steamside.data.InMemorySteamsideData;
import br.com.arbo.steamside.data.SteamsideData;
import br.com.arbo.steamside.firstrun.InitialLoadDetectedFirstRunEver;
import br.com.arbo.steamside.settings.file.LoadFile;

public class FromCloudAndFile implements InitialLoad
{

	@Override
	public SteamsideData loadSteamsideData()
	{
		Optional<SteamsideData> fromCloud = fromCloud();
		if (fromCloud.isPresent())
			return fromCloud.get();

		Optional<SteamsideData> fromFile = fromFile();
		if (fromFile.isPresent())
			return fromFile.get();

		bootstrap.fireEvent(new InitialLoadDetectedFirstRunEver());

		return InMemorySteamsideData.newInstance();
	}

	private Optional<SteamsideData> fromCloud()
	{
		try
		{
			return Optional.of(cloud.load().toSteamsideData());
			// TODO Success? Enqueue save to file
		}
		catch (Disabled e)
		{
			// Oh well, you know what you're doing, probably
			return Optional.empty();
		}
		catch (Unavailable e)
		{
			// TODO Send Warning to User Alert Bus: can't sync to the cloud
			e.printStackTrace();
			return Optional.empty();
		}
		catch (Missing e)
		{
			// TODO Send Suggestion to User Alert Bus: configure sync?
			e.printStackTrace();
			return Optional.empty();
		}
	}

	private Optional<SteamsideData> fromFile()
	{
		try
		{
			return Optional.of(file.load().toSteamsideData());
		}
		catch (br.com.arbo.steamside.settings.file.LoadFile.Missing e)
		{
			// TODO Notify the outside world. First time?
			e.printStackTrace();
			return Optional.empty();
		}
	}

	@Inject
	public FromCloudAndFile(
		LoadCloud cloud, LoadFile file, Bootstrap bootstrap)
	{
		this.cloud = cloud;
		this.file = file;
		this.bootstrap = bootstrap;
	}

	private final Bootstrap bootstrap;
	private final LoadCloud cloud;
	private final LoadFile file;
}


text:
package org.thingsboard.rule.engine.edge;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.thingsboard.rule.engine.api.RuleNode;
import org.thingsboard.rule.engine.api.TbContext;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.edge.EdgeEventActionType;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.plugin.ComponentType;
import org.thingsboard.server.common.data.rule.RuleChainType;
import org.thingsboard.server.common.msg.TbMsg;

import java.util.UUID;

@Slf4j
@RuleNode(
        type = ComponentType.ACTION,
        name = "push to cloud",
        configClazz = TbMsgPushToCloudNodeConfiguration.class,
        nodeDescription = "Pushes messages from edge to cloud",
        nodeDetails = "Push messages from edge to cloud. " +
                "This node used only on edge to push messages from edge to cloud. " +
                "Once message arrived into this node it's going to be converted into cloud event and saved to the local database. " +
                "Node doesn't push messages directly to cloud, but stores event(s) in the cloud queue. " +
                "
Supports next originator types:" +
                "
DEVICE" +
                "
ASSET" +
                "
ENTITY_VIEW" +
                "
DASHBOARD" +
                "
TENANT" +
                "
CUSTOMER" +
                "
EDGE

" +
                "As well node supports next message types:" +
                "
POST_TELEMETRY_REQUEST" +
                "
POST_ATTRIBUTES_REQUEST" +
                "
ATTRIBUTES_UPDATED" +
                "
ATTRIBUTES_DELETED" +
                "
ALARM

" +
                "Message will be routed via Failure route if node was not able to save cloud event to database or unsupported originator type/message type arrived. " +
                "In case successful storage cloud event to database message will be routed via Success route.",
        uiResources = {"static/rulenode/rulenode-core-config.js"},
        configDirective = "tbActionNodePushToCloudConfig",
        icon = "cloud_upload",
        ruleChainTypes = RuleChainType.EDGE
)
public class TbMsgPushToCloudNode extends AbstractTbMsgPushNode<TbMsgPushToCloudNodeConfiguration, Object, Object> {

    // Implementation of this node is done on the Edge

    @Override
    Object buildEvent(TenantId tenantId, EdgeEventActionType eventAction, UUID entityId, Object eventType, JsonNode entityBody) {
        return null;
    }

    @Override
    Object getEventTypeByEntityType(EntityType entityType) {
        return null;
    }

    @Override
    Object getAlarmEventType() {
        return null;
    }

    @Override
    String getIgnoredMessageSource() {
        return null;
    }

    @Override
    protected Class<TbMsgPushToCloudNodeConfiguration> getConfigClazz() {
        return TbMsgPushToCloudNodeConfiguration.class;
    }

    @Override
    void processMsg(TbContext ctx, TbMsg msg) {
    }

}


text:
package ru.spbstu.icc.kspt.kuznetsov.codestore.entities;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Submission implements Serializable{
	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue
	private Long id;

	private String submissionName;
	private String localPath;

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getSubmissionName() {
		return submissionName;
	}

	public void setSubmissionName(String submissionName) {
		this.submissionName = submissionName;
	}

	public String getLocalPath() {
		return localPath;
	}

	public void setLocalPath(String localPath) {
		this.localPath = localPath;
	}
}


text:
"""
Examples to show usage of the azure-core-tracing-opentelemetry
with the eventhub checkpoint storage blob SDK and exporting to
Azure monitor backend. This example traces calls for sending
checkpoints via the checkpoint storage blob sdk. The telemetry
will be collected automatically and sent to Application Insights
via the AzureMonitorTraceExporter
"""

import os

# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs
from azure.core.settings import settings
from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan

settings.tracing_implementation = OpenTelemetrySpan

# Regular open telemetry usage from here, see https://github.com/open-telemetry/opentelemetry-python
# for details
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor

trace.set_tracer_provider(TracerProvider())
tracer = trace.get_tracer(__name__)

# azure monitor trace exporter to send telemetry to appinsights
from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter
span_processor = BatchSpanProcessor(
    AzureMonitorTraceExporter.from_connection_string(
        os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
    )
)
trace.get_tracer_provider().add_span_processor(span_processor)

# Example with EventHub SDKs
from azure.eventhub import EventHubConsumerClient
from azure.eventhub.extensions.checkpointstoreblob import BlobCheckpointStore

CONNECTION_STR = os.environ["EVENT_HUB_CONN_STR"]
EVENTHUB_NAME = os.environ['EVENT_HUB_NAME']
STORAGE_CONNECTION_STR = os.environ["AZURE_STORAGE_CONN_STR"]
BLOB_CONTAINER_NAME = "your-blob-container-name"  # Please make sure the blob container resource exists.

def on_event(partition_context, event):
    # Put your code here.
    # Avoid time-consuming operations.
    print(event)
    partition_context.update_checkpoint(event)

checkpoint_store = BlobCheckpointStore.from_connection_string(
    STORAGE_CONNECTION_STR,
    container_name=BLOB_CONTAINER_NAME,
)
client = EventHubConsumerClient.from_connection_string(
    CONNECTION_STR,
    consumer_group='$Default',
    eventhub_name=EVENTHUB_NAME,
    checkpoint_store=checkpoint_store
)

with tracer.start_as_current_span(name="MyEventHub"):
    try:
        client.receive(on_event)
    except KeyboardInterrupt:
        client.close()


text:
State-of-the art async REST APIs for [django tastypie](https://github.com/django-tastypie/django-tastypie).

tastypie-async follows the [recommended practice](http://restful-api-design.readthedocs.io/en/latest/methods.html#asynchronous-requests) for async REST APIs, which is to return 202 CREATED on task submission, and issue a 303 SEE OTHER on status requests when the result is available.

### Hello world

In good tastypie tradition, API implementation is [straight forward](https://github.com/miraculixx/tastypie-async/blob/master/examples/double/api.py):

```python
from tpasync.resources import AsyncResourceMixin
import myapp.tasks as tasks

# resources.py
# -- define the resource
class DoubleResource(AsyncResourceMixin, Resource):
    def async_get_list(self, request, **kwargs):
        number = request.GET['foo']
        return tasks.double.delay(foo)

    class Meta:
        resource_name = 'double'
```

Adding the API to your Django app is the same as with any tastypie API:

```python
# -- register
api = Api(api_name='v1')
api.register(DoubleResouce())

# urls.py
urlpatterns += [
    r('^api/', include(api.urls),
]
```

The above example provides the `/api/v1/double/` URL supporting async `GET` requests:

```
# submits the celery task and returns a state location
GET /api/v1/foo/?foo=1
Status: 202 ACCEPTED
Location:/api/v1/double/state/30049f59-b619-4890-a1eb-d53b245797d1/
````

### Getting results

1.  query the state to get updates

    ```
    GET /api/v1/double/state/30049f59-b619-4890-a1eb-d53b245797d1/
    Status: 200 OK
    {
       "id":"7fbd961a-75d8-4aae-bd41-64296de661fa",
       "resource_uri":"/api/v1/double/state/7fbd961a-75d8-4aae-bd41-64296de661fa/",
       "state":"PENDING"
    }
    ```

2. when the result is ready it will be notified in the state response

    ```
    GET /api/v1/double/state/30049f59-b619-4890-a1eb-d53b245797d1/
    Status: 200 OK
    {
       "id":"394daac4-3daa-4a0f-87b8-f9e2c8c73749",
       "resource_uri":"/api/v1/double/state/394daac4-3daa-4a0f-87b8-f9e2c8c73749/",
       "result_uri":"/api/v1/double/result/394daac4-3daa-4a0f-87b8-f9e2c8c73749/",
       "state":"SUCCESS"
    }
    ```

3. get results. this returns whatever result was provided by the celery task, serialized by tastypie as usual:

    ```
    GET http://localhost:8001/api/v1/double/result/394daac4-3daa-4a0f-87b8-f9e2c8c73749/
    Status: 200 OK
    {
     "result": 2
    }
    ```

4. cancel tasks. you may also choose to cancel a task

    ```
    DELETE http://localhost:8001/api/v1/double/state/7fbd961a-75d8-4aae-bd41-64296de661fa/
    Status: 410 Gone
    ```

### Implementing operations

tastypie-async supports the usual tastypie operations, `GET/PUT/POST/DELETE` for list and detail. To implement override the respective `async_<method>` operation:

* `GET /` => `async_get_list`
* `GET /<pk>/` => `async_get_detail`
* `POST /` => `async_post_list`
* `POST /<pk>/` => `async_post_detail`
* `PUT /` => `async_put_list`
* `PUT /<pk>/` => `async_put_detail`
* `DELETE /` => `async_delete_list`
* `DELETE /<pk>/` => `async_delete_detail`
* `PATCH /` => `async_patch_list`
* `PATCH /<pk>/` => `async_patch_detail`

Implementation of any of these methods is straight forward, just return the `AsyncResult` returned by the celery task:

```
def async_get_list(request, **kwargs):
    return myapp.tasks.double.delay(requests.GET.get('foo'))
```

Task implementation is the same as with any other Celery task:

```python
# tasks.py
def double(number):
   return number * 2
```

Note that it is the responsibility of the task to execute actions that correspond to the API method called,
tastypie-async is only the broker between the API call and Celery.

### Installation

Just add `tpasync` to `INSTALLED_APPS`:

```python
# settings.py

INSTALLED_APPS = (
    ...
    'tastypie',
    'tpasync',
    ...
)
```

### Why not use the Celery REST API?

tastypie-async uses Celery as the execution engine. Any AsyncResource submits tasks to Celery
the same way any Celery task is executed. While Celery provides a REST API itself,
[Celery webhooks](http://docs.celeryproject.org/en/latest/userguide/remote-tasks.html), it is less flexible than tastypie-async and has a few other drawbacks. For example, the tasks submitted via Celery need to be aware of their use as a REST API, which means they are hard to be reused outside of celery webhooks. In contrast, tasks used in a `AsyncResource`
remain unaware of their use as a REST API, seperation of concerns is thus maintained.

Also adding authentication, authorization and throttling  to an AsyncResource is straight forward -- it works
the same as with any tastypie Resource because the method dispatcher is the same.

### License

see the `LICENSE` file


text:
package com.linecorp.armeria.client.http;

import static java.util.Objects.requireNonNull;

import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;

import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.EmptyHttpHeaders;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;

/**
 * Creates a new {@link SimpleHttpRequest}.
 */
public class SimpleHttpRequestBuilder {

    private static final byte[] EMPTY = new byte[0];

    private final URI uri;
    private final HttpMethod method;
    private HttpHeaders headers = EmptyHttpHeaders.INSTANCE;
    private byte[] content = EMPTY;

    /**
     * Returns a {@link SimpleHttpRequestBuilder} for a GET request to the given URI,
     * for setting additional HTTP parameters as needed.
     */
    public static SimpleHttpRequestBuilder forGet(String uri) {
        return createRequestBuilder(uri, HttpMethod.GET);
    }

    /**
     * Returns a {@link SimpleHttpRequestBuilder} for a POST request to the given URI,
     * for setting additional HTTP parameters as needed.
     */
    public static SimpleHttpRequestBuilder forPost(String uri) {
        return createRequestBuilder(uri, HttpMethod.POST);
    }

    /**
     * Returns a {@link SimpleHttpRequestBuilder} for a PUT request to the given URI,
     * for setting additional HTTP parameters as needed.
     */
    public static SimpleHttpRequestBuilder forPut(String uri) {
        return createRequestBuilder(uri, HttpMethod.PUT);
    }

    /**
     * Returns a {@link SimpleHttpRequestBuilder} for a PATCH request to the given URI,
     * for setting additional HTTP parameters as needed.
     */
    public static SimpleHttpRequestBuilder forPatch(String uri) {
        return createRequestBuilder(uri, HttpMethod.PATCH);
    }

    /**
     * Returns a {@link SimpleHttpRequestBuilder} for a DELETE request to the given URI,
     * for setting additional HTTP parameters as needed.
     */
    public static SimpleHttpRequestBuilder forDelete(String uri) {
        return createRequestBuilder(uri, HttpMethod.DELETE);
    }

    /**
     * Returns a {@link SimpleHttpRequestBuilder} for a HEAD request to the given URI,
     * for setting additional HTTP parameters as needed.
     */
    public static SimpleHttpRequestBuilder forHead(String uri) {
        return createRequestBuilder(uri, HttpMethod.HEAD);
    }

    /**
     * Returns a {@link SimpleHttpRequestBuilder} for an OPTIONS request to the given URI,
     * for setting additional HTTP parameters as needed.
     */
    public static SimpleHttpRequestBuilder forOptions(String uri) {
        return createRequestBuilder(uri, HttpMethod.OPTIONS);
    }

    private static SimpleHttpRequestBuilder createRequestBuilder(String uri, HttpMethod method) {
        requireNonNull(uri);
        try {
            return new SimpleHttpRequestBuilder(new URI(uri), method);
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException("invalid uri: " + uri, e);
        }
    }

    private SimpleHttpRequestBuilder(URI uri, HttpMethod method) {
        this.uri = uri;
        this.method = method;
    }

    /**
     * Adds a new header with the specified {@code name} and {@code value}.
     */
    public SimpleHttpRequestBuilder header(CharSequence name, Object value) {
        headers().add(requireNonNull(name, "name"), requireNonNull(value, "value"));
        return this;
    }

    /**
     * Adds all header entries in the specified {@code headers}.
     */
    public SimpleHttpRequestBuilder headers(HttpHeaders headers) {
        headers().add(requireNonNull(headers));
        return this;
    }

    private HttpHeaders headers() {
        if (headers == EmptyHttpHeaders.INSTANCE) {
            headers = new DefaultHttpHeaders();
        }
        return headers;
    }

    /**
     * Sets the given bytes to be used as the request content.
     */
    public SimpleHttpRequestBuilder content(byte[] bytes) {
        this.content = bytes;
        return this;
    }

    /**
     * Sets the given string to be used as the request content, decoding to bytes with the
     * given charset.
     */
    public SimpleHttpRequestBuilder content(String chars, Charset charset) {
        return content(chars.getBytes(charset));
    }

    /**
     * Creates a new {@link SimpleHttpRequest}.
     */
    public SimpleHttpRequest build() {
        return new SimpleHttpRequest(uri, method, headers, content);
    }

    @Override
    public String toString() {
        return SimpleHttpRequest.toString(uri, method, headers, content);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>tech.zool</groupId>
    <artifactId>DevDemos</artifactId>
    <version>0.1-SNAPSHOT</version>
  </parent>
  <artifactId>script-samples</artifactId>
  <packaging>jar</packaging>
  <name>Run Script samples</name>

  <dependencies>
    <dependency>
      <groupId>org.python</groupId>
      <artifactId>jython-standalone</artifactId>
      <version>2.7.1</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
    </dependency>
  </dependencies>
</project>


text:
Ext.provide('Phlexible.metasets.SelectConfigurationWindow');

Phlexible.metasets.SelectConfigurationWindow = Ext.extend(Ext.Window, {
    title: Phlexible.metasets.Strings.configure_select,
    strings: Phlexible.metasets.Strings,
    width: 300,
    height: 400,
    layout: 'fit',
    modal: true,

    initComponent: function() {
        var actions = new Ext.ux.grid.RowActions({
            header: this.strings.actions,
            width: 40,
            actions: [
                {
                    iconCls: 'p-metaset-delete-icon',
                    tooltip: this.strings.remove_value,
                    callback: this.deleteValue,
                    scope: this
                }
            ]
        });

        var values = [];
        if (this.options) {
            Ext.each(this.options.split(','), function(value) {
                values.push([value]);
            });
        }

        this.items = [{
            xtype: 'editorgrid',
            border: false,
            autoExpandColumn: 'value',
            viewConfig: {
                deferEmptyText: false,
                emptyText: this.strings.use_add,
                stripeRows: true
            },
            store: new Ext.data.SimpleStore({
                fields: ['value'],
                data: values
            }),
            columns: [{
                id: 'value',
                header: this.strings.value,
                dataIndex: 'value',
                editor: new Ext.form.TextField()
            },
                actions
            ],
            plugins: [actions],
            tbar: [{
                text: this.strings.add_value,
                iconCls: 'p-metaset-add-icon',
                handler: this.addValue,
                scope: this
            }]
        }];

        this.buttons = [{
            text: this.strings.cancel,
            handler: function() {
                this.close();
            },
            scope: this
        },{
            text: this.strings.store,
            handler: function() {
                var options = [],
                    records = this.getComponent(0).getStore().getRange();
                if (!records.length) {
                    Ext.MessageBox.alert(this.strings.failure, this.strings.add_at_least_one_value);
                    return;
                }
                Ext.each(records, function(r) {
                    options.push(r.get('value'));
                });
                this.fireEvent('store', options.join(','));
                this.close();
            },
            scope: this
        }];

        Phlexible.metasets.SelectConfigurationWindow.superclass.initComponent.call(this);
    },

    addValue: function() {
        this.getComponent(0).getStore().add(new Ext.data.Record({value: Ext.id(null, 'value-')}));
    },

    deleteValue: function(grid, record) {
        grid.getStore().remove(record);
    }
});


text:
"""Test the leica helper functions."""
from pathlib import PureWindowsPath

from camacq.plugins.leica.helper import find_image_path, get_field, get_imgs, get_well

from tests.common import FIELD_PATH, IMAGE_PATH, WELL_PATH

def test_find_image_path():
    """Test find image path."""
    parts = IMAGE_PATH.parts
    root = parts[0]
    relpath = parts[1:]
    windows_path = PureWindowsPath("")
    relpath = windows_path.joinpath(*relpath)

    path = find_image_path(str(relpath), root)

    assert path == str(IMAGE_PATH)

def test_get_field():
    """Test get field."""
    path = get_field(IMAGE_PATH)

    assert path == str(IMAGE_PATH.parent)

def test_get_well():
    """Test get well."""
    path = get_well(IMAGE_PATH)

    assert path == str(WELL_PATH)

def test_get_imgs():
    """Test get imgs."""
    images = get_imgs(str(WELL_PATH), search="C31")

    assert len(images) == 6

    images = get_imgs(str(FIELD_PATH), search="C22")

    assert len(images) == 3


text:
zsh-comp-jhbuild
================

zsh completion for jhbuild
It is a zsh completion for jhbuild.
It is a work in progress and just for me:)


text:
/**
 * @fileoverview Defines the Timeout class.  The arm() method is equivalent to
 * window.setTimeout() and maybeDisarm() is equivalent to window.clearTimeout().
 *
 * @author rdionne@google.com (Robert Dionne)
 */

goog.provide('jstestdriver.plugins.async.Timeout');

goog.require('jstestdriver');

/**
 * Constructs a Timeout. Accepts alternate implementations of setTimeout and
 * clearTimeout.
 *
 * @param {Function} setTimeout The global setTimeout function to use.
 * @param {Function} clearTimeout The global clearTimeout function to use.
 * @constructor
 */
jstestdriver.plugins.async.Timeout = function(setTimeout, clearTimeout) {
  this.setTimeout_ = setTimeout;
  this.clearTimeout_ = clearTimeout;
  this.handle_ = null;
};

/**
 * Arms this Timeout to fire after the specified delay.
 *
 * @param {Function} callback The callback to call after the delay passes.
 * @param {number} delay The timeout delay in milliseconds.
 */
jstestdriver.plugins.async.Timeout.prototype.arm = function(callback, delay) {
  var self = this;
  this.handle_ = this.setTimeout_(function() {
    self.maybeDisarm();
    return callback.apply(null, arguments);
  }, delay);
};

/**
 * Explicitly disarms the timeout.
 * @private
 */
jstestdriver.plugins.async.Timeout.prototype.disarm_ = function() {
  this.clearTimeout_(this.handle_);
  this.handle_ = null;
};

/**
 * @return {boolean} True if the timeout is armed.
 */
jstestdriver.plugins.async.Timeout.prototype.isArmed = function() {
  return this.handle_ != null;
};

/**
 * Disarms the timeout if it is armed.
 */
jstestdriver.plugins.async.Timeout.prototype.maybeDisarm = function() {
  if (this.isArmed()) {
    this.disarm_();
  }
};


text: Given two lists in sorted order, find their intersection.


text:
using System;
using System.Net;
using RHttpServer.Logging;

namespace RHttpServer
{
    /// <summary>
    ///     Ease-of-use wrapper for request cookies
    /// </summary>
    public sealed class RCookies
    {
        internal RCookies(CookieCollection cocol)
        {
            _cookies = cocol;
        }

        internal RCookies()
        {
        }

        private readonly CookieCollection _cookies;

        /// <summary>
        ///     Returns the cookie with the given tag if any
        /// </summary>
        /// <param name="cookieId"></param>
        public Cookie this[string cookieId]
        {
            get
            {
                try
                {
                    return _cookies[cookieId];
                }
                catch (Exception ex)
                {
                    Logger.Log(ex);
                    return null;
                }
            }
        }
    }
}


text:
"""
Pet Shop Demo

This is an example of a pet shop service written with Python Flask
It demonstraits how a RESTful service should be implemented.

Paths
-----
GET  /pets - Retrieves a list of pets from the database
GET  /pets{id} - Retrirves a Pet with a specific id
POST /pets - Creates a Pet in the datbase from the posted database
PUT  /pets/{id} - Updates a Pet in the database fom the posted database
DELETE /pets{id} - Removes a Pet from the database that matches the id
"""

import os
import sys
import logging
from flask import Response, jsonify, request, json, url_for, make_response
from . import app
from models import Pet, DataValidationError

# Pull options from environment
DEBUG = (os.getenv('DEBUG', 'False') == 'True')
PORT = os.getenv('PORT', '5000')

# Status Codes
HTTP_200_OK = 200
HTTP_201_CREATED = 201
HTTP_204_NO_CONTENT = 204
HTTP_400_BAD_REQUEST = 400
HTTP_404_NOT_FOUND = 404
HTTP_409_CONFLICT = 409

######################################################################
# Error Handlers
######################################################################
@app.errorhandler(DataValidationError)
def request_validation_error(error):
    """ Handles all data validation issues from the model """
    return bad_request(error)

@app.errorhandler(400)
def bad_request(error):
    """ Handles requests that have bad or malformed data """
    return jsonify(status=400, error='Bad Request', message=error.message), 400

@app.errorhandler(404)
def not_found(error):
    """ Handles Pets that cannot be found """
    return jsonify(status=404, error='Not Found', message=error.message), 404

@app.errorhandler(405)
def method_not_supported(error):
    """ Handles bad method calls """
    return jsonify(status=405, error='Method not Allowed',
                   message='Your request method is not supported.' \
                   ' Check your HTTP method and try again.'), 405

@app.errorhandler(500)
def internal_server_error(error):
    """ Handles catostrophic errors """
    return jsonify(status=500, error='Internal Server Error', message=error.message), 500

######################################################################
# GET INDEX
######################################################################
@app.route('/')
def index():
    """ Return something useful by default """
    return jsonify(name='Pet Demo REST API Service',
                   version='1.0',
                   url=url_for('list_pets', _external=True)), HTTP_200_OK

######################################################################
# LIST ALL PETS
######################################################################
@app.route('/pets', methods=['GET'])
def list_pets():
    """ Retrieves a list of pets from the database """
    app.logger.info('Listing pets')
    results = []
    category = request.args.get('category')
    if category:
        results = Pet.find_by_category(category)
    else:
        results = Pet.all()

    return jsonify([pet.serialize() for pet in results]), HTTP_200_OK

######################################################################
# RETRIEVE A PET
######################################################################
@app.route('/pets/<int:pet_id>', methods=['GET'])
def get_pets(pet_id):
    """ Retrieves a Pet with a specific id """
    app.logger.info('Finding a Pet with id [{}]'.format(pet_id))
    pet = Pet.find(pet_id)
    if pet:
        message = pet.serialize()
        return_code = HTTP_200_OK
    else:
        message = {'error' : 'Pet with id: %s was not found' % str(pet_id)}
        return_code = HTTP_404_NOT_FOUND

    return jsonify(message), return_code

######################################################################
# ADD A NEW PET
######################################################################
@app.route('/pets', methods=['POST'])
def create_pets():
    """ Creates a Pet in the datbase from the posted database """
    app.logger.info('Creating a new pet')
    payload = request.get_json()
    pet = Pet()
    pet.deserialize(payload)
    pet.save()
    message = pet.serialize()
    response = make_response(jsonify(message), HTTP_201_CREATED)
    response.headers['Location'] = url_for('get_pets', pet_id=pet.id, _external=True)
    return response

######################################################################
# UPDATE AN EXISTING PET
######################################################################
@app.route('/pets/<int:pet_id>', methods=['PUT'])
def update_pets(pet_id):
    """ Updates a Pet in the database fom the posted database """
    app.logger.info('Updating a Pet with id [{}]'.format(pet_id))
    pet = Pet.find(pet_id)
    if pet:
        payload = request.get_json()
        pet.deserialize(payload)
        pet.id = pet_id
        pet.save()
        message = pet.serialize()
        return_code = HTTP_200_OK
    else:
        message = {'error' : 'Pet with id: %s was not found' % str(pet_id)}
        return_code = HTTP_404_NOT_FOUND

    return jsonify(message), return_code

######################################################################
# DELETE A PET
######################################################################
@app.route('/pets/<int:pet_id>', methods=['DELETE'])
def delete_pets(pet_id):
    """ Removes a Pet from the database that matches the id """
    app.logger.info('Deleting a Pet with id [{}]'.format(pet_id))
    pet = Pet.find(pet_id)
    if pet:
        pet.delete()
    return make_response('', HTTP_204_NO_CONTENT)

######################################################################
# Demo DATA
######################################################################
@app.route('/pets/demo', methods=['POST'])
def create_demo_data():
    """ Loads a few Pets into the database for demos """
    app.logger.info('Loading demo Pets')
    Pet(0, 'fido', 'dog').save()
    Pet(0, 'kitty', 'cat').save()
    return make_response(jsonify(message='Created demo pets'), HTTP_201_CREATED)

######################################################################
#   U T I L I T Y   F U N C T I O N S
######################################################################
def initialize_logging(log_level=logging.INFO):
    """ Initialized the default logging to STDOUT """
    if not app.debug:
        print 'Setting up logging...'
        # Set up default logging for submodules to use STDOUT
        # datefmt='%m/%d/%Y %I:%M:%S %p'
        fmt = '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'
        logging.basicConfig(stream=sys.stdout, level=log_level, format=fmt)
        # Make a new log handler that uses STDOUT
        handler = logging.StreamHandler(sys.stdout)
        handler.setFormatter(logging.Formatter(fmt))
        handler.setLevel(log_level)
        # Remove the Flask default handlers and use our own
        handler_list = list(app.logger.handlers)
        for log_handler in handler_list:
            app.logger.removeHandler(log_handler)
        app.logger.addHandler(handler)
        app.logger.setLevel(log_level)
        app.logger.info('Logging handler established')


text:
import React from "react";
import { useTranslation } from "react-i18next";
import { Form, Input, InputProps, Popup } from "semantic-ui-react";
import { FormField } from "components/FormField";

interface ILikertValueFields<T> {
  leftValue: T;
  rightValue: T;
}

interface IProps {
  setLeftValue(num: number): void;
  setRightValue(num: number): void;
  switchValues(): void;
  canEdit: boolean;
  values: ILikertValueFields<number>;
  errors: ILikertValueFields<string>;
  touched: ILikertValueFields<boolean>;
}

const InputWithPopupInEdit = (
  p: {
    canEdit: boolean;
  } & InputProps
): JSX.Element => {
  const { t } = useTranslation();
  const { canEdit, ...inputProps } = p;
  const input = <Input {...inputProps} />;
  if (!canEdit) {
    const editMessage = t(
      "We do not allow the values of the scale to be edited to ensure data consistency. If you would like to change them, please delete this question and recreate it or contact support@impactasaurus.org"
    );
    // div here is to make the popup work on a disabled input field
    return <Popup content={editMessage} trigger={
{input}
} />;
  }
  return input;
};

const toInt = (s: string) => parseInt(s, 10);

export const LikertValueInput = (p: IProps): JSX.Element => {
  const { t } = useTranslation();
  const { errors, touched, values, canEdit } = p;
  return (

      <Form.Group>
        <FormField
          error={errors.leftValue}
          touched={touched.leftValue}
          inputID="lff-left"
          label={t("Left Value")}
          required={true}
          width={4}
        >
          <InputWithPopupInEdit
            canEdit={canEdit}
            id="lff-left"
            name="leftValue"
            type="number"
            placeholder={t("Left Value")}
            value={values.leftValue}
            onChange={(_, d) => p.setLeftValue(toInt(d.value))}
            disabled={!canEdit}
          />
        </FormField>
        <Form.Button
          width={8}
          basic={true}
          content={t("Reverse Scoring")}
          onClick={p.switchValues}
          className="invert"
          icon="exchange"
          disabled={!canEdit}
          type="button"
        />
        <FormField
          error={errors.rightValue as string}
          touched={touched.rightValue}
          inputID="lff-right"
          label={t("Right Value")}
          required={true}
          width={4}
        >
          <InputWithPopupInEdit
            canEdit={canEdit}
            id="lff-right"
            name="rightValue"
            type="number"
            placeholder={t("Right Value")}
            value={values.rightValue}
            onChange={(_, d) => p.setRightValue(toInt(d.value))}
            disabled={!canEdit}
          />
        </FormField>
      </Form.Group>

  );
};


text:
// TypeScript Version: 2.0

/**
* Interface defining function options.
*/
interface Options {
	/**
	* Package meta information (package.json) (default: {}).
	*/
	pkg?: any;

	/**
	* Command-line interface version.
	*/
	version?: string;

	/**
	* Help text (default: '').
	*/
	help?: string;

	/**
	* Process title or a boolean indicating whether to set the process title (default: true).
	*/
	title?: string | boolean;

	/**
	* Boolean indicating whether to check if a command-line interface is an outdated version (default: true).
	*/
	updates?: boolean;

	/**
	* Command-line arguments.
	*/
	argv?: Array<any>;

	/**
	* Command-line interface options (default: {}).
	*/
	options?: Options;
}

/**
* Command-line interface.
*/
declare class CLI {
	/**
	* Command-line interface constructor.
	*
	* @param options - options
	* @param options.pkg - package meta information (package.json) (default: {})
	* @param options.version - command-line interface version
	* @param options.help - help text (default: '')
	* @param options.title - process title or a boolean indicating whether to set the process title (default: true)
	* @param options.updates - boolean indicating whether to check if a command-line interface is an outdated version (default: true)
	* @param options.argv - command-line arguments
	* @param options.options - command-line interface options (default: {})
	* @throws must provide valid options
	* @returns command-line interface
	*
	* @example
	* var opts = {
	*     'pkg': require( './path/to/package.json' ),
	*     'help': 'Usage: beep [options] <boop>',
	*     'title': 'foo',
	*     'updates': true,
	*     'options': {
	*         'boolean': [
	*             'help',
	*             'version'
	*         ]
	*     }
	* };
	* var cli = new CLI( opts );
	* // returns <CLI>
	*
	* cli.close();
	*/
	constructor( options?: Options );

	/**
	* Returns parsed command-line arguments.
	*
	* @returns parsed command-line arguments
	*
	* @example
	* var cli = new CLI();
	*
	* var args = cli.args();
	* // returns <Array>
	*/
	args(): Array<string>;

	/**
	* Returns parsed command-line arguments.
	*
	* @returns parsed command-line arguments
	*
	* @example
	* var cli = new CLI();
	*
	* var args = cli.args();
	* // returns <Array>
	*/
	flags(): Array<string>;

	/**
	* Prints usage information and exits the process.
	*
	* @example
	* var opts = {
	*     'help': 'Usage: beep [options] <boop>'
	* };
	* var cli = new CLI( opts );
	*
	* cli.help();
	* // => 'Usage: beep [options] <boop>'
	*/
	help(): void;

	/**
	* Prints the command-line interface version and exits the process.
	*
	* @example
	* var opts = {
	*     'pkg': require( './path/to/package.json' )
	* };
	* var cli = new CLI( opts );
	*
	* cli.version();
	* // => '#.#.#'
	*/
	version(): void;

	/**
	* Gracefully exits the command-line interface and the calling process.
	*
	* @param code - exit code (default: 0)
	* @throws must provide a nonnegative integer
	*
	* @example
	* var cli = new CLI();
	*
	* // Gracefully exit:
	* cli.close();
	*/
	close( code?: number ): void;

	/**
	* Exits the command-line interface and the calling process due to an error.
	*
	* ## Notes
	*
	* -   The value assigned to the `message` property of the provided `Error` object is printed to `stderr` prior to exiting the command-line interface and the calling process.
	*
	* @param error - error object
	* @param code - exit code (default: 1)
	* @throws second argument must be a nonnegative integer
	*
	* @example
	* var cli = new CLI();
	*
	* // ...
	*
	* // Create an error object:
	* var err = new Error( 'invalid operation' );
	*
	* // Exit the process:
	* cli.error( err, 0 );
	*/
	error( error: Error, code?: number ): void;

	/**
	* Forces the command-line interface (and the calling process) to exit.
	*
	* @param code - exit code (default: 0)
	* @throws must provide a nonnegative integer
	*
	* @example
	* var cli = new CLI();
	*
	* // Forcefully exit:
	* cli.exit();
	*/
	exit( code?: number ): void;
}

// EXPORTS //

export = CLI;


text:
package com.xeiam.xchange.bitcurex.dto.account;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;

@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
public class BitcurexFunds {

    @JsonProperty("usd")
    private BigDecimal usd;
    @JsonProperty("pln")
    private BigDecimal pln;
    @JsonProperty("eur")
    private BigDecimal eur;
    @JsonProperty("btc")
    private BigDecimal btc;
    @JsonProperty("status")
    private String status;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    /**
     *
     * @return The usd
     */
    @JsonProperty("usd")
    public BigDecimal getUsd() {
        return usd;
    }

    /**
     *
     * @param usd The usd
     */
    @JsonProperty("usd")
    public void setUsd(BigDecimal usd) {
        this.usd = usd;
    }

    /**
     *
     * @return The pln
     */
    @JsonProperty("pln")
    public BigDecimal getPln() {
        return pln;
    }

    /**
     *
     * @param pln The pln
     */
    @JsonProperty("pln")
    public void setPln(BigDecimal pln) {
        this.pln = pln;
    }

    /**
     *
     * @return The eur
     */
    @JsonProperty("eur")
    public BigDecimal getEur() {
        return eur;
    }

    /**
     *
     * @param eur The eur
     */
    @JsonProperty("eur")
    public void setEur(BigDecimal eur) {
        this.eur = eur;
    }

    /**
     *
     * @return The btc
     */
    @JsonProperty("btc")
    public BigDecimal getBtc() {
        return btc;
    }

    /**
     *
     * @param btc The btc
     */
    @JsonProperty("btc")
    public void setBtc(BigDecimal btc) {
        this.btc = btc;
    }

    /**
     *
     * @return The Error
     */
    @JsonProperty("status")
    public String getStatus() {
        return status
;    }

    /**
     *
     * @param status
     */
    @JsonProperty("status")
    public void setStatus(String status) {
        this.status = status;
    }

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

}


text:
<?php
namespace Fd\EdificioBundle\Model;

/**
 * Cuando se crea un nuevo edificio se dispara un evento que a través de un servicio genera este domicilio
 * para el edificio nuevo.
 * El domicilio se crea como principal porque se está creando el edificio
 */
use Doctrine\ORM\EntityManager;
use Fd\EdificioBundle\Entity\Domicilio;
use Fd\EdificioBundle\Entity\Edificio;

class DomicilioTemporario {
    protected $em;

    public function __construct(EntityManager $em) {
        $this->em = $em;
    }

    public function crearTemporario(Edificio $edificio) {
        $domicilio = new Domicilio();
        $domicilio->setEdificio($edificio);

        $domicilio->setCalle('Ingrese la calle');
        $domicilio->setAltura(99);
        $domicilio->setPrincipal(TRUE);

        $this->em->persist($domicilio);
        $this->em->flush();

        return $domicilio;
    }

}