text:
<?php

namespace JaegerApp;

use JaegerApp\Di;
use JaegerApp\Encrypt;
use JaegerApp\Db;
use JaegerApp\Language;
use JaegerApp\Validate;
use JaegerApp\Files;
use JaegerApp\Errors;
use JaegerApp\License;
use JaegerApp\Email;
use JaegerApp\View;
use JaegerApp\Regex;
use JaegerApp\Shell;
use JaegerApp\Console;

/**
 * Jaeger - Bootstrap Object
 *
 * Sets up the environment and needed objects
 *
 * @package Bootstrap
 */
class Bootstrap extends Di
{
    /**
     * The language file to load
     *
     * @var array
     */
    protected $lang_file = null;

    /**
     * The paths to look for language files at
     *
     * @var array
     */
    protected $lang_paths = array();

    /**
     * The environment config details
     *
     * @var array
     */
    protected $config = array(
        'db' => array()
    );

    /**
     *
     * @ignore
     *
     */
    public function __construct()
    {
        parent::__construct();
        $this->setLangPath(realpath(dirname(__FILE__) . '/language'));
    }

    /**
     * Sets a language paths to use
     *
     * @param string $path
     */
    public function setLangPath($path)
    {
        $this->lang_paths[base64_encode($path)] = $path;
        return $this;
    }

    /**
     * Returns the set language paths
     *
     * @return \mithra62\array
     */
    public function getLangPath()
    {
        return $this->lang_paths;
    }

    /**
     * Sets the database connection details
     *
     * @param array $config
     */
    public function setDbConfig(array $config)
    {
        $this->config['db'] = $config;
        return $this;
    }

    /**
     * Returns the database configuration details
     *
     * @return array
     */
    public function getDbConfig()
    {
        return $this->config['db'];
    }

    /**
     * Sets up and returns all the objects we'll use
     *
     * @return \Pimple\Container
     */
    public function getServices()
    {
        $this->container = parent::getServices();
        $this->container['db'] = function ($c) {
            $db = new Db();
            $db->setCredentials($this->getDbConfig());
            $type = 'mysqli';
            if(class_exists('Pdo')) {
                $type = 'pdo';
            }

            $db->setAccessType($type);
            return $db;
        };

        $this->container['encrypt'] = function ($c) {
            $encrypt = new Encrypt();
            $new_key = $c['platform']->getEncryptionKey();
            $encrypt->setKey($new_key);
            return $encrypt;
        };

        $this->container['lang'] = function ($c) {
            $lang = new Language();
            if (is_array($this->getLangPath())) {
                foreach ($this->getLangPath() as $path) {
                    $lang->init($path);
                }
            } elseif ($this->getLangPath() != '') {
                $lang->init($this->getLangPath());
            }
            return $lang;
        };

        $this->container['validate'] = function ($c) {
            $validate = new Validate();
            $validate->setRegex($this->container['regex']);
            return $validate;
        };

        $this->container['files'] = function ($c) {
            $file = new Files();
            return $file;
        };

        $this->container['errors'] = function ($c) {
            $errors = new Errors();
            $errors->setValidation($c['validate']);
            return $errors;
        };

        $this->container['license'] = function ($c) {
            $license = new License();
            return $license;
        };

        $this->container['email'] = function ($c) {

            $email = new Email();
            $email->setView($c['view']);
            $email->setLang($c['lang']);
            return $email;
        };

        $this->container['view'] = function ($c) {
            $view = new View();
            $helpers = array(
                'file_size' => function ($text) {
                    return $this->container['view_helpers']->m62FileSize($text, false);
                },
                'lang' => function ($text) {
                    return $this->container['view_helpers']->m62Lang($text);
                },
                'date_time' => function ($text, $html = true) {
                    return $this->container['view_helpers']->m62DateTime($text, false);
                },
                'relative_time' => function ($date) {
                    return $this->container['view_helpers']->m62RelativeDateTime($date);
                },
                'encode' => function ($text) {
                    return $this->container['view_helpers']->m62Encode($text);
                },
                'decode' => function ($text) {
                    return $this->container['view_helpers']->m62Decode($text);
                }
            );

            $view->addHelper('m62', $helpers);
            return $view;
        };

        $this->container['regex'] = function ($c) {
            $regex = new Regex();
            return $regex;
        };

        $this->container['shell'] = function ($c) {
            $shell = new Shell();
            return $shell;
        };

        $this->container['console'] = function ($c) {
            $console = new Console();
            $console->setLang($c['lang']);
            return $console;
        };

        return $this->container;
    }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var fs = require('fs');

exports.mkdocs = {

  basic: function (test) {
    test.expect(1);

    var expected = [
          '404.html',
          'about',
          'css',
          'fonts',
          'img',
          'index.html',
          'js',
          'search',
          'sitemap.xml'
        ],
        actual = fs.readdirSync('test/basic/site')
          // Workaround for an apparent bug in mkdocs; some files are
          // copied to the output directory
          .filter(function (name) {
            return !/\.py(?:c)?$/.test(name);
          })
          .sort();

    test.deepEqual(expected, actual, 'should generate output files');

    test.done();
  }

};


text:
<?xml version="1.0" encoding="utf-8"?>
<Type Name="DescriptorSetAllocateInfo" FullName="Vulkan.DescriptorSetAllocateInfo">
  <TypeSignature Language="C#" Value="public class DescriptorSetAllocateInfo : Vulkan.MarshalledObject" />
  <TypeSignature Language="ILAsm" Value=".class public auto ansi beforefieldinit DescriptorSetAllocateInfo extends Vulkan.MarshalledObject" />
  <AssemblyInfo>
    <AssemblyName>Vulkan</AssemblyName>
    <AssemblyVersion>0.0.5950.20892</AssemblyVersion>
    <AssemblyVersion>0.0.6105.39043</AssemblyVersion>
    <AssemblyVersion>0.0.6106.39464</AssemblyVersion>
    <AssemblyVersion>0.0.6134.41045</AssemblyVersion>
    <AssemblyVersion>0.0.6142.19338</AssemblyVersion>
  </AssemblyInfo>
  <Base>
    <BaseTypeName>Vulkan.MarshalledObject</BaseTypeName>
  </Base>
  <Interfaces />
  <Docs>
    Structure specifying the allocation parameters for descriptor sets
    <remarks></remarks>
  </Docs>
  <Members>
    <Member MemberName=".ctor">
      <MemberSignature Language="C#" Value="public DescriptorSetAllocateInfo ();" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor() cil managed" />
      <MemberType>Constructor</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.5950.20892</AssemblyVersion>
        <AssemblyVersion>0.0.6105.39043</AssemblyVersion>
        <AssemblyVersion>0.0.6106.39464</AssemblyVersion>
        <AssemblyVersion>0.0.6134.41045</AssemblyVersion>
        <AssemblyVersion>0.0.6142.19338</AssemblyVersion>
      </AssemblyInfo>
      <Parameters />
      <Docs>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="DescriptorPool">
      <MemberSignature Language="C#" Value="public Vulkan.DescriptorPool DescriptorPool { get; set; }" />
      <MemberSignature Language="ILAsm" Value=".property instance class Vulkan.DescriptorPool DescriptorPool" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.5950.20892</AssemblyVersion>
        <AssemblyVersion>0.0.6105.39043</AssemblyVersion>
        <AssemblyVersion>0.0.6106.39464</AssemblyVersion>
        <AssemblyVersion>0.0.6134.41045</AssemblyVersion>
        <AssemblyVersion>0.0.6142.19338</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>Vulkan.DescriptorPool</ReturnType>
      </ReturnValue>
      <Docs>
        must: have enough free descriptor capacity remaining to allocate the descriptor sets of the specified layouts ****
        <value>To be added.</value>
        <remarks></remarks>
      </Docs>
    </Member>
    <Member MemberName="DescriptorSetCount">
      <MemberSignature Language="C#" Value="public uint DescriptorSetCount { get; set; }" />
      <MemberSignature Language="ILAsm" Value=".property instance unsigned int32 DescriptorSetCount" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.5950.20892</AssemblyVersion>
        <AssemblyVersion>0.0.6105.39043</AssemblyVersion>
        <AssemblyVersion>0.0.6106.39464</AssemblyVersion>
        <AssemblyVersion>0.0.6134.41045</AssemblyVersion>
        <AssemblyVersion>0.0.6142.19338</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.UInt32</ReturnType>
      </ReturnValue>
      <Docs>
        must: not be greater than the number of sets that are currently available for allocation in pname:descriptorPool
        <value>To be added.</value>
        <remarks></remarks>
      </Docs>
    </Member>
    <Member MemberName="Dispose">
      <MemberSignature Language="C#" Value="public override void Dispose (bool disposing);" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig virtual instance void Dispose(bool disposing) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.6134.41045</AssemblyVersion>
        <AssemblyVersion>0.0.6142.19338</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Void</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="disposing" Type="System.Boolean" />
      </Parameters>
      <Docs>
        <param name="disposing">To be added.</param>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="SetLayouts">
      <MemberSignature Language="C#" Value="public Vulkan.DescriptorSetLayout[] SetLayouts { get; set; }" />
      <MemberSignature Language="ILAsm" Value=".property instance class Vulkan.DescriptorSetLayout[] SetLayouts" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.5950.20892</AssemblyVersion>
        <AssemblyVersion>0.0.6105.39043</AssemblyVersion>
        <AssemblyVersion>0.0.6106.39464</AssemblyVersion>
        <AssemblyVersion>0.0.6134.41045</AssemblyVersion>
        <AssemblyVersion>0.0.6142.19338</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>Vulkan.DescriptorSetLayout[]</ReturnType>
      </ReturnValue>
      <Docs>
        is an array of descriptor set layouts, with each member specifying how the corresponding descriptor set is allocated.
        <value>To be added.</value>
        <remarks></remarks>
      </Docs>
    </Member>
    <Member MemberName="VirtualDispose">
      <MemberSignature Language="C#" Value="public override void VirtualDispose ();" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig virtual instance void VirtualDispose() cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.6105.39043</AssemblyVersion>
        <AssemblyVersion>0.0.6106.39464</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Void</ReturnType>
      </ReturnValue>
      <Parameters />
      <Docs>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
  </Members>
</Type>


text:
package com.pipipark.scaner.exception;

import com.pipipark.commons.throwable.ExceptionMessage;
import com.pipipark.commons.throwable.PPPRuntimeException;

@SuppressWarnings("serial")
public class ClassScanerException extends PPPRuntimeException {

	public ClassScanerException(ExceptionMessage message) {
		super(message);
	}

}


text:
Collection of sample projects using Kendo UI Builder for OpenEdge.

## Importing an existing project into Kendo UI Builder 2.0

Existing projects can be imported into Kendo UI Builder using the Import App option in Kendo UI Builder.
For projects from a previous version can be migrated to the new version by selecting the project from the main page in Kendo UI Builder. This will update the metadata. Custom code should be migrated manually.

## Running the sample apps

Kendo UI Builder apps can be run in several ways:
- Using the Preview option in Kendo UI Builder
- Using "npm start" from the app/ folder and accessing the app at http://localhost:4200
- Using Publish in Kendo UI Builder to create the build-output/debug or build-output/release folder, copy the folder to a web server and accessing index.html

Notes:
* This repository does not include the app/node_modules folder nor the build-output folder (optional in Kendo UI Builder 2.0).
    - Use Generate or Preview in Kendo UI Builder to create the app/node_modules folder.
    - Use Publish to create the build-output folder for get a static version of the app with a debug or a release version.
    - Alternatively, you can use "npm install" from the app/ folder to download the modules needed during development.

## Changing the Data Source

The Data Provider information in Kendo UI Builder is read-only. However, if you want to change the Data Provider used by a sample app to use your own OpenEdge backend, you could manually modify the corresponding JSON file in the meta/dataProviders folder in the project.
(Change serviceUri and catalogUris to change the location.)

# Projects

## form-external-paging

This example shows a form with navigation, CRUD capabilities, and also implements server paging. It is an extension of the form-with-crud app, but specifies server paging for its DataSource
	with a pagesize set to 5.

The Age combobox uses a local datasource.

Note:
- In order to prevent the automatic setting of the main datasource by the combobox at design time, a dummy datasource was added. A local datasource is set at runtime.

## form-with-crud

This example shows a form with various types of controls with navigation and CRUD capabilities.
A single row is displayed at a time and updates can be performed on the row. Navigation takes advantage of paging support of the datasource by setting pagesize to 1. In this way, binding between the datasource's row, the model, and the control is done automatically.

The Age combobox uses a local datasource.

Note:
- In order to prevent the automatic setting of the main datasource by the combobox at design time, a dummy datasource was added. A local datasource is set at runtime.

## grid-external-filtering

This example shows how to filter a grid by multiple fields using a single search text-box.

This is done by specifying a function in the "Change Event Function" property of the search text-box in the Component Properties pane.
The function itself is specified in the app/src/modules/<module-name>/<view-name>/controller.public.js.

Access to the data is done using the dsService helper class.

## grid-foreignkey

This example shows a view with grid component. One of the columns on the display data found in a related table.
Another view shows a grid component where one of the columns uses a DropDownList to input values from a related table.

## grid-image

This example shows how to display a static image on a grid using a row template function defined in app/src/modules/<module-name>/<view-name>/controller.public.js. The "Row Template Function" is specified via the Properties pane in the designer.

The static images are located in app/src/images.

## GridWithFormJFP

This example shows a grid component and a form with CRUD capabilities.
The JSON Filter Pattern (JFP) is used to provide server paging, filtering and sorting for the Customer grid.

This example showcases a Salesrep Drop Down List using data from data source specified for the view.
The view also shows a Country Drop Down List using local data from a data source created programmatically.

## ListView_FormWithCRUD

This example uses a list view and a form to provide CRUD operations.

## list-view-crud-with-validation

This example shows how to provide a more complex template for items in a list view.

This is done by specifying an HTML-based template in the app/src/modules/<module-name>/<view-name>/topSection.html and then specifying the id of the template in "Template Id" property in the list view's Component Properties pane.

This example also showcases validation on form fields.

The validation is implemented with code in app/src/modules/<module-name>/<view-name>/controller.public.js. See the code for more details.

Access to the data is done using the dsService helper class.


text:
#ifndef ANT_BSC_PAGE_0_H__
#define ANT_BSC_PAGE_0_H__

/** @file
 *
 * @defgroup ant_sdk_profiles_bsc_page0 BSC profile page 0
 * @{
 * @ingroup ant_sdk_profiles_bsc_pages
 */

#include <stdint.h>

/**@brief Data structure for BSC data page 0.
 *
 * This structure is used as a common page.
 */
typedef struct
{
    uint16_t event_time;            ///< Speed or cadence event time.
    uint16_t rev_count;             ///< Speed or cadence revolution count.
} ant_bsc_page0_data_t;

/**@brief Initialize page 0.
 */
#define DEFAULT_ANT_BSC_PAGE0() \
    (ant_bsc_page0_data_t)      \
    {                           \
        .event_time  = 0,       \
        .rev_count   = 0        \
    }

/**@brief Function for encoding page 0.
 *
 * @param[in]  p_page_data      Pointer to the page data.
 * @param[out] p_page_buffer    Pointer to the data buffer.
 */
void ant_bsc_page_0_encode(uint8_t * p_page_buffer, ant_bsc_page0_data_t const * p_page_data);

/**@brief Function for decoding page 0.
 *
 * @param[in]  p_page_buffer    Pointer to the data buffer.
 * @param[out] p_page_data      Pointer to the page data.
 */
void ant_bsc_page_0_decode(uint8_t const * p_page_buffer, ant_bsc_page0_data_t * p_page_data);

#endif // ANT_BSC_PAGE_0_H__
/** @} */


text:
class AlignmentOutputParameters : public BaseAlignment {
 public:
  bool printHeader;
  string clippingString;
  SAMOutput::Clipping clipping;
  bool  forPicard;
  bool  separateGaps;
	int printFormat;
  bool printSAM;
	string outFileName;

  void Init() {
    printHeader = false;
    clipping = SAMOutput::none;
    clippingString = "";
    forPicard = false;
    separateGaps = false;
		printFormat = SummaryPrint;
		outFileName = "";
    printSAM = false;
  }

  void RegisterCommandLineOptions(CommandLineParser &clp) {
    clp.RegisterFlagOption("header", (bool*)&printHeader, "For column formatted output, print a line "
                           "containing the names of each column.");
    clp.RegisterFlagOption("forPicard", &forPicard, "");
        clp.RegisterStringOption("clipping", &clippingString, "");
    clp.RegisterFlagOption("sam", &printSAM, "");
    clp.RegisterIntOption("m", &printFormat, "", CommandLineParser::NonNegativeInteger);
    clp.RegisterStringOption("out", &outFileName, "");
  }

  void MakeSane() {

    if (printSAM) {
      printFormat = SAM;
      forPicard = true;
    }

    //
    // Parse the clipping.
    //
    if (clippingString == "soft") {
      clipping = SAMOutput::soft;
    }
    else if (clippingString == "hard") {
      clipping = SAMOutput::hard;
    }
    else if (clippingString == "none") {
      clipping = SAMOutput::none;
    }
  }
};

#endif


text:
package org.mifos.framework.components.tabletag;

import java.util.Locale;
import java.util.ResourceBundle;

import org.mifos.accounts.loan.util.helpers.RequestConstants;
import org.mifos.framework.util.helpers.FilePaths;

/**
 * This class renders the page scroll property of the page like previous and
 * next links.
 */
public class PageScroll {

    /**
     * Function is used to get the required pages on the click of previous or
     * next link.
     *
     * @param current
     *            value of the current page.
     * @param pageSize
     *            no of data in a single page.
     * @param size
     *            size of the data.
     * @param currentFlowKey
     * @param prev
     *            boolean value to find out whether previous is clicked or not.
     * @param next
     *            boolean value to find out whether next is clicked or not.
     * @param jsp
     *            name of the jsp to which this previous or next click will take
     *            you to.
     * @return string next page.
     */
    protected static String getPages(int current, int pageSize, int size, String action, String currentFlowKey,
            Locale locale, String perspective) {
        StringBuilder result = new StringBuilder();
        ResourceBundle resource = ResourceBundle.getBundle(FilePaths.TABLE_TAG_PROPERTIESFILE, locale);
        // to check the onClick status of the prev and next whether that is
        // disable or not
        boolean prev = (current > 1) ? true : false;
        boolean next = ((current * pageSize) >= size) ? false : true;
        // Used to set the number of the start page
        int pageStart = ((current - 1) * pageSize) + 1;

        // Used to set the number of the end page
        int pageEnd = (current * pageSize);
        if (pageEnd > size) {
            pageEnd = size;
        }

        result.append("
");

        /**
         * to check whether previous is clicked or next is clicked and call the
         * respective page according to the click. if previous or next is not
         * allowed then disable the respective link.
         */

        String previousStr = resource.getString("Previous");
        String nextStr = resource.getString("Next");
        String resultsStr = resource.getString("Results");
        resultsStr = resultsStr.replaceFirst("%s1", new Integer(pageStart).toString());
        resultsStr = resultsStr.replaceFirst("%s2", new Integer(pageEnd).toString());
        resultsStr = resultsStr.replaceFirst("%s3", new Integer(size).toString());

        if (prev) {
            result.append("").append(
                    getAnchor(action, resource.getString("Previous"), "searchPrev", currentFlowKey, current - 1,
                            perspective)).append("	");
        } else {
            result.append("" + previousStr + "	");
        }
        result.append("" + resultsStr + " 	");
        if (next) {
            result.append("").append(
                    getAnchor(action, nextStr, "searchNext", currentFlowKey, current + 1, perspective)).append("	");
        } else {
            result.append("" + nextStr + "	");
        }
        result.append("
");
        return result.toString();
    }

    /**
     * Function to get the link property on previous and next.
     *
     * @param hRef
     *            page to which it is going on click.
     * @param text
     *            text to be displayed.
     * @param currentFlowKey
     * @param paramName1
     *            current.
     * @param paramvalue1
     *            current page number.
     * @param paramName2
     *            method name.
     * @param paramvalue2
     *            method value(previous or next).
     * @return
     */
    protected static String getAnchor(String hRef, String text, String method, String currentFlowKey, int current,
            String perspective) {
        StringBuilder result = new StringBuilder();

        result.append("").append(text).append("");
        return result.toString();
    }
}


text:
"use strict";
var Observable_1 = require('../../Observable');
var skipLast_1 = require('../../operator/skipLast');
Observable_1.Observable.prototype.skipLast = skipLast_1.skipLast;
//# sourceMappingURL=skipLast.js.map


text:
class HowtoState < GameState
  include Interaction

  def initialize
    @text = Gosu::Image.new($window, "res/howto-text.png", false)
    @back_button = Button.new(75, 650, :back, 108, 32, Proc.new {
      $window.state_manager.pop
    })
  end

  def update
    @back_button.update
  end

  def draw
    @text.draw 0, 0, Z::UI
    @back_button.draw
    draw_scope
  end

end


text:
from abc import ABCMeta, abstractmethod
import random
import math
from ggplot import *
import pandas as pd
from board_base import BoardBase

class Board(BoardBase):
    def __init__(self):
        self.limit = 8
        self.board = [[None for y in xrange(self.limit)] for x in xrange(self.limit)]

        for row in self.board:
            row[random.randrange(self.limit)] = 1

        self.moves = [
        lambda x, y : (x, y + 1),
        lambda x, y : (x + 1, y + 1),
        lambda x, y : (x + 1, y),
        lambda x, y : (x + 1, y - 1),
        lambda x, y : (x, y - 1),
        lambda x, y : (x - 1, y - 1),
        lambda x, y : (x - 1, y),
        lambda x, y : (x - 1, y + 1)
        ]

    def __str__(self):
        return self._print_board(self.board)

    def get_board(self):
        return self.board

    def next_moves(self, board):
        for i in xrange(len(board)):
            for j in xrange(len(board)):
                if board[i][j] == 1:
                    ctr = 0
                    for move in self.moves:
                        x, y = move(i, j)
                        ctr += 1
                        if self._is_valid(x, y) and board[x][y] == None:
                            board[i][j] = None
                            board[x][y] = 1
                            yield (board, (i, j), (x, y), self.eval(board))
                            board[x][y] = None
                            board[i][j] = 1

    def _print_board(self, board):
        answer = [" ".join(map(lambda x : "Q" if x else ".", row)) for row in board]
        return "\n".join(answer)

    def _randomize(self, board):
        board = [[None for y in xrange(self.limit)] for x in xrange(self.limit)]
        for row in board:
            row[random.randrange(self.limit)] = 1
        return board

    def improvise(self, board, limit = 1000, show = False):
        # Temperature is initialized to limit.
        temperature = limit
        heuristic = self.eval(board)
        final = heuristic
        costs = [heuristic]
        while True:
            if temperature == 0:
                if show:
                    print "Min heuristic cost attained:", final
                    data = pd.DataFrame({'Indices' : range(len(costs)), "Cost" : costs})
                    plt = ggplot(aes(x = 'Indices',y = 'Cost'), data = data) + \
                    geom_point()
                    plt.__repr__()
                return final

            # randomly select a neighbouring
            # state of board using the
            # reservoir sampling method.
            next_move = self.reservoir_sampling(board)
            next_move_cost = self.eval(next_move)
            diff = next_move_cost - heuristic

            if diff > 0:
                board = next_move
                heuristic = next_move_cost
            else:
                prob_change = pow(math.e, float(diff) / temperature)
                rnd = random.random()
                if rnd < prob_change:
                    board = next_move
                    heuristic = next_move_cost
            temperature -= 1
            costs.append(heuristic)
            final = min(final, heuristic)

    def _clone_board(self, board):
        new_board = [[None for x in xrange(self.limit)] for y in xrange(self.limit)]
        for i in xrange(len(board)):
            for j in xrange(len(board)):
                new_board[i][j] = board[i][j]
        return new_board

    def reservoir_sampling(self, board, k = 1):
        index = 1
        answer = None
        for neighbour in self.next_moves(board):
            if answer == None:
                future_board, initial, future, new_cost = neighbour
                new_board = self._clone_board(board)
                new_board[initial[0]][initial[1]] = None
                new_board[future[0]][future[1]] = 1
                answer = new_board
                index += 1

            else:
                remember = 1.0 / index
                rnd_number = random.random()

                if rnd_number < remember:
                    future_board, initial, future, new_cost = neighbour
                    new_board = self._clone_board(board)
                    new_board[initial[0]][initial[1]] = None
                    new_board[future[0]][future[1]] = 1
                    answer = new_board
                index += 1
        return answer

    def _is_valid(self, x, y):
        return 0 <= x < self.limit and 0 <= y < self.limit

    def _iter(self, x, y, move, board):
        x, y = move(x, y)
        while self._is_valid(x, y):
            if board[x][y] == 1:
                return 1
            x, y = move(x, y)
        return 0

    def eval(self, board):
        total = 0
        for i in xrange(len(board)):
            for j in xrange(len(board)):
                if board[i][j] == 1:
                    # there is a queen here.
                    for move in self.moves:
                        total += self._iter(i, j, move, board)
        return total / 2

b = Board()
print b.improvise(b.get_board(), show = True)


text:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace JSNLog.Infrastructure
{
    internal class LogMessageHelpers
    {
        public static T DeserializeJson<T>(string json)
        {
            T result = JsonConvert.DeserializeObject<T>(json);
            return result;
        }

        public static bool IsPotentialJson(string msg)
        {
            string trimmedMsg = msg.Trim();
            return (trimmedMsg.StartsWith("{") && trimmedMsg.EndsWith("}"));
        }

        /// <summary>
        /// Tries to deserialize msg.
        /// If that works, returns the resulting object.
        /// Otherwise returns msg itself (which is a string).
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static Object DeserializeIfPossible(string msg)
        {
            try
            {
                if (IsPotentialJson(msg))
                {
                    Object result = DeserializeJson<Object>(msg);
                    return result;
                }
            }
            catch
            {
            }

            return msg;
        }

        /// <summary>
        /// Returns true if the msg contains a valid JSON string.
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static bool IsJsonString(string msg)
        {
            try
            {
                if (IsPotentialJson(msg))
                {
                    // Try to deserialise the msg. If that does not throw an exception,
                    // decide that msg is a good JSON string.

                    DeserializeJson<Dictionary<string, Object>>(msg);

                    return true;
                }
            }
            catch
            {
            }

            return false;
        }

        /// <summary>
        /// Takes a log message and finds out if it contains a valid JSON string.
        /// If so, returns it unchanged.
        ///
        /// Otherwise, surrounds the string with quotes (") and escapes the string for JavaScript.
        /// </summary>
        /// <param name="ms"></param>
        /// <returns></returns>
        public static string EnsureValidJson(string msg)
        {
            if (IsJsonString(msg))
            {
                return msg;
            }

            return HtmlHelpers.JavaScriptStringEncode(msg, true);
        }
    }
}


text:
namespace securegcm {

using securemessage::CryptoOps;
using securemessage::ByteBuffer;
using securemessage::Util;

namespace {

// Fields to fill in the GcmMetadata proto.
const Type kGcmMetadataType = DEVICE_TO_DEVICE_MESSAGE;

// Represents the version of this context.
const uint8_t kProtocolVersion = 1;

// The following represent the starting positions of the each entry within
// the string representation of this D2DConnectionContextV1.
//
// The saved session has a 1 byte protocol version, two 4 byte sequence numbers,
// and two 32 byte AES keys: (1 + 4 + 4 + 32 + 32 = 73).

// The two sequence numbers are 4 bytes each.
const int kSequenceNumberLength = 4;

// 32 byte AES keys.
const int kAesKeyLength = 32;

// The encode sequence number starts at 1 to account for the 1 byte version
// number.
const int kEncodeSequenceStart = 1;
const int kEncodeSequenceEnd = kEncodeSequenceStart + kSequenceNumberLength;

const int kDecodeSequenceStart = kEncodeSequenceEnd;
const int kDecodeSequenceEnd = kDecodeSequenceStart + kSequenceNumberLength;

const int kEncodeKeyStart = kDecodeSequenceEnd;
const int kEncodeKeyEnd = kEncodeKeyStart + kAesKeyLength;

const int kDecodeKeyStart = kEncodeKeyEnd;
const int kSavedSessionLength = kDecodeKeyStart + kAesKeyLength;

// Convenience function to creates a DeviceToDeviceMessage proto with |payload|
// and |sequence_number|.
DeviceToDeviceMessage CreateDeviceToDeviceMessage(const std::string& payload,
                                                  uint32_t sequence_number) {
  DeviceToDeviceMessage device_to_device_message;
  device_to_device_message.set_sequence_number(sequence_number);
  device_to_device_message.set_message(payload);
  return device_to_device_message;
}

// Convert 4 bytes in big-endian representation into an unsigned int.
uint32_t BytesToUnsignedInt(std::vector<uint8_t> bytes) {
  return bytes[0] << 24 | bytes[1] << 12 | bytes[2] << 8 | bytes[3];
}

// Convert an unsigned int into a 4 byte big-endian representation.
std::vector<uint8_t> UnsignedIntToBytes(uint32_t val) {
  return {static_cast<uint8_t>(val >> 24), static_cast<uint8_t>(val >> 12),
          static_cast<uint8_t>(val >> 8), static_cast<uint8_t>(val)};
}

}  // namespace

D2DConnectionContextV1::D2DConnectionContextV1(
    const CryptoOps::SecretKey& encode_key,
    const CryptoOps::SecretKey& decode_key, uint32_t encode_sequence_number,
    uint32_t decode_sequence_number)
    : encode_key_(encode_key),
      decode_key_(decode_key),
      encode_sequence_number_(encode_sequence_number),
      decode_sequence_number_(decode_sequence_number) {}

std::unique_ptr<std::string> D2DConnectionContextV1::EncodeMessageToPeer(
    const std::string& payload) {
  encode_sequence_number_++;
  const DeviceToDeviceMessage message =
      CreateDeviceToDeviceMessage(payload, encode_sequence_number_);

  const D2DCryptoOps::Payload payload_with_type(kGcmMetadataType,
                                                message.SerializeAsString());
  return D2DCryptoOps::SigncryptPayload(payload_with_type, encode_key_);
}

std::unique_ptr<std::string> D2DConnectionContextV1::DecodeMessageFromPeer(
    const std::string& message) {
  std::unique_ptr<D2DCryptoOps::Payload> payload =
      D2DCryptoOps::VerifyDecryptPayload(message, decode_key_);
  if (!payload) {
    Util::LogError("DecodeMessageFromPeer: Failed to verify message.");
    return nullptr;
  }

  if (kGcmMetadataType != payload->type()) {
    Util::LogError("DecodeMessageFromPeer: Wrong message type in D2D message.");
    return nullptr;
  }

  DeviceToDeviceMessage d2d_message;
  if (!d2d_message.ParseFromString(payload->message())) {
    Util::LogError("DecodeMessageFromPeer: Unable to parse D2D message proto.");
    return nullptr;
  }

  decode_sequence_number_++;
  if (d2d_message.sequence_number() != decode_sequence_number_) {
    std::ostringstream stream;
    stream << "DecodeMessageFromPeer: Seqno in D2D message ("
           << d2d_message.sequence_number()
           << ") does not match expected seqno (" << decode_sequence_number_
           << ").";
    Util::LogError(stream.str());
    return nullptr;
  }

  return std::unique_ptr<std::string>(d2d_message.release_message());
}

std::unique_ptr<std::string> D2DConnectionContextV1::GetSessionUnique() {
  const ByteBuffer encode_key_data = encode_key_.data();
  const ByteBuffer decode_key_data = decode_key_.data();
  const int32_t encode_key_hash = java_util::JavaHashCode(encode_key_data);
  const int32_t decode_key_hash = java_util::JavaHashCode(decode_key_data);

  const ByteBuffer& first_buffer =
      encode_key_hash < decode_key_hash ? encode_key_data : decode_key_data;
  const ByteBuffer& second_buffer =
      encode_key_hash < decode_key_hash ? decode_key_data : encode_key_data;

  ByteBuffer data_to_hash(D2DCryptoOps::kSalt, D2DCryptoOps::kSaltLength);
  data_to_hash = ByteBuffer::Concat(data_to_hash, first_buffer);
  data_to_hash = ByteBuffer::Concat(data_to_hash, second_buffer);

  std::unique_ptr<ByteBuffer> hash = CryptoOps::Sha256(data_to_hash);
  if (!hash) {
    Util::LogError("GetSessionUnique: SHA-256 hash failed.");
    return nullptr;
  }

  return std::unique_ptr<std::string>(new std::string(hash->String()));
}

// Structure of saved session is:
//
// +---------------------------------------------------------------------------+
// | 1 Byte  |      4 Bytes      |      4 Bytes      |  32 Bytes  |  32 Bytes  |
// +---------------------------------------------------------------------------+
// | Version | encode seq number | decode seq number | encode key | decode key |
// +---------------------------------------------------------------------------+
//
// The sequence numbers are represented in big-endian.
std::unique_ptr<std::string> D2DConnectionContextV1::SaveSession() {
  ByteBuffer byteBuffer = ByteBuffer(&kProtocolVersion, static_cast<size_t>(1));

  // Append encode sequence number.
  std::vector<uint8_t> encode_sequence_number_bytes =
      UnsignedIntToBytes(encode_sequence_number_);
  for (int i = 0; i < encode_sequence_number_bytes.size(); i++) {
    byteBuffer.Append(static_cast<size_t>(1), encode_sequence_number_bytes[i]);
  }

  // Append decode sequence number.
  std::vector<uint8_t> decode_sequence_number_bytes =
      UnsignedIntToBytes(decode_sequence_number_);
  for (int i = 0; i < decode_sequence_number_bytes.size(); i++) {
    byteBuffer.Append(static_cast<size_t>(1), decode_sequence_number_bytes[i]);
  }

  // Append encode key.
  byteBuffer = ByteBuffer::Concat(byteBuffer, encode_key_.data());

  // Append decode key.
  byteBuffer = ByteBuffer::Concat(byteBuffer, decode_key_.data());

  return std::unique_ptr<std::string>(new std::string(byteBuffer.String()));
}

// static.
std::unique_ptr<D2DConnectionContextV1>
D2DConnectionContextV1::FromSavedSession(const std::string& savedSessionInfo) {
  ByteBuffer byteBuffer = ByteBuffer(savedSessionInfo);

  if (byteBuffer.size() != kSavedSessionLength) {
    return nullptr;
  }

  uint32_t encode_sequence_number = BytesToUnsignedInt(
      byteBuffer.SubArray(kEncodeSequenceStart, kEncodeSequenceEnd)->Vector());
  uint32_t decode_sequence_number = BytesToUnsignedInt(
      byteBuffer.SubArray(kDecodeSequenceStart, kDecodeSequenceEnd)->Vector());

  const CryptoOps::SecretKey encode_key =
      CryptoOps::SecretKey(*byteBuffer.SubArray(kEncodeKeyStart, kAesKeyLength),
                           CryptoOps::KeyAlgorithm::AES_256_KEY);
  const CryptoOps::SecretKey decode_key =
      CryptoOps::SecretKey(*byteBuffer.SubArray(kDecodeKeyStart, kAesKeyLength),
                           CryptoOps::KeyAlgorithm::AES_256_KEY);

  return std::unique_ptr<D2DConnectionContextV1>(new D2DConnectionContextV1(
      encode_key, decode_key, encode_sequence_number, decode_sequence_number));
}

}  // namespace securegcm


text:
var moment = require('alloy/moment');
var Q = require('q');

function doClick(e) {
    updateAllInformation();
}

$.index.open();

var httpRequest = (function(){
	function encodeData(obj, url) {
		var str = [];
		for (var p in obj) {
			str.push(Ti.Network.encodeURIComponent(p) + "=" + Ti.Network.encodeURIComponent(obj[p]));
		}

		if (_.indexOf(url, "?") == -1) {
			return url + "?" + str.join("&");
		} else {
			return url + "&" + str.join("&");
		}
	}

	return function(args) {
		var defer, tiHttpClient;
		var url = args.url;
		var data = args.data;
		var method = args.method || 'GET';
		var headers = args.headers;

		defer = Q.defer();

		tiHttpClient = Ti.Network.createHTTPClient({
			onload: function() {
				var parsedData, error;
				if (this.status >= 200 && this.status < 300) {
					try { parsedData = JSON.parse(this.responseText); }
					catch (e) { error = e; }
				}
				else {
					error = "Bad HTTP Code";
				}
				if (error) {
					defer.reject({
						status:  this.status,
						message: error
					});
				}
				else {
					defer.resolve({
						status:  this.status,
						data: parsedData
					});
				}
			},
			onerror: function() {
				defer.reject({
					status:  this.status,
					message: this.responseText
				});
			},
			onsendstream: function(e) {
				defer.notify(e);
			},
			timeout: 1000
		});

		if(method == 'GET' && data){
			url = encodeData(data,url);
		}

		tiHttpClient.open(method, url, true);

		_.each(headers,function(value,key){
			tiHttpClient.setRequestHeader(key,value);
		});
		tiHttpClient.send(method == 'POST'?data:null);

		return defer.promise;
	};
})();

/*

weatherStatusCode
날씨 Context 중 상태 코드 알수 없음 : 0 맑음 : 1 흐림 : 2 안개 : 3 구름 : 4 비 : 5 눈 : 6 비/눈 : 7 폭우 : 8 폭설 : 9 폭우/폭설 : 10
weatherStatusDescription

weatherModifyCode
날씨 Context 중 수식 코드 알수 없음 : 0 강추위(한파) : 1 춥다 : 2 쌀쌀하다 : 3 포근하다 : 4 따듯하다 : 5 선선하다 : 6 덥다 : 7 무더위(폭염) : 8
weatherModifyDescription
 */

function getCurrentPosition() {
	var data = "",
	    defer = Q.defer();
	Ti.Geolocation.getCurrentPosition(function(e){
		if(e.success){
			defer.resolve(e);
		}else{
			defer.reject("GEO ERROR: " + e.code + ', ' +e.error);
		}
	});

	return defer.promise;
}

function updateAllInformation(){
	getCurrentPosition().then(function(e){
		updateWeather(e);
		updateWeatherStatus(e);
		updateLandmarkName(e);
	});
}

function updateWeather(e){
	//$.label.text = "확인중...";
	$.updateInfo.text = '';

	httpRequest({
		url : 'https://apis.sktelecom.com/v1/weather/status',
		method : 'GET',
		data : {
			latitude : e.coords.latitude,
			longitude : e.coords.longitude
		},
		headers : {
			'TDCProjectKey' : '2045a1d8-0ff7-46f3-b0e6-ae608ddd25dd',
			'Accept' : 'application/json'
		}
	}).then(function(result){

		$.modifyDesc.text = result.data.weatherModifyDescription;
		$.statusDesc.text = result.data.weatherStatusDescription;

		getFlickrPhotos({text : result.data.weatherModifyDescription, targetProxy : $.modifyDescImage});
		getFlickrPhotos({text : result.data.weatherStatusDescription, targetProxy : $.statusImage});

		$.updateInfo.text = moment().format('llll');
	});
}

function updateLandmarkName(e){

	httpRequest({
		url : 'https://apis.sktelecom.com/v1/zonepoi/pois',
		method : 'GET',
		data : {
			latitude : e.coords.latitude,
			longitude : e.coords.longitude
		},
		headers : {
			'TDCProjectKey' : '2045a1d8-0ff7-46f3-b0e6-ae608ddd25dd',
			'Accept' : 'application/json'
		}
	}).then(function(result){
		console.log(result);
		var landmarkname = result.data.results[0].name;
		$.landmark.text = landmarkname;
		console.log(result.data);
		//getFlickrPhotos({text : landmarkname.replace(/\((.*)?\)/,''), targetProxy : $.landmarkImage});
	}).catch(function(e){
		// alert(e);
	});
}

function updateWeatherStatus(e){
	// ref :  https://developers.skplanetx.com/apidoc/kor/weather/information/#doc1168
	httpRequest({
		url : 'http://apis.skplanetx.com/weather/current/minutely',
		method : 'GET',
		data : {
			version : '1',
			lat : e.coords.latitude,
			lon : e.coords.longitude
		},
		headers : {
			'appKey' : 'ea5b6542-e779-3fad-836d-a8e760539fe3',
			'Accept' : 'application/json'
		}
	}).then(function(result){
		var mData = result.data.weather.minutely[0];
		var precipitationTexts = ["없음", "비", "비/눈", "눈"];

		$.status.text = JSON.stringify(mData,null, '  ');
		// $.status.text = String.format("바람 : %sms \n강수 : %s, \n기온 : %s도 ( %s ~ %s ) \n습도 : %s%%",
			// mData.wind.wspd,
			// precipitationTexts[parseInt(mData.precipitation.type)],
			// mData.temperature.tc,
			// mData.temperature.tmin,
			// mData.temperature.tmax,
			// mData.humidity
		// );
	});
}

updateAllInformation();
Ti.App.addEventListener('resume', updateAllInformation);

function getFlickrPhotos(args){
	args = args || {};

	httpRequest({
		url : 'https://api.flickr.com/services/rest/',
		method : 'GET',
		data : {
			method : 'flickr.photos.search',
			api_key : '3daf938f07bf4146d6a416260a5737b1',
			text : args.text,
			format : 'json',
			nojsoncallback : 1
		},
		headers : {
			'Accept' : 'application/json'
		}
	}).then(function(result){
		var photo = result.data.photos.photo[_.random(0,result.data.photos.photo.length)];

		if(photo && photo.farm)
		{
			args.targetProxy && (args.targetProxy.image = 'http://farm' + photo.farm + '.staticflickr.com/' + photo.server + '/' + photo.id + '_' + photo.secret + '_n.jpg');
		}
	});
}


text:
"use strict";

var Asynchronous, // constructor, function
    FileSystemStrategy = require(__dirname + "/../FileSystemStrategy"),
    fs = require("fs");

/**
 * @auguments JsLoader/FileSystem/FileSystemStrategy
 * @constructor
 */
Asynchronous = function () {
    FileSystemStrategy.call(this);
};
Asynchronous.prototype = Object.create(FileSystemStrategy.prototype);

/**
 * @param {string} path
 * @param {JsLoader/FileSystem/FileSystemStrategy~existsCallback} callback
 * @return {void}
 */
Asynchronous.prototype.exists = function (path, callback) {
    fs.exists(path, function (exists) {
        callback(exists);
    });
};

/**
 * @param {string} path
 * @param {JsLoader/FileSystem/FileSystemStrategy~readDirCallback} callback
 * @return {void}
 */
Asynchronous.prototype.readDir = function (path, callback) {
    fs.readdir(path, function (err, files) {
        callback(files, err);
    });
};

/**
 * @param {string} path
 * @param {object} options
 * @param {JsLoader/FileSystem/FileSystemStrategy~readFileCallback} callback
 * @return {void}
 */
Asynchronous.prototype.readFile = function (path, options, callback) {
    fs.readFile(path, options, function (err, content) {
        callback(content, err);
    });
};

/**
 * @param {string} path
 * @param {JsLoader/FileSystem/FileSystemStrategy~realpathCallback} callback
 * @return {void}
 * @throws {Error}
 */
Asynchronous.prototype.realpath = function (path, callback) {
    fs.realpath(path, function (err, realpath) {
        callback(realpath, err);
    });
};

/**
 * @param {string} path
 * @param {JsLoader/FileSystem/FileSystemStrategy~statCallback} callback
 * @return {void}
 */
Asynchronous.prototype.stat = function (path, callback) {
    fs.stat(path, function (err, stat) {
        callback(stat, err);
    });
};

module.exports = Asynchronous;


text:
@interface DKButtonDecoratedTextField : NSTextField

@end


text:
#include "SkTypes.h"
#include "SkTHash.h"
#include "Timer.h"
#include "Window_ios.h"
#include "../Application.h"

#include "SDL.h"

using sk_app::Application;

int main(int argc, char* argv[]) {
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) != 0) {
        SkDebugf("Could not initialize SDL!\n");
        return 1;
    }

    Application* app = Application::Create(argc, argv, nullptr);

    SDL_Event event;
    bool done = false;
    while (!done) {
        while (SDL_PollEvent(&event)) {
            switch (event.type) {
                // events handled by the windows
                case SDL_WINDOWEVENT:
                case SDL_FINGERDOWN:
                case SDL_FINGERMOTION:
                case SDL_FINGERUP:
                case SDL_KEYDOWN:
                case SDL_KEYUP:
                case SDL_TEXTINPUT:
                    done = sk_app::Window_ios::HandleWindowEvent(event);
                    break;

                case SDL_QUIT:
                    done = true;
                    break;

                default:
                    break;
            }
        }

        app->onIdle();
    }
    delete app;

    SDL_Quit();

    return 0;
}


text:
package org.apache.metron.integration.mock;

import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.RetriesExhaustedWithDetailsException;
import org.apache.metron.hbase.Connector;
import org.apache.metron.hbase.TupleTableConfig;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MockHBaseConnector extends Connector {
    static List<Put> puts = Collections.synchronizedList(new ArrayList<Put>());
    public MockHBaseConnector(TupleTableConfig conf, String _quorum, String _port) throws IOException {
        super(conf, _quorum, _port);
    }

    @Override
    public void put(Put put) throws InterruptedIOException, RetriesExhaustedWithDetailsException {
        puts.add(put);
    }

    @Override
    public void close() {

    }
    public static void clear() {
        puts.clear();
    }
    public static List<Put> getPuts() {
        return puts;
    }
}


text:
/*****************************************************************************/
/* Imports */
/*****************************************************************************/
// - Main
import gulp from 'gulp';

// - Gulp modules
import gulpLoadPlugins from 'gulp-load-plugins';
const $ = gulpLoadPlugins();

// - Project config
import config from './_config';

export default () => {
  return gulp.src(config.images.src)
    // Filter out previously done images
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))

    // Place our nice new images
    .pipe(gulp.dest(config.images.path))

    // Let the console know what we did
    .pipe($.size({title: 'images'}));
}


text:
@implementation PKTOrganization

#pragma mark - PKTModel

+ (NSDictionary *)dictionaryKeyPathsForPropertyNames {
  return @{
           @"organizationID" : @"org_id",
           @"workspaces" : @"spaces",
           @"imageFile" : @"image"
           };
}

+ (NSValueTransformer *)workspacesValueTransformer {
  return [NSValueTransformer pkt_transformerWithModelClass:[PKTWorkspace class]];
}

+ (NSValueTransformer *)imageFileValueTransformer {
  return [NSValueTransformer pkt_transformerWithModelClass:[PKTFile class]];
}

+ (NSValueTransformer *)rightsValueTransformer {
  return [NSValueTransformer pkt_rightValueTransformer];
}

#pragma mark - API

+ (PKTAsyncTask *)fetchAll {
  PKTRequest *request = [PKTOrganizationsAPI requestForAllOrganizations];
  PKTAsyncTask *requestTask = [[PKTClient currentClient] performRequest:request];

  PKTAsyncTask *task = [requestTask map:^id(PKTResponse *response) {
    return [response.body pkt_mappedArrayWithBlock:^id(NSDictionary *orgDict) {
      return [[self alloc] initWithDictionary:orgDict];
    }];
  }];

  return task;
}

+ (PKTAsyncTask *)fetchWithID:(NSUInteger)organizationID {
  PKTRequest *request = [PKTOrganizationsAPI requestForOrganizationWithID:organizationID];
  PKTAsyncTask *requestTask = [[PKTClient currentClient] performRequest:request];

  PKTAsyncTask *task = [requestTask map:^id(PKTResponse *response) {
    return [[self alloc] initWithDictionary:response.body];
  }];

  return task;
}

@end


text:
<?php
/**
 * User: Alex Gusev <alex@flancer64.com>
 */

namespace Praxigento\Core\Api\App\Repo;

use Praxigento\Core\Data as DataObject;

/**
 * Base interface for CRUD repositories (general Create-Read-Update-Delete operations).
 */
interface Crud
    extends \Praxigento\Core\Api\App\Repo\DataSource
{
    /**
     * Create new data instance (simple entity or aggregate) using $data. Exception is thrown in case of any error.
     *
     * @param DataObject|array $data
     * @return bool|int|string|array|DataObject ID (integer|string|array) or 'true|false' (if insertion is failed)
     * or array|DataObject (if newly created object is returned).
     */
    public function create($data);

    /**
     * @param $where
     * @return int The number of affected rows.
     */
    public function delete($where = null);

    /**
     * @param int|string|array $id
     * @return int The number of affected rows.
     */
    public function deleteById($id);

    /**
     * Replace data for the entity.
     *
     * @param array $data [COL_NAME=>$value, ...]
     * @return int Count of the updated rows.
     */
    public function replace($data);

    /**
     * @param array $data [COL_NAME=>$value, ...]
     * @param mixed $where
     * @return int Count of the updated rows.
     */
    public function update($data, $where);

    /**
     * Update instance in the DB (look up by ID values).
     *
     * TODO: change ($id, $data) to ($data, $id)
     *
     * @param int|string|array $id
     * @param array|DataObject $data
     * @return int The number of affected rows.
     */
    public function updateById($id, $data);
}


text:
package com.microsoft.o365_tasks.utils;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;

public class DateUtil {

    private static final String UTC_TIMEZONE_ID = "UTC";

    private static String zeroPad(int number, int padLength) {

        String str = Integer.toString(number);

        if (str.length() > padLength)
            return str;

        char[] zeroes = new char[padLength - str.length()];
        for (int i = 0; i < zeroes.length; i++) {
            zeroes[i] = '0';
        }

        return new String(zeroes) + str;
    }

    /**
     * ISO8601 date/time parser based on the parser from Json.NET.
     *
     * https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/Utilities/DateTimeParser.cs
     *
     * This parser can handle optional date/time parts and will happily parse up to 7 digits of millisecond
     * precision, as can be the case for ISO8601 strings coming from .NET applications.
     *
     * Unfortunaly the Java Date class only supports up to 999ms of precision, so any additional precision is lost.
     *
     */
    private static class Iso8601Parser
    {
        private static final int CONSUME_FAIL = -1;
        private static final int MAX_FRACTION_DIGITS = 7;
        private static final int TICKS_PER_MILLISECOND = 10000;
        private static final int[] POWERS_OF_TEN = new int[] { -1 /* not used */, 10, 100, 1000, 10000, 100000, 1000000 };

        private char[] mInput;
        private int mPosition;

        private int mYear;
        private int mMonth;
        private int mDayOfMonth;
        private int mHour;
        private int mMinute;
        private int mSecond;
        private int mFraction;
        private String mTimeZoneId;

        public Date parseIso8601(String dateString) throws DateParseException {

            mInput = dateString.toCharArray();
            mPosition = 0;

            mYear = 0;
            mMonth = 1;
            mDayOfMonth = 1;
            mHour = 0;
            mMinute = 0;
            mSecond = 0;
            mFraction = 0;
            mTimeZoneId = UTC_TIMEZONE_ID;

            parseDateComponent();

            if (tryConsumeChar('T') || tryConsumeChar('t')) {

                parseTimeComponent();

                if (tryConsumeChar('.')) {

                    parseMillisecondComponent();
                }

                parseTimeZoneComponent();

            }

            //assert this is the end of the string
            if (mPosition < mInput.length)
                throw makeParserError("Unexpected character '" + mInput[mPosition] + "'");

            TimeZone timeZone = TimeZone.getTimeZone(mTimeZoneId);

            if (!timeZone.getID().equalsIgnoreCase(mTimeZoneId)) {
                throw makeParserError("Invalid time zone: " + mTimeZoneId);
            }

            Calendar cal = new GregorianCalendar(timeZone);
            cal.setLenient(false);

            cal.set(Calendar.YEAR, mYear);
            cal.set(Calendar.MONTH, mMonth - 1);
            cal.set(Calendar.DAY_OF_MONTH, mDayOfMonth);
            cal.set(Calendar.HOUR_OF_DAY, mHour);
            cal.set(Calendar.MINUTE, mMinute);
            cal.set(Calendar.SECOND, mSecond);
            cal.set(Calendar.MILLISECOND, mFraction / TICKS_PER_MILLISECOND);

            return cal.getTime();
        }

        private void parseDateComponent() throws DateParseException {

            boolean ok;

            //Parse year component
            ok = (mYear = consume4Digits()) != CONSUME_FAIL
                    && 1 <= mYear;

            if (!ok) throw makeParserError("Invalid year component");

            consumeChar('-');

            //Parse month component
            ok = (mMonth = consume2Digits()) != CONSUME_FAIL
                    && 1 <= mMonth
                    && mMonth <= 12;

            if (!ok) throw makeParserError("Invalid month component");

            consumeChar('-');

            //Parse day component
            ok = (mDayOfMonth = consume2Digits()) != CONSUME_FAIL
                    && 1 <= mDayOfMonth; //check start of range

            if (!ok) throw makeParserError("Invalid day component");
        }

        private void parseTimeComponent() throws DateParseException {

            boolean ok;

            //Parse hour component
            ok = (mHour = consume2Digits()) != CONSUME_FAIL
                    && mHour < 24;

            if (!ok) throw makeParserError("Invalid hour component");

            consumeChar(':');

            //Parse minutes component
            ok = (mMinute = consume2Digits()) != CONSUME_FAIL
                    && mMinute < 60;

            if (!ok) throw makeParserError("Invalid minute component");

            consumeChar(':');

            //Parse seconds component
            ok = (mSecond = consume2Digits()) != CONSUME_FAIL
                    && mSecond < 60;

            if (!ok) throw makeParserError("Invalid second component");
        }

        private void parseMillisecondComponent() throws DateParseException {
            int numberOfDigits = 0;

            while (mPosition < mInput.length && numberOfDigits < MAX_FRACTION_DIGITS)
            {
                int digit = mInput[mPosition] - '0';
                if (digit < 0 || digit > 9)
                    break;

                mFraction = (mFraction * 10) + digit;

                numberOfDigits++;
                mPosition++;
            }

            if (numberOfDigits < MAX_FRACTION_DIGITS) {

                if (numberOfDigits == 0)
                    throw makeParserError("Invalid millisecond component");

                mFraction *= POWERS_OF_TEN[MAX_FRACTION_DIGITS - numberOfDigits];
            }
        }

        private void parseTimeZoneComponent() throws DateParseException {

            if (tryConsumeChar('Z') || tryConsumeChar('z')) {

                mTimeZoneId = UTC_TIMEZONE_ID;

            }
            else {
                boolean isPositive = tryConsumeChar('+');

                if (!isPositive && !tryConsumeChar('-')) {

                    //No time zone component! bail out
                    return;
                }

                boolean ok;

                //Hour component
                int zoneHour = 0;

                ok = (zoneHour = consume2Digits()) != CONSUME_FAIL
                        && zoneHour < 24;

                if (!ok) throw makeParserError("Invalid zone hour component");

                tryConsumeChar(':'); //colon is optional

                //Minute component
                int zoneMinute = 0;

                ok = (zoneMinute = consume2Digits()) != CONSUME_FAIL
                        && zoneMinute < 60;

                if (!ok) throw makeParserError("Invalid zone minute component");

                mTimeZoneId = "GMT" + (isPositive ? '+' : '-') + zeroPad(zoneHour, 2) + ':' + zeroPad(zoneMinute, 2);
            }
        }

        private DateParseException makeParserError(String message) {
            return new DateParseException(message, new String(mInput), mPosition);
        }

        /**
         * Consumes four digits from the input.
         * @return The decimal value or CONSUME_FAIL
         */
        private int consume4Digits()
        {
            if (mPosition + 3 < mInput.length)
            {
                int digit1 = mInput[mPosition + 0] - '0';
                int digit2 = mInput[mPosition + 1] - '0';
                int digit3 = mInput[mPosition + 2] - '0';
                int digit4 = mInput[mPosition + 3] - '0';

                if (0 <= digit1 && digit1 < 10 &&
                    0 <= digit2 && digit2 < 10 &&
                    0 <= digit3 && digit3 < 10 &&
                    0 <= digit4 && digit4 < 10) {

                    mPosition += 4;
                    return (((((digit1 * 10) + digit2) * 10) + digit3) * 10) + digit4;
                }
            }

            return CONSUME_FAIL;
        }

        /**
         * Consumes two decimal digits from the input.
         * @return The decimal value or CONSUME_FAIL
         */
        private int consume2Digits()
        {
            if (mPosition + 1 < mInput.length)
            {
                int digit1 = mInput[mPosition + 0] - '0';
                int digit2 = mInput[mPosition + 1] - '0';

                if (0 <= digit1 && digit1 < 10 &&
                    0 <= digit2 && digit2 < 10) {

                    mPosition += 2;
                    return (digit1 * 10) + digit2;
                }
            }

            return CONSUME_FAIL;
        }

        /**
         * Attempts to consume a character from the input.
         * Throws if unsuccessful.
         * @param ch The character to consume
         * @throws DateParseException
         */
        private void consumeChar(char ch) throws DateParseException {
            if (!tryConsumeChar(ch)) {
                throw makeParserError("Expected '" + ch + "'");
            }
        }

        /**
         * Attempts to consume a character from the input.
         * The input position is only advanced when successful.
         * @param ch The character to consume
         * @return true if successful
         */
        private boolean tryConsumeChar(char ch)
        {
            if (mPosition < mInput.length && mInput[mPosition] == ch) {
                mPosition += 1;
                return true;
            }

            return false;
        }
    }

    public static Date parseIso8601(String s) throws DateParseException {

        Iso8601Parser parser = new Iso8601Parser();

        return parser.parseIso8601(s);
    }

    public static String formatIso8601(Date date) {
        return formatIso8601(date, TimeZone.getTimeZone(UTC_TIMEZONE_ID));
    }

    public static String formatIso8601(Date date, TimeZone tz) {

        Calendar calendar = new GregorianCalendar(tz, Locale.US);
        calendar.setTime(date);

        //Any formatted string should fit within 35 characters...
        StringBuilder sb = new StringBuilder(35);

        sb.append(zeroPad(calendar.get(Calendar.YEAR), 4));
        sb.append('-');
        sb.append(zeroPad(calendar.get(Calendar.MONTH) + 1, 2));
        sb.append('-');
        sb.append(zeroPad(calendar.get(Calendar.DAY_OF_MONTH), 2));
        sb.append('T');
        sb.append(zeroPad(calendar.get(Calendar.HOUR_OF_DAY), 2));
        sb.append(':');
        sb.append(zeroPad(calendar.get(Calendar.MINUTE), 2));
        sb.append(':');
        sb.append(zeroPad(calendar.get(Calendar.SECOND), 2));
        sb.append('.');
        sb.append(zeroPad(calendar.get(Calendar.MILLISECOND), 3)); //maximum accuracy of Calendar is 999 ms

        int offset = tz.getOffset(calendar.getTimeInMillis());
        if (offset == 0) {
            sb.append('Z');
        }
        else {
            int hours = Math.abs((offset / (60 * 1000)) / 60);
            int minutes = Math.abs((offset / (60 * 1000)) % 60);
            sb.append(offset < 0 ? '-' : '+');
            sb.append(zeroPad(hours, 2));
            sb.append(':');
            sb.append(zeroPad(minutes, 2));
        }

        return sb.toString();
    }

}


text:
<?php
/**
 *
 * @author Dean Manalo
 * @version Client 1.0.0
 *
 */
class Client extends MX_Controller{

	public function __construct(){
		parent::__construct();
		$this->load->module('auth');
	}

	public function index(){
		$this->session->set_flashdata('referrer', current_url());
		render("client.page", "client.template");
	}

	public function register(){
		$this->session->set_flashdata('referrer', current_url());
		render("registration.form","default.template");
	}

	public function changePassword(){
		if($this->session->userdata('c_username')){
			if($this->input->post(NULL, TRUE)){
				if($this->form_validation->run('change_client_password')){
					$username = $this->session->userdata('c_username');
					$newPassword = $this->input->post('new_password');
					$hashedPassword = $this->bcrypt->hash_password($newPassword);
					if($this->auth_model->updatePassword($username, $hashedPassword)){
						$this->session->set_flashdata('success_message', 'Password change successful');
						redirect('client');
					}
					else{
						$this->session->set_flashdata('error_message', 'A problem occurred while changing your password');
						redirect('client');
					}
				}
				else{
					render('client/change_password.form', 'client.template');
				}
			}
			else{
				render('client/change_password.form', 'client.template');
			}
		}
		else{
			echo "ERROR 403 FORBIDDEN";
		}
	}

	public function profileSettings(){
		if($this->session->userdata('c_username')){
			$username = $this->session->userdata('c_username');

			if($this->input->post(NULL, TRUE)){
				if($this->form_validation->run('profile_settings')){
					unset($_POST['first_name']);
					unset($_POST['last_name']);
					unset($_POST['date_of_birth']);
					if($this->auth_model->updateUserInfo($this->input->post(NULL, TRUE), $username)){
						$this->session->set_flashdata('success_message', 'Profile has been successfully updated');
						redirect("client");
					}
					else{
						//$this->session->set_flashdata('error_message', 'An error occurred');
						redirect("client");
					}
				}
				else{
					$data['userInfo'] = $this->auth_model->userInfo($username);
					render('client/profile_settings.form', 'client.template', $data);
				}
			}
			else{
				$data['userInfo'] = $this->auth_model->userInfo($username);
				render('client/profile_settings.form', 'client.template', $data);
			}
		}
		else{
			echo "ERROR 403 FORBIDDEN";
		}
	}

	public function accountSettings(){
		if($this->session->userdata('c_username')){
			$username = $this->session->userdata('c_username');

			if($this->input->post(NULL, TRUE)){
				if($this->form_validation->run('account_settings')){
					unset($_POST['username']);
					$currentEmail = $this->auth_model->userInfo($username)->email;

					if($currentEmail == $this->input->post('new_email', TRUE)){
						unset($_POST['new_email']);
						$_POST['security_answer'] = $this->encryption->encrypt($this->input->post('security_answer', TRUE));
						if($this->auth_model->updateUserInfo($this->input->post(NULL, TRUE), $username)){
							$this->session->set_flashdata('success_message', 'Your account has been updated');
							redirect("client");
						}
						else{
							redirect("client");
						}
					}
					else{
						$_POST['security_answer'] = $this->encryption->encrypt($this->input->post('security_answer', TRUE));
						if($this->auth_model->updateUserInfo($this->input->post(NULL, TRUE), $username)){
							$this->auth->sendEmailVerification($username);
							$this->session->set_flashdata('success_message', 'An email has been sent to you, follow the link to verify your new email address');
							redirect("client");
						}
						else{
							redirect("client");
						}
					}

				}
				else{
					$data['userInfo'] = $this->auth_model->userInfo($username);
					render('client/account_settings.form', 'client.template', $data);
				}
			}
			else{
				$data['userInfo'] = $this->auth_model->userInfo($username);
				render('client/account_settings.form', 'client.template', $data);
			}
		}
		else{
			echo "ERROR 403 FORBIDDEN";
		}
	}

	public function removePendingEmail(){
		$username = $this->session->userdata('c_username');
		if($this->auth_model->deleteUserPendingEmail($username)){
			$this->session->set_flashdata('success_message', 'Pending email removed');
			redirect("account_settings");
		}else{
			$this->session->set_flashdata('error_message', 'An error occured while trying to remove pending email');
			redirect("account_settings");
		}
	}

}
?>


text:
jQuery.sap.require("oscon2014.util.Formatter");

sap.ui.controller("oscon2014.view.Master", {

	handleListItemPress : function (evt) {
		var context = evt.getSource().getBindingContext();
		this.nav.to("Detail", context);
	},

	handleSearch : function (evt) {

		// create model filter
		var filters = [];
		var query = evt.getParameter("query");
		if (query && query.length > 0) {
			var filter = new sap.ui.model.Filter("SoId", sap.ui.model.FilterOperator.Contains, query);
			filters.push(filter);
		}

		// update list binding
		var list = this.getView().byId("list");
		var binding = list.getBinding("items");
		binding.filter(filters);
	},

	handleListSelect : function (evt) {
		var context = evt.getParameter("listItem").getBindingContext();
		this.nav.to("Detail", context);
	}
});


text:
<component name="libraryTable">
  <library name="Maven: io.github.jpenren:thymeleaf-spring-data-dialect:2.0.0">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/io/github/jpenren/thymeleaf-spring-data-dialect/2.0.0/thymeleaf-spring-data-dialect-2.0.0.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$MAVEN_REPOSITORY$/io/github/jpenren/thymeleaf-spring-data-dialect/2.0.0/thymeleaf-spring-data-dialect-2.0.0-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/io/github/jpenren/thymeleaf-spring-data-dialect/2.0.0/thymeleaf-spring-data-dialect-2.0.0-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
update APEX_050000.WWV_FLOW_FND_USER set web_password = 'Manager_12C' where user_name = 'ADMIN';
commit;


text:
package org.helianto.classic;

import java.io.Serializable;
import java.util.List;

/**
 * Interface to represent a tree node required by a TreeBuilder.
 *
 *

 * Any tree assembled with nodes implementing this interface are
 * simple ordered lists. Implementing classes must assure
 * appropriate ordering using getLevel() and getSequence().
 *

 *
 * @author Mauricio Fernandes de Castro
 */
public interface Node extends Comparable<Node>, Serializable {

	/**
	 * Id associated to the node.
	 */
	public int getId();

	/**
	 * Text displayed next to the node.
	 */
	public String getCaption();

	/**
	 * Content wrapped by the node.
	 */
	public Object getContent();

	/**
	 * Level used to provide ordering and identation.
	 */
	public int getLevel();

	/**
	 * Sequence used to provide ordering within a level.
	 */
	public int getSequence();

	/**
	 * Exposed icon.
	 */
	public String getIcon();

	/**
	 * True if node is expanded.
	 */
	public boolean isExpanded();

	/**
	 * True if node is editable.
	 */
	public boolean isEditable();

	/**
	 * Child list.
	 */
	public List<Node> getChildList();

}


text:
<!doctype html>
<html>
  <head>
    <title>Notifications: Showing a notification with an image and then abort the load immediately.</title>
    <script src="../resources/testharness.js"></script>
    <script src="../resources/testharnessreport.js"></script>
    <script src="../serviceworker/resources/test-helpers.js"></script>
    <script src="resources/test-helpers.js"></script>
  </head>
  <body>
    <script>
      // Tests that showing a notification with an image that takes 200ms to load, which
      // is unlikely to succeed because the Service Worker registration will be unregistered
      // immediately after, does not cause a crash.

      async_test(function(test) {
          var scope = 'resources/scope/' + location.pathname,
              script = 'resources/instrumentation-service-worker.js';

          testRunner.grantWebNotificationPermission(location.origin, true);
          getActiveServiceWorkerWithMessagePort(test, script, scope).then(function(info) {
              // (1) Display a Web Notification through the Service Worker with which
              // will take 200ms to load, and unregister the Service Worker immediately
              // after that to abort the in-progress load.
              info.port.postMessage({
                  command: 'show',

                  title: 'My Notification',
                  options: { body: 'Hello, world!',
                             icon: '/resources/slow-image.php?redirect_name=square100.png&mimeType=image/png&sleep=200' }
              });

              return info.registration.unregister().then(function () {
                  test.done();
              });
          }).catch(unreached_rejection(test));

      }, 'Showing a notification with an image and then abort the load immediately.');
    </script>
  </body>
</html>


text:
require 'chef/knife'
require 'chef/knife/bootstrap'
require 'chef/encrypted_data_bag_item'
require 'chef/knife/core/windows_bootstrap_context'
# Chef 11 PathHelper doesn't have #home
#require 'chef/util/path_helper'

class Chef
  class Knife
    module BootstrapWindowsBase

      # :nodoc:
      # Would prefer to do this in a rational way, but can't be done b/c of
      # Mixlib::CLI's design :(
      def self.included(includer)
        includer.class_eval do

          deps do
            require 'readline'
            require 'chef/json_compat'
          end

          option :chef_node_name,
            :short => "-N NAME",
            :long => "--node-name NAME",
            :description => "The Chef node name for your new node"

          option :prerelease,
            :long => "--prerelease",
            :description => "Install the pre-release chef gems"

          option :bootstrap_version,
            :long => "--bootstrap-version VERSION",
            :description => "The version of Chef to install",
            :proc => Proc.new { |v| Chef::Config[:knife][:bootstrap_version] = v }

          option :bootstrap_proxy,
            :long => "--bootstrap-proxy PROXY_URL",
            :description => "The proxy server for the node being bootstrapped",
            :proc => Proc.new { |p| Chef::Config[:knife][:bootstrap_proxy] = p }

          option :bootstrap_no_proxy,
            :long => "--bootstrap-no-proxy [NO_PROXY_URL|NO_PROXY_IP]",
            :description => "Do not proxy locations for the node being bootstrapped; this option is used internally by Opscode",
            :proc => Proc.new { |np| Chef::Config[:knife][:bootstrap_no_proxy] = np }

          # DEPR: Remove this option in Chef 13
          option :distro,
            :short => "-d DISTRO",
            :long => "--distro DISTRO",
            :description => "Bootstrap a distro using a template. [DEPRECATED] Use -t / --bootstrap-template option instead.",
            :proc        => Proc.new { |v|
              Chef::Log.warn("[DEPRECATED] -d / --distro option is deprecated. Use --bootstrap-template option instead.")
              v
            }

          option :bootstrap_template,
            :short => "-t TEMPLATE",
            :long => "--bootstrap-template TEMPLATE",
            :description => "Bootstrap Chef using a built-in or custom template. Set to the full path of an erb template or use one of the built-in templates."

          # DEPR: Remove this option in Chef 13
          option :template_file,
            :long => "--template-file TEMPLATE",
            :description => "Full path to location of template to use. [DEPRECATED] Use -t / --bootstrap-template option instead.",
            :proc        => Proc.new { |v|
              Chef::Log.warn("[DEPRECATED] --template-file option is deprecated. Use --bootstrap-template option instead.")
              v
            }

          option :run_list,
            :short => "-r RUN_LIST",
            :long => "--run-list RUN_LIST",
            :description => "Comma separated list of roles/recipes to apply",
            :proc => lambda { |o| o.split(",") },
            :default => []

          option :hint,
            :long => "--hint HINT_NAME[=HINT_FILE]",
            :description => "Specify Ohai Hint to be set on the bootstrap target.  Use multiple --hint options to specify multiple hints.",
            :proc => Proc.new { |h|
              Chef::Config[:knife][:hints] ||= Hash.new
              name, path = h.split("=")
              Chef::Config[:knife][:hints][name] = path ? Chef::JSONCompat.parse(::File.read(path)) : Hash.new
            }

          option :first_boot_attributes,
            :short => "-j JSON_ATTRIBS",
            :long => "--json-attributes",
            :description => "A JSON string to be added to the first run of chef-client",
            :proc => lambda { |o| JSON.parse(o) },
            :default => {}

          # Mismatch between option 'encrypted_data_bag_secret' and it's long value '--secret' is by design for compatibility
          option :encrypted_data_bag_secret,
            :short => "-s SECRET",
            :long  => "--secret ",
            :description => "The secret key to use to decrypt data bag item values.  Will be rendered on the node at c:/chef/encrypted_data_bag_secret and set in the rendered client config.",
            :default => false

          # Mismatch between option 'encrypted_data_bag_secret_file' and it's long value '--secret-file' is by design for compatibility
          option :encrypted_data_bag_secret_file,
            :long => "--secret-file SECRET_FILE",
            :description => "A file containing the secret key to use to encrypt data bag item values. Will be rendered on the node at c:/chef/encrypted_data_bag_secret and set in the rendered client config."

          option :auth_timeout,
            :long => "--auth-timeout MINUTES",
            :description => "The maximum time in minutes to wait to for authentication over the transport to the node to succeed. The default value is 2 minutes.",
            :default => 2

          option :node_ssl_verify_mode,
            :long        => "--node-ssl-verify-mode [peer|none]",
            :description => "Whether or not to verify the SSL cert for all HTTPS requests.",
            :proc        => Proc.new { |v|
              valid_values = ["none", "peer"]
              unless valid_values.include?(v)
                raise "Invalid value '#{v}' for --node-ssl-verify-mode. Valid values are: #{valid_values.join(", ")}"
              end
            }

          option :node_verify_api_cert,
            :long        => "--[no-]node-verify-api-cert",
            :description => "Verify the SSL cert for HTTPS requests to the Chef server API.",
            :boolean     => true

          option :msi_url,
            :short => "-u URL",
            :long => "--msi-url URL",
            :description => "Location of the Chef Client MSI. The default templates will prefer to download from this location. The MSI will be downloaded from chef.io if not provided.",
            :default => ''

          option :install_as_service,
            :long => "--install-as-service",
            :description => "Install chef-client as service in windows machine",
            :default => false

          option :bootstrap_vault_file,
          :long        => '--bootstrap-vault-file VAULT_FILE',
          :description => 'A JSON file with a list of vault(s) and item(s) to be updated'

          option :bootstrap_vault_json,
            :long        => '--bootstrap-vault-json VAULT_JSON',
            :description => 'A JSON string with the vault(s) and item(s) to be updated'

          option :bootstrap_vault_item,
            :long        => '--bootstrap-vault-item VAULT_ITEM',
            :description => 'A single vault and item to update as "vault:item"',
            :proc        => Proc.new { |i|
              (vault, item) = i.split(/:/)
              Chef::Config[:knife][:bootstrap_vault_item] ||= {}
              Chef::Config[:knife][:bootstrap_vault_item][vault] ||= []
              Chef::Config[:knife][:bootstrap_vault_item][vault].push(item)
              Chef::Config[:knife][:bootstrap_vault_item]
            }
        end
      end

      def default_bootstrap_template
        "windows-chef-client-msi"
      end

      def bootstrap_template
        # The order here is important. We want to check if we have the new Chef 12 option is set first.
        # Knife cloud plugins unfortunately all set a default option for the :distro so it should be at
        # the end.
        config[:bootstrap_template] || config[:template_file] || config[:distro] || default_bootstrap_template
      end

       # TODO: This should go away when CHEF-2193 is fixed
      def load_template(template=nil)
        # Are we bootstrapping using an already shipped template?

        template = bootstrap_template

        # Use the template directly if it's a path to an actual file
        if File.exists?(template)
          Chef::Log.debug("Using the specified bootstrap template: #{File.dirname(template)}")
          return IO.read(template).chomp
        end

        # Otherwise search the template directories until we find the right one
        bootstrap_files = []
        bootstrap_files << File.join(File.dirname(__FILE__), 'bootstrap/templates', "#{template}.erb")
        bootstrap_files << File.join(Knife.chef_config_dir, "bootstrap", "#{template}.erb") if Chef::Knife.chef_config_dir
        ::Knife::Windows::PathHelper.all_homes('.chef', 'bootstrap', "#{template}.erb") { |p| bootstrap_files << p }
        bootstrap_files << Gem.find_files(File.join("chef","knife","bootstrap","#{template}.erb"))
        bootstrap_files.flatten!

        template = Array(bootstrap_files).find do |bootstrap_template|
          Chef::Log.debug("Looking for bootstrap template in #{File.dirname(bootstrap_template)}")
          ::File.exists?(bootstrap_template)
        end

        unless template
          ui.info("Can not find bootstrap definition for #{config[:distro]}")
          raise Errno::ENOENT
        end

        Chef::Log.debug("Found bootstrap template in #{File.dirname(template)}")

        IO.read(template).chomp
      end

      def bootstrap_context
        @bootstrap_context ||= Knife::Core::WindowsBootstrapContext.new(config, config[:run_list], Chef::Config)
      end

      def load_correct_secret
        knife_secret_file = Chef::Config[:knife][:encrypted_data_bag_secret_file]
        knife_secret = Chef::Config[:knife][:encrypted_data_bag_secret]
        cli_secret_file = config[:encrypted_data_bag_secret_file]
        cli_secret = config[:encrypted_data_bag_secret]

        cli_secret_file = nil if cli_secret_file == knife_secret_file
        cli_secret = nil if cli_secret == knife_secret

        cli_secret_file = Chef::EncryptedDataBagItem.load_secret(cli_secret_file) if cli_secret_file != nil
        knife_secret_file = Chef::EncryptedDataBagItem.load_secret(knife_secret_file) if knife_secret_file != nil

        cli_secret_file || cli_secret || knife_secret_file || knife_secret
      end

      def render_template(template=nil)
        config[:secret] = load_correct_secret
        Erubis::Eruby.new(template).evaluate(bootstrap_context)
      end

      def bootstrap(proto=nil)
        if Chef::Config[:knife][:encrypted_data_bag_secret_file] || Chef::Config[:knife][:encrypted_data_bag_secret]
          warn_chef_config_secret_key
        end

        validate_name_args!

        @node_name = Array(@name_args).first
        # back compat--templates may use this setting:
        config[:server_name] = @node_name

        STDOUT.sync = STDERR.sync = true

        if (Chef::Config[:validation_key] && !File.exist?(File.expand_path(Chef::Config[:validation_key])))
          if Chef::VERSION.split('.').first.to_i == 11
            ui.error("Unable to find validation key. Please verify your configuration file for validation_key config value.")
            exit 1
          end

          unless locate_config_value(:chef_node_name)
            ui.error("You must pass a node name with -N when bootstrapping with user credentials")
            exit 1
          end

          chef_vault_handler.run(node_name: config[:chef_node_name]) if chef_vault_handler.doing_chef_vault?

          client_builder.run
          bootstrap_context.client_pem = client_builder.client_path
        else
          ui.info("Doing old-style registration with the validation key at #{Chef::Config[:validation_key]}...")
          ui.info("Delete your validation key in order to use your user credentials instead")
          ui.info("")
        end

        wait_for_remote_response( config[:auth_timeout].to_i )
        ui.info("Bootstrapping Chef on #{ui.color(@node_name, :bold)}")
        # create a bootstrap.bat file on the node
        # we have to run the remote commands in 2047 char chunks
        create_bootstrap_bat_command do |command_chunk|
          begin
            render_command_result = run_command(command_chunk)
            ui.error("Batch render command returned #{render_command_result}") if render_command_result != 0
            render_command_result
          rescue SystemExit => e
            raise unless e.success?
          end
        end

        # execute the bootstrap.bat file
        bootstrap_command_result = run_command(bootstrap_command)
        ui.error("Bootstrap command returned #{bootstrap_command_result}") if bootstrap_command_result != 0

        bootstrap_command_result
      end

      protected

      # Default implementation -- override only if required by the transport
      def wait_for_remote_response(wait_max_minutes)
      end

      def bootstrap_command
        @bootstrap_command ||= "cmd.exe /C #{bootstrap_bat_file}"
      end

      def bootstrap_render_banner_command(chunk_num)
        "cmd.exe /C echo Rendering #{bootstrap_bat_file} chunk #{chunk_num}"
      end

      def escape_windows_batch_characters(line)
        # TODO: The commands are going to get redirected - do we need to escape &?
        line.gsub!(/[(<|>)^]/).each{|m| "^#{m}"}
      end

      def create_bootstrap_bat_command()
        chunk_num = 0
        bootstrap_bat = ""
        banner = bootstrap_render_banner_command(chunk_num += 1)
        render_template(load_template(config[:bootstrap_template])).each_line do |line|
          escape_windows_batch_characters(line)
          # We are guaranteed to have a prefix "banner" command that echo's chunk number.  We can
          # confidently prefix every actual command with &&.
          # TODO: Why does ^\n&& work directly through the commandline but not through SOAP?
          render_line = " && >> #{bootstrap_bat_file} (echo.#{line.chomp.strip})"
          # Windows commands are limited to 8191 characters for machines running XP or higher but
          # this includes the length of environment variables after they have been expanded.
          # Since we don't actually know how long %TEMP% (and it's used twice - once in the banner
          # and once in every command redirection), we simply guess and set the max to 5000.
          # TODO: When a more accurate method is available, fix this.
          if bootstrap_bat.length + render_line.length + banner.length > 5000
            # Can't fit it into this chunk? - flush (if necessary) and then try.
            # Do this first because banner.length might change (e.g. due to an extra digit) and
            # prevent a fit.
            unless bootstrap_bat.empty?
              yield banner + bootstrap_bat
              bootstrap_bat = ""
              banner = bootstrap_render_banner_command(chunk_num += 1)
            end
            # Will this ever fit?
            if render_line.length + banner.length > 5000
              raise "Command in bootstrap template too long by #{render_line.length + banner.length - 5000} characters : #{line}"
            end
          end
          bootstrap_bat << render_line
        end
        raise "Bootstrap template was empty!  Check #{config[:bootstrap_template]}" if bootstrap_bat.empty?
        yield banner + bootstrap_bat
      end

      def bootstrap_bat_file
        @bootstrap_bat_file ||= "\"%TEMP%\\bootstrap-#{Process.pid}-#{Time.now.to_i}.bat\""
      end

      def locate_config_value(key)
        key = key.to_sym
        config[key] || Chef::Config[:knife][key]
      end

      def warn_chef_config_secret_key
        ui.info "* " * 40
        ui.warn(<<-WARNING)
\nSpecifying the encrypted data bag secret key using an 'encrypted_data_bag_secret'
entry in 'knife.rb' is deprecated. Please use the '--secret' or '--secret-file'
options of this command instead.

#{ui.color('IMPORTANT:', :red, :bold)} In a future version of Chef, this
behavior will be removed and any 'encrypted_data_bag_secret' entries in
'knife.rb' will be ignored completely.
        WARNING
        ui.info "* " * 40
      end
    end
  end
end