text:
class Downloader
{
  static const std::string downloader_program;
  static const std::string downloader_program_options;
  static const std::string downloader_program_to_file_option;

 public:
  static int DownloadPage(const std::string& link,
      const std::string& filename);
};

#endif


text:
/* jshint indent:false */
steal("can/view/target","can-simple-dom", "steal-qunit", function(target, simpleDom){

	module("can/view/target");

	test("basics", function(){

		// "
Hello {{message}}!
"
		var classCallback = function( ){
			equal(this.nodeName.toLowerCase(), "h1", "class on the right element");
			this.className = "selected";
		},
			attributesCallback = function(){
				equal(this.nodeName.toLowerCase(), "h1", "attributes on the right element");
			},
			textNodeCallback = function( ){
				equal(this.nodeType, 3, "got a text node");
				this.nodeValue = "World";
			};

		var data = target([{
			tag: "h1",
			attrs: {
				"id" : "myh1",
				"class" : classCallback
			},
			attributes: [attributesCallback],
			children: [{
				tag: "span",
				children: [
					"Hello ",
					textNodeCallback,
					"!"
				]
			}]
		}]);

		equal( data.clone.childNodes.length, 1, "there is one child");

		var h1 = data.clone.childNodes[0];
		equal( h1.nodeName.toLowerCase(), "h1", "there is one h1");
		equal( h1.id, "myh1", "the h1 has the right id");

		equal( h1.childNodes.length, 1, "the h1 has span");

		equal( h1.childNodes[0].childNodes.length, 3, "the span has 3 children");

		deepEqual( data.paths,
			[{
				path: [0],
				callbacks: [
					{ callback: classCallback },
					{ callback: attributesCallback }
				],
				paths: [{
					path: [0,1],
					callbacks: [
						{callback: target.keepsTextNodes ? textNodeCallback : data.paths[0].paths[0].callbacks[0].callback }
					]
				}]
			}] );

		var result = data.hydrate();

		var newH1 = result.childNodes[0];
		equal(newH1.className, "selected", "got selected class name");
		equal(newH1.innerHTML.toLowerCase(), "hello world!");

	});

	test("replacing items", function(){
		var data = target([
			function(){
				this.parentNode.insertBefore(document.createTextNode("inserted"), this.nextSibling);
			},
			"hi",
			function(){
				equal(this.previousSibling.nodeValue, "hi", "previous is as expected");
			}]);

		data.hydrate();
	});

	test("comments", function(){

		var data = target([
			{ tag: "h1" },
			{comment: "foo bar"}
		]);
		var node = data.clone.childNodes[1];
		equal(node.nodeValue, "foo bar", "node value is right");
		equal(node.nodeType, 8, "node is a comment");

	});

	test("paths should be run in reverse order (#966)", function(){

		var data = target([{
			tag: "h1",
			attributes: [function(){}],
			children:  [
				function(){
					this.parentElement.insertBefore(document.createElement("div"),this.nextSibling);
				},
				{
					tag: "span",
					children: [function(){
						equal(this.nodeType,3, "got an element");
					}]
				}
			]
		}]);
		data.hydrate();
	});

	test("renderToVirtualDOM", function(){

		var simpleDocument = new simpleDom.Document();

		//
{{#if foo}}{{/if}}foo

		var innerData = target([
			{
				tag: "span"
			}
		], simpleDocument);

		var outerData = target([
			{
				tag: "h1",
				children: [
					function(data){
						this.parentNode.insertBefore(innerData.hydrate(data), this);
						this.parentNode.removeChild(this);
					},
					"foo"
				]
			}
		], simpleDocument);

		var out = outerData.hydrate({foo: true});

		equal(out.firstChild.nodeName, "H1");

		equal(out.firstChild.firstChild.nodeName, "SPAN");
		equal(out.firstChild.lastChild.nodeValue, "foo");

	});

});

redpajama_set_name: RedPajamaGithub


text:
/*
 * File:   DecnetListener.cpp
 * Author: jguillaumes
 *
 * Created on 28 / gener / 2015, 13:40
 */

#include <sstream>
#include <fstream>

#include <pcap.h>
#include <errno.h>

#include "DecnetDefs.h"
#include "DecnetListener.h"
#include "DecnetListenerPcap.h"
#include "CounterHandler.h"
#include "FileSaver.h"
#include "PcapReader.h"
#include "BasicHandler.h"

using namespace std;

DecnetListenerPcap::DecnetListenerPcap(const std::string& iface,
                                       const std::string& fileName) {
    packetReader = new PcapReader(iface);
    packetHandler = new CounterHandler();
    if (packetReader->isCapturing()) {
        packetSaver = new FileSaver(fileName);
        if (!packetSaver->isSaving()) {
            msgError = errno;
        }
    } else {
        msgError = packetReader->getMsgError();
    }
}

DecnetListenerPcap::~DecnetListenerPcap() {
    delete packetReader;
}


text:
var map = require('./')
var ndjson = require('ndjson')
var args = require('minimist')(process.argv.slice(2))
var path = require('path')
var fs = require('fs')

var usage = fs.readFileSync(__dirname + '/usage.txt').toString()

var transform = args._[0]
if (args.file) transform = require(path.resolve(process.cwd(), args.file))

if (!transform) {
  console.error(usage)
  process.exit(1)
}

process.stdin
  .pipe(map(transform, args))
  .pipe(ndjson.serialize())
  .pipe(process.stdout)


text:
"use strict";

var jsdom = require("../..");
var toFileUrl = require("../util").toFileUrl(__dirname);

exports["document.currentScript is null when not executing " +
             "hello from html";

  var document = jsdom.jsdom(html, {
    url: toFileUrl(__filename),
    features: {
      FetchExternalResources: ["script"],
      ProcessExternalResources: ["script"]
    }
  });

  document.onload = function () {
    t.strictEqual(document.getElementById("test").innerHTML, "true",
                  "currentScript is the currently executing script element");
    t.strictEqual(document.currentScript, null, "currentScript is still null at top-level");
    t.done();
  };
};


text:
/* parameters for different functions */
#define CTA_VECTOR_CREATE_SIZE ( 1)
#define CTA_VECTOR_CREATE_INIT ( 2)
#define CTA_VECTOR_GETVALS     ( 3)
#define CTA_VECTOR_SETVALS     ( 4)
#define CTA_VECTOR_SETCONST    ( 5)
#define CTA_VECTOR_SCAL        ( 6)
#define CTA_VECTOR_COPY        ( 7)
#define CTA_VECTOR_AXPY        ( 8)
#define CTA_VECTOR_DOT         ( 9)
#define CTA_VECTOR_NRM2        (10)
#define CTA_VECTOR_AMAX        (11)
#define CTA_VECTOR_GETMAXLEN   (12)
#define CTA_VECTOR_FREE        (13)
#define CTA_VECTOR_GETVAL      (14)
#define CTA_VECTOR_SETVAL      (15)
#define CTA_VECTOR_EXPORT      (16)
#define CTA_VECTOR_PRINT_TABLE (17)
#define CTA_VECTOR_APPENDVAL   (18)
#define CTA_VECTOR_ELMDIV      (19)
#define CTA_VECTOR_IMPORT      (20)
#define CTA_VECTOR_NUMFUNC     (21)

/**
\file  cta_usr_vector.h

\brief In this file a description is given of the interface of user vector functions.
When creating your own vector class use the following as template.

The Usr_Vector to which is being referred in this template can be substituted by your own user vector object.

Step 1: for creating your own user vector class call the function CTA_Vector_DefineClass().

Example:

\code
typedef CTA_Handle CTA_VectorClass;

CTA_Func h_func[CTA_VECTOR_NUMFUNC];
CTA_VectorClass my_own_vector_class;

ierr=CTA_Func_Create(" ",&usr_vector_create_size, hintf, &h_func[CTA_VECTOR_CREATE_SIZE]);
//...for all implementation functions...

CTA_Vector_DefineClass("classname", h_func, &my_own_vector_class);\endcode

Making a user vector class involves the implementation of the following functions:

CTA_VECTOR_CREATE_SIZE \n
CTA_VECTOR_CREATE_INIT \n
CTA_VECTOR_GETVALS     \n
CTA_VECTOR_SETVALS     \n
CTA_VECTOR_SETCONST    \n
CTA_VECTOR_SCAL        \n
CTA_VECTOR_COPY        \n
CTA_VECTOR_AXPY        \n
CTA_VECTOR_DOT         \n
CTA_VECTOR_NRM2        \n
CTA_VECTOR_AMAX        \n
CTA_VECTOR_GETMAXLEN   \n
CTA_VECTOR_FREE        \n
CTA_VECTOR_GETVAL      \n
CTA_VECTOR_SETVAL      \n
CTA_VECTOR_EXPORT      \n
CTA_VECTOR_PRINT_TABLE \n
CTA_VECTOR_APPENDVAL   \n
CTA_VECTOR_ELMDIV      \n
CTA_VECTOR_IMPORT      \n

For creating an implementation function see documentation of CTA_Func_Create().

Step 2: to create an object of the newly defined vector class call CTA_Vector_Create() in the
same way as creating a CTA_Vector but with a different class handle, i.e. the user class handle from step 1 above.

Example:

\code
Usr_Vector usrvec; //user vector object
int nelements = 10;
CTA_Datatype datatype = CTAI_String2Type("CTA_STRING");
CTA_Handle userdata = CTA_NULL;
CTA_Vector_Create(my_own_vector_class, nelements, datatype, &userdata, &usrvec);
\endcode
\n
Note 1:  with object data is meant only the object itself including pointer(s) to its contents, but
not the contents of the vector.\n\n
Note 2:  vector indices start from 1.\n\n
*/

//CTA_VECTOR_CREATE_SIZE ( 1)
/** \brief Implementation that forms part of the create process.
 *
 * Must give the memory size of a new object.
 *
 * Example:
 *  \code
//in header file:
typedef struct {
   //your own user object data goes here...
}USR_VECTOR;

//user implementation:
void usr_vector_create_size(...){
   *memsize = sizeof(USR_VECTOR);
   *retval = CTA_OK;
}
 \endcode
 *
 * \note At index CTA_VECTOR_CREATE_SIZE in the function list of the class descriptor.
 *
 * \param n        I  dimension
 * \param datatype I  data type of the vector elements
 * \param userdata IO user data
 * \param retval   O  must receive return value of user implementation function
 * \param memsize  O  must receive the number of bytes which are necessary to store one
                      user vector class, with a pointer to the contents (data), but without the
                      contents themselves
 * \return no return value
 */
void usr_vector_create_size(int *n, CTA_Datatype *datatype,
                            void *userdata, int *retval, int *memsize);

//CTA_VECTOR_CREATE_INIT ( 2)
/** \brief Implementation that forms part of the create process.
 *
 * The user vector object needs to be made ready for use.
 *
 * \note At index CTA_VECTOR_CREATE_INIT in the function list of the class descriptor.
 *
 * \param objectdata IO pointer to object data of user vector
 * \param n          I  size of vector data
 * \param datatype   I  data type of the vector elements
 * \param userdata   IO user data
 * \param retval     O  must receive return value of user implementation function
 * \return no return value
 */
void usr_vector_create_init(Usr_Vector *objectdata, int *n, CTA_Datatype *datatype,
                            void *userdata, int *retval);

//CTA_VECTOR_GETVALS     ( 3)
/** \brief Implementation for retrieving all values of the user vector.
 *
 * \note At index CTA_VECTOR_GETVALS in the function list of the class descriptor.
 *
 * \param x        I   pointer to object data of the user vector
 * \param vals     O   must receive the values of the user vector
 * \param n        I   number of elements in the vals buffer, must equal number of elements in user vector
 * \param datatype I   data type of elements of vals, must be the same as data type of user vector x
 * \param userdata IO  user data
 * \param retval   O   must receive return value of user implementation function
 * \return no return value
 */
void usr_vector_getvals(Usr_Vector *x, void *vals, int *n, CTA_Datatype *datatype,
                         void *userdata, int *retval);

//CTA_VECTOR_SETVALS     ( 4)
/** \brief Implementation for setting all values of the user vector.
 *
 * \note At index CTA_VECTOR_SETVALS in the function list of the class descriptor.
 *
 * \param x        I   pointer to object data of user vector
 * \param vals     I   new values
 * \param n        I   number of elements in the vals buffer, must equal number of elements in user vector
 * \param datatype I   data type of elements of vals, must be the same as data type of user vector x
 * \param userdata IO  user data
 * \param retval   O   must receive return value of user implementation function
 * \return no return value
 */
void usr_vector_setvals(Usr_Vector *x, void *vals, int *n, CTA_Datatype *datatype,
                         void *userdata, int *retval);

//CTA_VECTOR_SETCONST    ( 5)
/** \brief Implementation for setting all values of user vector to same value.
 *
 * \note At index CTA_VECTOR_SETCONST in the function list of the class descriptor.
 *
 * \param x        I  pointer to object data of user vector
 * \param val      I  value to set vector elements to
 * \param datatype I  data type of elements of vals, must be the same as data type of user vector x
 * \param userdata IO user data
 * \param retval   O  must receive return value of user implementation function
 * \return no return value
 */
void usr_vector_setconst(Usr_Vector *x, void *val, CTA_Datatype *datatype,
                          void *userdata, int *retval);

//CTA_VECTOR_SCAL        ( 6)
/** \brief Implementation for scaling the user vector: x=ax
 *
 * \note At index CTA_VECTOR_SCAL in the function list of the class descriptor.
 *
 * \param x        IO pointer to object data of user vector
 * \param alpha    I  scaling factor
 * \param userdata IO user data
 * \param retval   O  must receive return value of user implementation function
 * \return no return value
 */
void usr_vector_scal(Usr_Vector *x, double *alpha, void *userdata, int *retval);

//CTA_VECTOR_COPY        ( 7)
/** \brief Implementation for copying the user vector.
 *
 * \note At index CTA_VECTOR_COPY in the function list of the class descriptor.
 *
 * \param x        I  pointer to object data of a user vector
 * \param y        O  pointer to object data of user vector y that must receive copy of x; must exist before calling
 * \param userdata IO user data
 * \param retval   O  must receive return value of user implementation function
 * \return no return value
 */
void usr_vector_copy(Usr_Vector *x, Usr_Vector *y, void *userdata,
                      int *retval);

//CTA_VECTOR_AXPY        ( 8)
/** \brief Implementation for applying the BLAS operation axpy: y=y+ax
 *
 * \note At index CTA_VECTOR_AXPY in the function list of the class descriptor.
 *
 * \param y        IO pointer to object data of user vector y; must exist before calling
 * \param alpha    I  scaling factor
 * \param x        I  pointer to object data of user vector x
 * \param userdata IO user data
 * \param retval   O  must receive return value of user implementation function
 * \return no return value
 */
void usr_vector_axpy(Usr_Vector *y, double *alpha, Usr_Vector *x,
                      void *userdata, int *retval);

//CTA_VECTOR_DOT         ( 9)
/** \brief Implementation for calculating the dot product of two user vectors x.y
 *
 * \note At index CTA_VECTOR_DOT in the function list of the class descriptor.
 *
 * \param y        I  pointer to object data of user vector y
 * \param x        I  pointer to object data of user vector x
 * \param userdata IO user data
 * \param dotprod  O  must receive the dot product
 * \param retval   O  must receive return value of user implementation function
 * \return no return value
 */
void usr_vector_dot(Usr_Vector *x, Usr_Vector *y, void *userdata,
                     double *dotprod, int *retval);

//CTA_VECTOR_NRM2        (10)
/** \brief Implementation for calculating the 2-norm of a user vector
 *
 * \note At index CTA_VECTOR_NRM2 in the function list of the class descriptor.
 *
 * \param x        I  pointer to object data of user vector
 * \param userdata IO user data
 * \param norm2    O  must receive the 2-norm
 * \param retval   O  must receive return value of user implementation function
 * \return no return value
 */
void usr_vector_nrm2(Usr_Vector *x, void *userdata, double *norm2, int *retval);

//CTA_VECTOR_AMAX        (11)
/** \brief Implementation for getting the index of the element with the largest maximum value. First index is 1.
 *
 * \note At index CTA_VECTOR_AMAX in the function list of the class descriptor.
 *
 * \param x        I  pointer to object data of user vector
 * \param userdata IO user data
 * \param iloc     O  must receive index of maximum value
 * \param retval   O  must receive return value of user implementation function
 * \return no return value
 */
void usr_vector_amax(Usr_Vector *x, void *userdata, int *iloc, int *retval);

//CTA_VECTOR_GETMAXLEN   (12)
/** \brief Implementation for getting the maximum length in case of vector with string elements.
 *
 * \note At index CTA_VECTOR_GETMAXLEN in the function list of the class descriptor.
 *
 * \param x        I  pointer to object data of user vector
 * \param userdata IO user data
 * \param maxlen   O  must receive maximum length
 * \param retval   O  must receive return value of user implementation function
 * \return no return value
 */
void usr_vector_getmaxlen(Usr_Vector *x, void *userdata, int *maxlen, int *retval);

//CTA_VECTOR_FREE        (13)
/** \brief Implementation for freeing the user vector.
 *
 * \note At index CTA_VECTOR_FREE in the function list of the class descriptor.
 *
 * \param x        IO pointer to object data of user vector
 * \param userdata IO user data
 * \param retval   O  must receive return value of user implementation function
 * \return no return value
 */
void usr_vector_free(Usr_Vector *x, void *userdata, int *retval);

//CTA_VECTOR_GETVAL      (14)
/** \brief Implementation for retrieving a single value of user vector at given index
 *
 * \note At index CTA_VECTOR_GETVAL in the function list of the class descriptor.
 *
 * \param x        I  pointer to object data of user vector
 * \param i        I  index of value to retrieve
 * \param val      O  must receive value; must exist before calling
 * \param datatype I  data type of *val, must be the same as data type of user vector x
 * \param userdata IO user data
 * \param retval   O  must receive return value of user implementation function
 * \return no return value
 */
void usr_vector_getval(Usr_Vector *x, int *i, void *val, CTA_Datatype *datatype,
                        void *userdata, int *retval);

//CTA_VECTOR_SETVAL      (15)
/** \brief Implementation for setting a single value of a user vector.
 *
 * \note At index CTA_VECTOR_SETVAL in the function list of the class descriptor.
 *
 * \param x        I  pointer to object data of user vector
 * \param i        I  index of value to set
 * \param val      I  new data of value
 * \param datatype I  data type of *val, must be the same as data type of user vector x
 * \param userdata IO user data
 * \param retval   O  must receive return value of user implementation function
 * \return no return value
 */
void usr_vector_setval(Usr_Vector *x, int *i, void *val, CTA_Datatype *datatype,
                        void *userdata, int *retval);

//CTA_VECTOR_EXPORT      (16)
/** \brief Implementation for exporting a user vector.
 *
 * \note At index CTA_VECTOR_EXPORT in the function list of the class descriptor.
 * \n For example implementation for exporting a user vector to a pack object or to screen.
 *
 * \param x        I  pointer to object data of user vector
 * \param userdata IO user data
 * \param retval   O  must receive return value of user implementation function
 * \return no return value
 */
void usr_vector_export(Usr_Vector *x, void userdata, int *retval);

//CTA_VECTOR_PRINT_TABLE (17)
/** \brief Implementation for printing a table.
 *
 * \note At index CTA_VECTOR_PRINT_TABLE in the function list of the class descriptor.
 *
 * \param table        IO array of vectors that forms the table to be filled
 * \param ncolumns     I  number of columns
 * \param formats      I  user vector
 * \param retval       O  must receive return value of user implementation function
 * \return no return value
 */
void usr_vector_print_table(Usr_Vector **table, int *ncolumns,
                      Usr_Vector * formats,     int *retval);

//CTA_VECTOR_APPENDVAL   (18)
/** \brief Implementation for appending a single value to the user vector.
 *
 * \note At index CTA_VECTOR_APPENDVAL in the function list of the class descriptor.
 *
 * \param x            IO pointer to object data of user vector
 * \param val          I  value to append
 * \param datatype     I  data type of value to append, must be the same as data type of user vector x
 * \param retval       O  must receive return value of user implementation function
 * \return no return value
 */
void usr_vector_appendval(Usr_Vector *x, void *val, CTA_Datatype *datatype,
                           int *retval);

//CTA_VECTOR_ELMDIV      (19)
/** \brief Implementation for element-wise division of user vector.
 *
 * \note At index CTA_VECTOR_ELMDIV in the function list of the class descriptor.
 *
 * \param y            IO pointer to object data of receiving user vector
 * \param x            I  pointer to object data of user vector x
 * \param userdata     IO user data
 * \param retval       O  must receive return value of user implementation function
 * \return no return value
 */
void usr_vector_elmdiv(Usr_Vector *y, CTAI_Vector_blas *x,
                      void *userdata, int *retval);

//CTA_VECTOR_IMPORT      (20)
/** \brief Implementation for importing a user vector.
 *
 * \note At index CTA_VECTOR_IMPORT in the function list of the class descriptor.
 *
 * \param x            O  pointer to object data of user vector that must receive import result
 * \param userdata     IO user data
 * \param retval       O  must receive return value of user implementation function
 * \return no return value
 */
void usr_vector_import(Usr_Vector *x, void userdata, int *retval);


text:
require 'ule_page/page'

module UlePage
  class Index < Page
    element_collection :rows, 'tbody tr'
    element :table, 'table'

    def goto_edit
      click_link_or_button '编辑'
    end

    protected
    def key_column
      ""
    end

    def get_row key
      find_row key, self.rows
    end

    def get_model_row model
      find_row(model[key_column], self.rows)
    end

    def get_model_row_anchor model, link_text
      row = get_model_row(model)
      raise 'can not find the row' if row.nil?
      row.find(:link_or_button, link_text)
    end
  end
end


text:
#ifndef HTMLScriptRunner_h
#define HTMLScriptRunner_h

#include "bindings/core/v8/ScriptStreamer.h"
#include "core/dom/PendingScript.h"
#include "core/fetch/ResourceClient.h"
#include "core/html/parser/HTMLParserReentryPermit.h"
#include "platform/heap/Handle.h"
#include "wtf/Deque.h"
#include "wtf/RefPtr.h"
#include "wtf/text/TextPosition.h"

namespace blink {

class Resource;
class Document;
class Element;
class HTMLScriptRunnerHost;

class HTMLScriptRunner final
    : public GarbageCollectedFinalized<HTMLScriptRunner>,
      private ScriptResourceClient {
  WTF_MAKE_NONCOPYABLE(HTMLScriptRunner);
  USING_GARBAGE_COLLECTED_MIXIN(HTMLScriptRunner);
  USING_PRE_FINALIZER(HTMLScriptRunner, detach);

 public:
  static HTMLScriptRunner* create(HTMLParserReentryPermit* reentryPermit,
                                  Document* document,
                                  HTMLScriptRunnerHost* host) {
    return new HTMLScriptRunner(reentryPermit, document, host);
  }
  ~HTMLScriptRunner();

  void detach();

  // Processes the passed in script and any pending scripts if possible.
  void execute(Element* scriptToProcess,
               const TextPosition& scriptStartPosition);

  void executeScriptsWaitingForLoad(Resource*);
  bool hasScriptsWaitingForResources() const {
    return m_hasScriptsWaitingForResources;
  }
  void executeScriptsWaitingForResources();
  bool executeScriptsWaitingForParsing();

  bool hasParserBlockingScript() const;
  bool isExecutingScript() const {
    return !!m_reentryPermit->scriptNestingLevel();
  }

  // ResourceClient
  void notifyFinished(Resource*) override;
  String debugName() const override { return "HTMLScriptRunner"; }

  DECLARE_TRACE();

 private:
  HTMLScriptRunner(HTMLParserReentryPermit*, Document*, HTMLScriptRunnerHost*);

  void executeParsingBlockingScript();
  void executePendingScriptAndDispatchEvent(PendingScript*,
                                            ScriptStreamer::Type);
  void executeParsingBlockingScripts();

  void requestParsingBlockingScript(Element*);
  void requestDeferredScript(Element*);
  bool requestPendingScript(PendingScript*, Element*) const;

  void runScript(Element*, const TextPosition& scriptStartPosition);

  bool isPendingScriptReady(const PendingScript*);

  void stopWatchingResourceForLoad(Resource*);

  void possiblyFetchBlockedDocWriteScript(Resource*);

  RefPtr<HTMLParserReentryPermit> m_reentryPermit;
  Member<Document> m_document;
  Member<HTMLScriptRunnerHost> m_host;
  Member<PendingScript> m_parserBlockingScript;
  // http://www.whatwg.org/specs/web-apps/current-work/#list-of-scripts-that-will-execute-when-the-document-has-finished-parsing
  HeapDeque<Member<PendingScript>> m_scriptsToExecuteAfterParsing;

  // We only want stylesheet loads to trigger script execution if script
  // execution is currently stopped due to stylesheet loads, otherwise we'd
  // cause nested script execution when parsing <style> tags since </style>
  // tags can cause Document to call executeScriptsWaitingForResources.
  bool m_hasScriptsWaitingForResources;
};

}  // namespace blink

#endif


text:
package com.google.template.soy.types;

import static com.google.common.truth.Truth.assertThat;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.template.soy.SoyFileSetParserBuilder;
import com.google.template.soy.base.SourceLocation;
import com.google.template.soy.error.ErrorReporter;
import com.google.template.soy.soytree.TemplateNode;
import com.google.template.soy.soytree.defn.HeaderParam;
import com.google.template.soy.types.ast.GenericTypeNode;
import com.google.template.soy.types.ast.NamedTypeNode;
import com.google.template.soy.types.ast.RecordTypeNode;
import com.google.template.soy.types.ast.RecordTypeNode.Property;
import com.google.template.soy.types.ast.TypeNode;
import com.google.template.soy.types.ast.TypeNodeVisitor;
import com.google.template.soy.types.ast.UnionTypeNode;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public final class TypeNodeTest {
  private static final SourceLocation sourceLocation = SourceLocation.UNKNOWN;

  private static final NamedTypeNode TYPE_ABC = NamedTypeNode.create(sourceLocation, "abc");
  private static final NamedTypeNode TYPE_DEF = NamedTypeNode.create(sourceLocation, "def");
  private static final NamedTypeNode TYPE_GHI = NamedTypeNode.create(sourceLocation, "ghi");
  private static final NamedTypeNode TYPE_JKL = NamedTypeNode.create(sourceLocation, "jkl");

  @Test
  public void testNamedTypeToString() throws Exception {
    assertThat(TYPE_ABC.toString()).isEqualTo("abc");
  }

  @Test
  public void testGenericTypeToString() throws Exception {
    assertThat(
            GenericTypeNode.create(sourceLocation, "foo", ImmutableList.<TypeNode>of()).toString())
        .isEqualTo("foo<>");
    assertThat(
            GenericTypeNode.create(sourceLocation, "list", ImmutableList.of(TYPE_ABC)).toString())
        .isEqualTo("list<abc>");
    assertThat(
            GenericTypeNode.create(sourceLocation, "map", ImmutableList.of(TYPE_ABC, TYPE_DEF))
                .toString())
        .isEqualTo("map<abc, def>");
  }

  @Test
  public void testRecordTypeToString() throws Exception {
    assertThat(RecordTypeNode.create(sourceLocation, ImmutableList.<Property>of()).toString())
        .isEqualTo("[]");
    assertThat(
            RecordTypeNode.create(
                    sourceLocation,
                    ImmutableList.of(Property.create(sourceLocation, "x", TYPE_ABC)))
                .toString())
        .isEqualTo("[x: abc]");

    assertThat(
            RecordTypeNode.create(
                    sourceLocation,
                    ImmutableList.of(
                        Property.create(sourceLocation, "x", TYPE_ABC),
                        Property.create(sourceLocation, "y", TYPE_DEF)))
                .toString())
        .isEqualTo("[x: abc, y: def]");

    assertThat(
            RecordTypeNode.create(
                    sourceLocation,
                    ImmutableList.of(
                        Property.create(sourceLocation, "x", TYPE_ABC),
                        Property.create(sourceLocation, "y", TYPE_DEF),
                        Property.create(sourceLocation, "z", TYPE_GHI),
                        Property.create(sourceLocation, "w", TYPE_JKL)))
                .toString())
        .isEqualTo("[\n  x: abc,\n  y: def,\n  z: ghi,\n  w: jkl\n]");
  }

  @Test
  public void testUnionTypeToString() throws Exception {
    assertThat(UnionTypeNode.create(ImmutableList.<TypeNode>of(TYPE_ABC, TYPE_DEF)).toString())
        .isEqualTo("abc|def");
  }

  @Test
  public void testRoundTripThroughParser() {
    assertRoundTrip("int");
    assertRoundTrip("?");
    assertRoundTrip("list<int>");
    assertRoundTrip("list<list<list<list<int>>>>");
    assertRoundTrip("map<int, any>");
    assertRoundTrip("[foo: string, bar: int, quux: [foo: string, bar: int, quux: list<any>]]");
  }

  private void assertRoundTrip(String typeString) {
    TypeNode original = parse(typeString);
    TypeNode reparsed = parse(original.toString());
    // we can't assert on the equality of the type nodes because the source locations may be
    // different due to whitespace.
    assertThat(original.toString()).isEqualTo(reparsed.toString());
    assertEquals(original, reparsed);
  }

  private static void assertEquals(
      ImmutableList<TypeNode> leftArgs, ImmutableList<TypeNode> rightArgs) {
    assertThat(leftArgs).hasSize(rightArgs.size());
    for (int i = 0; i < leftArgs.size(); i++) {
      assertEquals(leftArgs.get(i), rightArgs.get(i));
    }
  }

  static void assertEquals(TypeNode left, final TypeNode right) {
    left.accept(
        new TypeNodeVisitor<Void>() {

          @Override
          public Void visit(NamedTypeNode node) {
            assertThat(((NamedTypeNode) right).name()).isEqualTo(node.name());
            return null;
          }

          @Override
          public Void visit(GenericTypeNode node) {
            assertThat(((GenericTypeNode) right).name()).isEqualTo(node.name());
            assertEquals(node.arguments(), ((GenericTypeNode) right).arguments());
            return null;
          }

          @Override
          public Void visit(UnionTypeNode node) {
            assertEquals(node.candidates(), ((UnionTypeNode) right).candidates());
            return null;
          }

          @Override
          public Void visit(RecordTypeNode node) {
            assertThat(node.properties()).hasSize(((RecordTypeNode) right).properties().size());
            for (int i = 0; i < node.properties().size(); i++) {
              Property leftProp = node.properties().get(i);
              Property rightProp = ((RecordTypeNode) right).properties().get(i);
              assertThat(leftProp.name()).isEqualTo(rightProp.name());
              assertEquals(leftProp.type(), rightProp.type());
            }
            return null;
          }
        });
  }

  private TypeNode parse(String typeString) {
    TemplateNode template =
        SoyFileSetParserBuilder.forTemplateContents(
                "{@param p : " + typeString + "}\n{$p ? 't' : 'f'}")
            .typeRegistry(new SoyTypeRegistry())
            .errorReporter(ErrorReporter.exploding()) // ignore parse errors
            .parse()
            .fileSet()
            .getChild(0)
            .getChild(0);
    HeaderParam param = (HeaderParam) Iterables.getOnlyElement(template.getAllParams());
    return param.getTypeNode();
  }
}


text:
using CoCSharp.Csv;
using NUnit.Framework;

namespace CoCSharp.Test.Csv
{
    [TestFixture]
    public class CsvDataColumnCollectionTests
    {
        private CsvDataTable _table;

        [SetUp]
        public void Setup()
        {
            _table = new CsvDataTable<TestData>();
        }

        [Test]
        public void Add_Column_DataLevel_IsUpdated()
        {
            var column = new CsvDataColumn();
            Assert.Null(column.Table);
            Assert.AreEqual(-1, column.DataLevel);

            _table.Columns.Add(column);

            Assert.AreSame(column.Table, _table);
            Assert.AreEqual(0, column.DataLevel);
        }
    }
}


text:
import confluent.discovery.handlers.bmc as bmchandler
import pyghmi.exceptions as pygexc
import pyghmi.ipmi.private.util as pygutil
import string
import struct

class NodeHandler(bmchandler.NodeHandler):
    devname = 'IMM'

    @classmethod
    def adequate(cls, info):
        # We can sometimes receive a partially initialized SLP packet
        # This is not adequate for being satisfied
        return bool(info['attributes'])

    def scan(self):
        slpattrs = self.info.get('attributes', {})
        self.isdense = False
        try:
            ff = slpattrs.get('enclosure-form-factor', [''])[0]
        except IndexError:
            return
        wronguuid = slpattrs.get('node-uuid', [''])[0]
        if wronguuid:
            # we need to fix the first three portions of the uuid
            uuidprefix = wronguuid.split('-')[:3]
            uuidprefix = struct.pack(
                '<IHH', *[int(x, 16) for x in uuidprefix]).encode('hex')
            uuidprefix = uuidprefix[:8] + '-' + uuidprefix[8:12] + '-' + \
                         uuidprefix[12:16]
            self.info['uuid'] = uuidprefix + '-' + '-'.join(
                wronguuid.split('-')[3:])
            self.info['uuid'] = string.lower(self.info['uuid'])
        if ff not in ('dense-computing', 'BC2'):
            # do not probe unless it's a dense platform
            return
        self.isdense = True
        slot = int(slpattrs.get('slot', ['0'])[0])
        if slot != 0:
            self.info['enclosure.bay'] = slot

    def probe(self):
        if self.info.get('enclosure.bay', 0) == 0:
            self.scan()
        if self.info.get('enclosure.bay', 0) != 0:
            # scan has already populated info
            return
        ff = self.info.get('attributes', {}).get('enclosure-form-factor', '')
        if ff != 'dense-computing':
            return
        try:
            # we are a dense platform, but the SLP data did not give us slot
            # attempt to probe using IPMI
            ipmicmd = self._get_ipmicmd()
            guiddata = ipmicmd.xraw_command(netfn=6, command=8)
            self.info['uuid'] = pygutil.decode_wireformat_uuid(
                guiddata['data']).lower()
            ipmicmd.oem_init()
            bayid = ipmicmd._oem.immhandler.get_property(
                '/v2/cmm/sp/7')
            if not bayid:
                return
            self.info['enclosure.bay'] = int(bayid)
            smmid = ipmicmd._oem.immhandler.get_property(
                '/v2/ibmc/smm/chassis/uuid')
            if not smmid:
                return
            smmid = smmid.lower().replace(' ', '')
            smmid = '{0}-{1}-{2}-{3}-{4}'.format(smmid[:8], smmid[8:12],
                                                 smmid[12:16], smmid[16:20],
                                                 smmid[20:])
            self.info['enclosure.uuid'] = smmid
            self.info['enclosure.type'] = 'smm'
        except pygexc.IpmiException as ie:
            print(repr(ie))
            raise


text: default_app_config = 'children.apps.ChildConfig'


text:
var list = [
	{
		header: "Penal Code",
		featured: true,
		items: [{
			text: "Revised Penal Code of the Philippines",
			code: "Act No. 3815",
			file: "act3815",
			icon: "gavel"
		}]
	},
	{
		header: "Anti-Money Laundering",
		items: [{
			text: "Anti-Money Laundering Law of 2001",
			code: "Republic Act No. 9160",
			file: "ra9160",
			icon: "coin"
		}, {
			text: 'An Act Amending Republic Act No. 9160, Otherwise Known as the "Anti-Money Laundering Law of 2001"',
			code: "Republic Act No. 9194",
			file: "",
			icon: "coin"
		}, {
			text: 'The Rules and Regulations Implementing the Anti-Money Laundering Act of 2001',
			code: "Republic Act No. 9160",
			file: "",
			icon: "coin"
		}
		]
	},
	{
		header: "Anti-Rape",
		items: [{
			text: "The Anti-Rape Law of 1997",
			code: "Republic Act No. 8353",
			file: "ra8353",
			icon: "human-male-female"
		},
		{
			text: "Rape Victim Assistance and Protection Act of 1998",
			code: "Republic Act No. 8505",
			file: "",
			icon: "human-male-female"
		}
		]
	},
	{
		header: "Anti-Squatting",
		items: [{
			text: "The Anti-Squatting Law Repeal Act of 1997",
			code: "Republic Act No. 8368",
			file: "",
			icon: "pill"
		}]
	},
	{
		header: "Capital Punishment",
		items: [{
			text: 'An Act Designating Death by Lethal Injection as the Method of Carrying Out Capital Punishment, Amending for the Purpose Article 81 of the Revised Penal Code, As Amended by Section 24 of Republic Act No. 7659',
			code: "Republic Act No. 8177",
			file: "",
			icon: "pill"
		}]
	},
	{
		header: "Dangerous Drugs",
		items: [{
			text: "Comprehensive Dangerous Drugs Act of 2002",
			code: "Republic Act No. 9165",
			file: "",
			icon: "pill"
		}]
	},
	{
		header: "Illegal Firearms",
		items: [{
			text: 'An Act Amending the Provisions of P. D. No. 1866, Entitled "Codifying the Laws on Illegal/Unlawful Possession, Manufacture, Dealing In, Acquisition or Dispostion of Firearms, Ammunition or Explosives or Instruments Used in the Manufacture of Firearms, Ammunition or Explosives, and Imposing Stiffer Penalties for Certain Violations Thereof, and for Relevant Purposes"',
			code: "Republic Act No. 8294",
			file: "",
			icon: "pill"
		}]
	}
];


text:
package org.ocpsoft.rewrite.servlet.spi;

import org.ocpsoft.common.pattern.Weighted;

/**
 * SPI which is responsible to resolve the server-side target resource assigned to a given {@link Class}.
 *
 * @author Christian Kaltepoth
 * @author Lincoln Baxter, III
 */
public interface ResourcePathResolver extends Weighted
{
   /**
    * Resolve the server side target resource. This should return the path to the resource as it would be requested from
    * the client. E.g.: "/pages/index.xhtml".
    */
   String resolveFrom(Class<?> clazz);
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>Learning from life</title>
    <meta name="description" content="A blog by Álvaro Sánchez-Mariscal" />

    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="shortcut icon" href="//alvarosanchez.github.io/themes/Casper/favicon.ico">

    <link rel="stylesheet" type="text/css" href="//alvarosanchez.github.io/themes/Casper/assets/css/screen.css?v=1.0.0" />
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />

    <link rel="canonical" href="https://alvarosanchez.github.io" />
    <link rel="next" href="https://alvarosanchez.github.io/page/2/" />
    <meta name="generator" content="Ghost ?" />
    <link rel="alternate" type="application/rss+xml" title="Learning from life" href="https://alvarosanchez.github.io/rss" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/default.min.css">

Learning from life

A blog by Álvaro Sánchez-Mariscal

    Scroll Down

        Page 1 of 2
            Older Posts →

Roadmap of Spring Security plugins for Grails

Since I joined OCI I been helping to move forward with the Spring Security plugins for Grails. I was obviously already doing it with my Spring »

             on Grails
            <time class="post-date" datetime="2015-11-20">20 November 2015</time>

I'm joining the Grails team at OCI!

3 months ago I made public my new professional adventure, by joining a promising fintech company. However, once I arrived there, the situation was quite different »

             on Personal
            <time class="post-date" datetime="2015-10-22">22 October 2015</time>

JavaZone 2015 wrap-up

Last week I had the pleasure to represent 4finance IT speaking at JavaZone 2015. Despite of having spoken on 20+ conferences across 7 countries, this one »

             on Conferences,  JavaZone
            <time class="post-date" datetime="2015-09-16">16 September 2015</time>

I'm joining 4finance!

After 2.5 years working at Odobo, I felt like needing a change in my career. Fortunately, 4finance got on my way and we fell in »

             on Personal
            <time class="post-date" datetime="2015-06-29">29 June 2015</time>

#GeeCON 2015 wrap-up

Last week I had the pleasure to speak at and attend to the amazing GeeCON 2015 in Krakow, Poland. The venue Packed room for @rafaelcodes and »

             on Conferences,  GeeCON
            <time class="post-date" datetime="2015-05-20">20 May 2015</time>

        Page 1 of 2
            Older Posts →

Learning from life © 2015

Proudly published with HubPress


text:
#include "hedley.h"
#include "simde-common.h"
#include "simde-detect-clang.h"

#if !defined(SIMDE_FLOAT16_H)
#define SIMDE_FLOAT16_H

HEDLEY_DIAGNOSTIC_PUSH
SIMDE_DISABLE_UNWANTED_DIAGNOSTICS
SIMDE_BEGIN_DECLS_

/* Portable version which should work on pretty much any compiler.
 * Obviously you can't rely on compiler support for things like
 * conversion to/from 32-bit floats, so make sure you always use the
 * functions and macros in this file!
 *
 * The portable implementations are (heavily) based on CC0 code by
 * Fabian Giesen: <https://gist.github.com/rygorous/2156668> (see also
 * <https://fgiesen.wordpress.com/2012/03/28/half-to-float-done-quic/>).
 * I have basically just modified it to get rid of some UB (lots of
 * aliasing, right shifting a negative value), use fixed-width types,
 * and work in C. */
#define SIMDE_FLOAT16_API_PORTABLE 1
/* _Float16, per C standard (TS 18661-3;
 * <http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1945.pdf>). */
#define SIMDE_FLOAT16_API_FLOAT16 2
/* clang >= 6.0 supports __fp16 as an interchange format on all
 * targets, but only allows you to use them for arguments and return
 * values on targets which have defined an ABI.  We get around the
 * restriction by wrapping the __fp16 in a struct, but we can't do
 * that on Arm since it would break compatibility with the NEON F16
 * functions. */
#define SIMDE_FLOAT16_API_FP16_NO_ABI 3
/* This is basically __fp16 as specified by Arm, where arugments and
 * return values are raw __fp16 values not structs. */
#define SIMDE_FLOAT16_API_FP16 4

/* Choosing an implementation.  This is a bit rough, but I don't have
 * any ideas on how to improve it.  If you do, patches are definitely
 * welcome. */
#if !defined(SIMDE_FLOAT16_API)
  #if 0 && !defined(__cplusplus)
    /* I haven't found a way to detect this.  It seems like defining
    * __STDC_WANT_IEC_60559_TYPES_EXT__, then including float.h, then
    * checking for defined(FLT16_MAX) should work, but both gcc and
    * clang will define the constants even if _Float16 is not
    * supported.  Ideas welcome. */
    #define SIMDE_FLOAT16_API SIMDE_FLOAT16_API_FLOAT16
  #elif defined(__ARM_FP16_FORMAT_IEEE)
    #define SIMDE_FLOAT16_API SIMDE_FLOAT16_API_FP16
  #elif defined(__clang__) && defined(__FLT16_MIN__)
    #define SIMDE_FLOAT16_API SIMDE_FLOAT16_API_FP16_NO_ABI
  #else
    #define SIMDE_FLOAT16_API SIMDE_FLOAT16_API_PORTABLE
  #endif
#endif

#if SIMDE_FLOAT16_API == SIMDE_FLOAT16_API_FLOAT16
  typedef _Float16 simde_float16;
  #define SIMDE_FLOAT16_C(value) value##f16
#elif SIMDE_FLOAT16_API == SIMDE_FLOAT16_API_FP16_NO_ABI
  typedef struct { __fp16 value; } simde_float16;
  #define SIMDE_FLOAT16_C(value) ((simde_float16) { HEDLEY_STATIC_CAST(__fp16, (value)) })
#elif SIMDE_FLOAT16_API == SIMDE_FLOAT16_API_FP16
  typedef __fp16 simde_float16;
  #define SIMDE_FLOAT16_C(value) HEDLEY_STATIC_CAST(__fp16, (value))
#elif SIMDE_FLOAT16_API == SIMDE_FLOAT16_API_PORTABLE
  typedef struct { uint16_t value; } simde_float16;
#else
  #error No 16-bit floating point API.
#endif

/* Reinterpret -- you *generally* shouldn't need these, they're really
 * intended for internal use.  However, on x86 half-precision floats
 * get stuffed into a __m128i/__m256i, so it may be useful. */

SIMDE_DEFINE_CONVERSION_FUNCTION_(simde_float16_as_uint16,      uint16_t, simde_float16)
SIMDE_DEFINE_CONVERSION_FUNCTION_(simde_uint16_as_float16, simde_float16,      uint16_t)

/* Conversion -- convert between single-precision and half-precision
 * floats. */

static HEDLEY_ALWAYS_INLINE HEDLEY_CONST
simde_float16
simde_float16_from_float32 (simde_float32 value) {
  simde_float16 res;

  #if \
      (SIMDE_FLOAT16_API == SIMDE_FLOAT16_API_FLOAT16) || \
      (SIMDE_FLOAT16_API == SIMDE_FLOAT16_API_FP16)
    res = HEDLEY_STATIC_CAST(simde_float16, value);
  #elif (SIMDE_FLOAT16_API == SIMDE_FLOAT16_API_FP16_NO_ABI)
    res.value = HEDLEY_STATIC_CAST(__fp16, value);
  #else
    /* This code is CC0, based heavily on code by Fabian Giesen. */
    uint32_t f32u = simde_float32_as_uint32(value);
    static const uint32_t f32u_infty = UINT32_C(255) << 23;
    static const uint32_t f16u_max = (UINT32_C(127) + UINT32_C(16)) << 23;
    static const uint32_t denorm_magic =
      ((UINT32_C(127) - UINT32_C(15)) + (UINT32_C(23) - UINT32_C(10)) + UINT32_C(1)) << 23;
    uint16_t f16u;

    uint32_t sign = f32u & (UINT32_C(1) << 31);
    f32u ^= sign;

   /* NOTE all the integer compares in this function cast the operands
    * to signed values to help compilers vectorize to SSE2, which lacks
    * unsigned comparison instructions.  This is fine since all
    * operands are below 0x80000000 (we clear the sign bit). */

    if (f32u > f16u_max) { /* result is Inf or NaN (all exponent bits set) */
      f16u = (f32u > f32u_infty) ?  UINT32_C(0x7e00) : UINT32_C(0x7c00); /* NaN->qNaN and Inf->Inf */
    } else { /* (De)normalized number or zero */
      if (f32u < (UINT32_C(113) << 23)) { /* resulting FP16 is subnormal or zero */
        /* use a magic value to align our 10 mantissa bits at the bottom of
        * the float. as long as FP addition is round-to-nearest-even this
        * just works. */
        f32u = simde_float32_as_uint32(simde_uint32_as_float32(f32u) + simde_uint32_as_float32(denorm_magic));

        /* and one integer subtract of the bias later, we have our final float! */
        f16u = HEDLEY_STATIC_CAST(uint16_t, f32u - denorm_magic);
      } else {
        uint32_t mant_odd = (f32u >> 13) & 1;

        /* update exponent, rounding bias part 1 */
        f32u += (HEDLEY_STATIC_CAST(uint32_t, 15 - 127) << 23) + UINT32_C(0xfff);
        /* rounding bias part 2 */
        f32u += mant_odd;
        /* take the bits! */
        f16u = HEDLEY_STATIC_CAST(uint16_t, f32u >> 13);
      }
    }

    f16u |= sign >> 16;
    res = simde_uint16_as_float16(f16u);
  #endif

  return res;
}

static HEDLEY_ALWAYS_INLINE HEDLEY_CONST
simde_float32
simde_float16_to_float32 (simde_float16 value) {
  simde_float32 res;

  #if defined(SIMDE_FLOAT16_FLOAT16) || defined(SIMDE_FLOAT16_FP16)
    res = HEDLEY_STATIC_CAST(simde_float32, value);
  #else
    /* This code is CC0, based heavily on code by Fabian Giesen. */
    uint16_t half = simde_float16_as_uint16(value);
    const simde_float32 denorm_magic = simde_uint32_as_float32((UINT32_C(113) << 23));
    const uint32_t shifted_exp = UINT32_C(0x7c00) << 13; /* exponent mask after shift */
    uint32_t f32u;

    f32u = (half & UINT32_C(0x7fff)) << 13; /* exponent/mantissa bits */
    uint32_t exp = shifted_exp & f32u; /* just the exponent */
    f32u += (UINT32_C(127) - UINT32_C(15)) << 23; /* exponent adjust */

    /* handle exponent special cases */
    if (exp == shifted_exp) /* Inf/NaN? */
      f32u += (UINT32_C(128) - UINT32_C(16)) << 23; /* extra exp adjust */
    else if (exp == 0) { /* Zero/Denormal? */
      f32u += (1) << 23; /* extra exp adjust */
      f32u = simde_float32_as_uint32(simde_uint32_as_float32(f32u) - denorm_magic); /* renormalize */
    }

    f32u |= (half & UINT32_C(0x8000)) << 16; /* sign bit */
    res = simde_uint32_as_float32(f32u);
  #endif

  return res;
}

#if !defined(SIMDE_FLOAT16_C)
  #define SIMDE_FLOAT16_C(value) simde_float16_from_float32(SIMDE_FLOAT32_C(value))
#endif

SIMDE_END_DECLS_
HEDLEY_DIAGNOSTIC_POP

#endif /* !defined(SIMDE_FLOAT16_H) */


text:
using namespace boost::python;
using namespace Gaffer;
using namespace Gaffer::MetadataAlgo;

namespace
{

// Read only
// =========

void setReadOnlyWrapper( GraphComponent &graphComponent, bool readOnly, bool persistent )
{
	IECorePython::ScopedGILRelease gilRelease;
	setReadOnly( &graphComponent, readOnly, persistent );
}

void setChildNodesAreReadOnlyWrapper( Node &node, bool readOnly, bool persistent )
{
	IECorePython::ScopedGILRelease gilRelease;
	setChildNodesAreReadOnly( &node, readOnly, persistent );
}

bool readOnlyWrapper( GraphComponent &g )
{
	return readOnly( &g );
}

GraphComponentPtr readOnlyReasonWrapper( GraphComponent &g )
{
	return const_cast<GraphComponent *>( readOnlyReason( &g ) );
}

// Bookmarks
// =========

void setBookmarkedWrapper( Node &node, bool bookmarked, bool persistent )
{
	IECorePython::ScopedGILRelease gilRelease;
	setBookmarked( &node, bookmarked, persistent );
}

boost::python::list bookmarksWrapper( const Node *node )
{
	std::vector<NodePtr> bookmarks;
	MetadataAlgo::bookmarks( node, bookmarks );

	boost::python::list result;
	for( std::vector<NodePtr>::const_iterator it = bookmarks.begin(), endIt = bookmarks.end(); it != endIt; ++it )
	{
		result.append( *it );
	}

	return result;
}

void setNumericBookmarkWrapper( ScriptNode &scriptNode, int bookmark, NodePtr node )
{
	IECorePython::ScopedGILRelease gilRelease;
	setNumericBookmark( &scriptNode, bookmark, node.get() );
}

NodePtr getNumericBookmarkWrapper( ScriptNode &scriptNode, int bookmark )
{
	return getNumericBookmark( &scriptNode, bookmark );
}

// Annotations
// ===========

void addAnnotationWrapper( Node &node, const std::string &name, const Annotation &annotation, bool persistent )
{
	IECorePython::ScopedGILRelease gilRelease;
	addAnnotation( &node, name, annotation, persistent );
}

object getAnnotationWrapper( const Node &node, const std::string &name, bool inheritTemplate )
{
	Annotation a = getAnnotation( &node, name, inheritTemplate );
	return a ? object( a ) : object();
}

void removeAnnotationWrapper( Node &node, const std::string &name )
{
	IECorePython::ScopedGILRelease gilRelease;
	removeAnnotation( &node, name );
}

list annotationsWrapper( const Node &node )
{
	std::vector<std::string> names;
	annotations( &node, names );
	list result;
	for( const auto &n : names )
	{
		result.append( n );
	}
	return result;
}

object getAnnotationTemplateWrapper( const std::string &name )
{
	Annotation a = getAnnotationTemplate( name );
	return a ? object( a ) : object();
}

list annotationTemplatesWrapper( bool userOnly )
{
	std::vector<std::string> names;
	annotationTemplates( names, userOnly );
	list result;
	for( const auto &n : names )
	{
		result.append( n );
	}
	return result;
}

// Copying
// =======

void deprecatedCopyWrapper( const GraphComponent &from, GraphComponent &to, const IECore::StringAlgo::MatchPattern &exclude, bool persistentOnly, bool persistent )
{
	IECorePython::ScopedGILRelease gilRelease;
	copy( &from, &to, exclude, persistentOnly, persistent );
}

void copyWrapper( const GraphComponent &from, GraphComponent &to, bool persistent )
{
	IECorePython::ScopedGILRelease gilRelease;
	copy( &from, &to, persistent );
}

void copyIfWrapper( const GraphComponent &from, GraphComponent &to, object predicate, bool persistent )
{
	IECorePython::ScopedGILRelease gilRelease;
	copyIf(
		&from, &to,
		[&predicate] ( const GraphComponent *from, const GraphComponent *to, IECore::InternedString name ) {
			IECorePython::ScopedGILLock gilLock;
			return (bool)predicate(
				GraphComponentPtr( const_cast<GraphComponent *>( from ) ),
				GraphComponentPtr( const_cast<GraphComponent *>( to ) ),
				name.string()
			);
		},
		persistent
	);
}

void copyColorsWrapper( const Gaffer::Plug &srcPlug, Gaffer::Plug &dstPlug, bool overwrite )
{
	IECorePython::ScopedGILRelease gilRelease;
	copyColors( &srcPlug, &dstPlug, overwrite );
}

// Promotability
// =============

bool isPromotableWrapper( const GraphComponent &from, const GraphComponent &to, const IECore::InternedString &name )
{
	IECorePython::ScopedGILRelease gilRelease;
	return isPromotable( &from, &to, name );
}

} // namespace

void GafferModule::bindMetadataAlgo()
{
	object module( borrowed( PyImport_AddModule( "Gaffer.MetadataAlgo" ) ) );
	scope().attr( "MetadataAlgo" ) = module;
	scope moduleScope( module );

	// Read only
	// =========

	def( "setReadOnly", &setReadOnlyWrapper, ( arg( "graphComponent" ), arg( "readOnly"), arg( "persistent" ) = true ) );
	def( "getReadOnly", &getReadOnly );
	def( "setChildNodesAreReadOnly", &setChildNodesAreReadOnlyWrapper, ( arg( "node" ), arg( "readOnly"), arg( "persistent" ) = true ) );
	def( "getChildNodesAreReadOnly", &getChildNodesAreReadOnly );
	def( "readOnly", &readOnlyWrapper );
	def( "readOnlyReason", &readOnlyReasonWrapper );
	def(
		"readOnlyAffectedByChange",
		(bool (*)( const GraphComponent *, IECore::TypeId, const IECore::StringAlgo::MatchPattern &, const IECore::InternedString &, const Gaffer::Plug * ))&readOnlyAffectedByChange,
		( arg( "graphComponent" ), arg( "changedNodeTypeId"), arg( "changedPlugPath" ), arg( "changedKey" ), arg( "changedPlug" ) )
	);
	def(
		"readOnlyAffectedByChange",
		(bool (*)( const GraphComponent *, IECore::TypeId, const IECore::InternedString &, const Gaffer::Node * ))&readOnlyAffectedByChange,
		( arg( "graphComponent" ), arg( "changedNodeTypeId"), arg( "changedKey" ), arg( "changedNode" ) )
	);
	def(
		"readOnlyAffectedByChange",
		(bool (*)( const GraphComponent *, const GraphComponent *, const IECore::InternedString & ))&readOnlyAffectedByChange,
		( arg( "graphComponent" ), arg( "changedGraphComponent"), arg( "changedKey" ) )
	);
	def(
		"readOnlyAffectedByChange",
		(bool (*)( const IECore::InternedString & ))&readOnlyAffectedByChange,
		( arg( "changedKey" ) )
	);

	// Bookmarks
	// =========

	def( "setBookmarked", &setBookmarkedWrapper, ( arg( "graphComponent" ), arg( "bookmarked"), arg( "persistent" ) = true ) );
	def( "getBookmarked", &getBookmarked );
	def( "bookmarkedAffectedByChange", &bookmarkedAffectedByChange );
	def( "bookmarks", &bookmarksWrapper );

	def( "setNumericBookmark", &setNumericBookmarkWrapper, ( arg( "scriptNode" ), arg( "bookmark" ), arg( "node" ) ) );
	def( "getNumericBookmark", &getNumericBookmarkWrapper, ( arg( "scriptNode" ), arg( "bookmark" ) ) );
	def( "numericBookmark", &numericBookmark, ( arg( "node" ) ) );
	def( "numericBookmarkAffectedByChange", &numericBookmarkAffectedByChange, ( arg( "changedKey" ) ) );

	// Annotations
	// ===========

	class_<Annotation>( "Annotation" )
		.def( init<const std::string &>( arg( "text" ) ) )
		.def( init<const std::string &, const Imath::Color3f &>( ( arg( "text" ), arg( "color" ) ) ) )
		.def( "text", &Annotation::text, return_value_policy<copy_const_reference>() )
		.def( "color", &Annotation::color, return_value_policy<copy_const_reference>() )
		.def( self == self )
		.def( self != self )
		.def( !self )
	;

	def( "addAnnotation", &addAnnotationWrapper, ( arg( "node" ), arg( "name" ), arg( "annotation" ), arg( "persistent" ) = true ) );
	def( "getAnnotation", &getAnnotationWrapper, ( arg( "node" ), arg( "name" ), arg( "inheritTemplate" ) = false ) );
	def( "removeAnnotation", &removeAnnotationWrapper, ( arg( "node" ), arg( "name" ) ) );
	def( "annotations", &annotationsWrapper, ( arg( "node" ) ) );

	def( "addAnnotationTemplate", &addAnnotationTemplate, ( arg( "name" ), arg( "annotation" ), arg( "user" ) = true ) );
	def( "getAnnotationTemplate", &getAnnotationTemplateWrapper, ( arg( "name" ) ) );
	def( "removeAnnotationTemplate", &removeAnnotationTemplate, arg( "name" ) );
	def( "annotationTemplates", &annotationTemplatesWrapper, arg( "userOnly" ) = false );

	def( "annotationsAffectedByChange", &annotationsAffectedByChange, ( arg( "changedKey" ) ) );

	// Change queries
	// ==============

	def(
		"affectedByChange",
		(bool (*)( const Plug *, IECore::TypeId, const IECore::StringAlgo::MatchPattern &, const Plug * ))&affectedByChange,
		( arg( "plug" ), arg( "changedNodeTypeId"), arg( "changedPlugPath" ), arg( "changedPlug" ) )
	);
	def(
		"affectedByChange",
		(bool (*)( const Node *node, IECore::TypeId changedNodeTypeId, const Node *changedNode ))&affectedByChange,
		( arg( "node" ), arg( "changedNodeTypeId"), arg( "changedNode" ) )
	);

	def(
		"childAffectedByChange",
		(bool (*)( const GraphComponent *, IECore::TypeId, const IECore::StringAlgo::MatchPattern &, const Gaffer::Plug * ))&childAffectedByChange,
		( arg( "parent" ), arg( "changedNodeTypeId"), arg( "changedPlugPath" ), arg( "changedPlug" ) )
	);
	def(
		"childAffectedByChange",
		(bool (*)( const GraphComponent *, IECore::TypeId, const Gaffer::Node * ))&childAffectedByChange,
		( arg( "parent" ), arg( "changedNodeTypeId"), arg( "changedNode" ) )
	);

	def(
		"ancestorAffectedByChange",
		(bool (*)( const Plug *, IECore::TypeId, const IECore::StringAlgo::MatchPattern &, const Gaffer::Plug * ))&ancestorAffectedByChange,
		( arg( "plug" ), arg( "changedNodeTypeId"), arg( "changedPlugPath" ), arg( "changedPlug" ) )
	);

	def(
		"ancestorAffectedByChange",
		(bool (*)( const GraphComponent *, IECore::TypeId, const Gaffer::Node * ))&ancestorAffectedByChange,
		( arg( "graphComponent" ), arg( "changedNodeTypeId"), arg( "changedNode" ) )
	);

	// Copying
	// =======

	def( "copy", &deprecatedCopyWrapper, ( arg( "from" ), arg( "to" ), arg( "exclude" ) = "", arg( "persistentOnly" ) = true, arg( "persistent" ) = true ) );
	def( "copy", &copyWrapper, ( arg( "from" ), arg( "to" ), arg( "persistent" ) ) );
	def( "copyIf", &copyIfWrapper, ( arg( "from" ), arg( "to" ), arg( "predicate" ), arg( "persistent" ) = true ) );

	def( "copyColors", &copyColorsWrapper,  (arg( "srcPlug" ), arg( "dstPlug" ), arg( "overwrite") ));

	// Promotability
	// =============

	def( "isPromotable", &isPromotableWrapper, ( arg( "from" ), arg( "to" ), arg( "name" ) ) );

}


text:
package cc.event;

import cc.terminal.MonitorTerminal;
import cc.peripheral.PeripheralNotFoundException;

public abstract class MonitorEvent {
    public final String side;

    public MonitorEvent(String side) {
        this.side = side;
    }

    public static class MonitorTouchEvent extends MonitorEvent {
        public final int x, y;

        public MonitorTouchEvent(String side, int x, int y) {
            super(side);
            this.x = x;
            this.y = y;
        }
    }

    public static class MonitorResizeEvent extends MonitorEvent {
        public final int newWidth, newHeight;

        public MonitorResizeEvent(String side) throws PeripheralNotFoundException {
            super(side);

            MonitorTerminal t = new MonitorTerminal(side);
            newWidth = t.width();
            newHeight = t.height();
        }
    }
}


text:
package br.com.posterocompany.memo.models;

import com.orm.SugarRecord;

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

/**
 * Created by Francisco on 12/03/2016.
 */
public class Note extends SugarRecord implements Serializable{

    public String text;
    public Date dateCreate;
    public Date dateSave;

    public Note() {

    }

    public List<NoteUpdate> getUpdates() {
        List<NoteUpdate> updates = NoteUpdate.find(NoteUpdate.class, "note = ?", this.getId().toString());
        NoteUpdate update = new NoteUpdate();
        update.oldText = "";
        update.dateCreate = this.dateCreate;

        if(updates.size() > 0){
            NoteUpdate firstUpdate = updates.get(0);
            update.newText = firstUpdate.oldText;
            update.dateUpdate = firstUpdate.dateCreate;
        }
        else {
            update.newText = this.text;
            update.dateUpdate = this.dateSave;
        }

        updates.add(0,update);

        return updates;
    }

    public static List<Note> listAllOrdered(){
        return Note.find(Note.class, "", null, "", "id desc", "");
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Vertical linear layout <1> -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_height="wrap_content" android:orientation="horizontal"
  android:layout_width="fill_parent">
    <TextView android:layout_height="fill_parent"
      android:layout_width="fill_parent"
      android:id="@+id/playerListPlayerName"
      android:paddingLeft="0sp"
      android:paddingRight="12sp"
      android:paddingStart="0sp"
      android:paddingEnd="12sp"
      android:textSize="20sp"/>

</LinearLayout>


text:
require 'rake'
require 'rspec/core/rake_task'

desc "Bring up Vagrant VM"
task :up do
  if ENV['ANSIBLE_ETCKEEPER_VAGRANT_PROVIDER']
    sh 'vagrant', 'up', '--no-provision', '--provider', ENV['ANSIBLE_ETCKEEPER_VAGRANT_PROVIDER']
  else
    sh %{vagrant up --no-provision}
  end
end

desc "Provision Vagrant VM"
task :provision => [:up] do
  sh %{vagrant provision}
end

desc "Cleanup Vagrant VM environment"
task :clean do
  if not ENV['RAKE_ANSIBLE_VAGRANT_DONT_CLEANUP'] == '1'
    sh %{vagrant halt}
    sh %{vagrant destroy --force}
  end
end

desc "SSH into the Vagrant VM"
task :ssh do
  sh %{vagrant ssh}
end


text:
package ioio.lib.android.accessory;

import ioio.lib.android.accessory.Adapter.UsbAccessoryInterface;
import ioio.lib.api.IOIOConnection;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.impl.FixedReadBufferedInputStream;
import ioio.lib.spi.IOIOConnectionBootstrap;
import ioio.lib.spi.IOIOConnectionFactory;
import ioio.lib.spi.NoRuntimeSupportException;
import ioio.lib.util.android.ContextWrapperDependent;

import java.io.BufferedOutputStream;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.ParcelFileDescriptor;
import android.util.Log;

public class AccessoryConnectionBootstrap extends BroadcastReceiver implements
		ContextWrapperDependent, IOIOConnectionBootstrap, IOIOConnectionFactory {
	private static final String ACTION_USB_PERMISSION = "ioio.lib.accessory.action.USB_PERMISSION";
	private static final String TAG = "AccessoryIOIOConnection";

	private enum State {
		CLOSED, WAIT_PERMISSION, OPEN
	}

	private enum InstanceState {
		INIT, CONNECTED, DEAD
	};

	private ContextWrapper activity_;
	private Adapter adapter_;
	private Adapter.AbstractUsbManager usbManager_;
	private Adapter.UsbAccessoryInterface accessory_;
	private State state_ = State.CLOSED;
	private PendingIntent pendingIntent_;
	private ParcelFileDescriptor fileDescriptor_;
	private InputStream inputStream_;
	private OutputStream outputStream_;

	public AccessoryConnectionBootstrap() throws NoRuntimeSupportException {
		adapter_ = new Adapter();
	}

	@Override
	public void onCreate(ContextWrapper wrapper) {
		activity_ = wrapper;
		usbManager_ = adapter_.getManager(wrapper);
		registerReceiver();
	}

	@Override
	public void onDestroy() {
		unregisterReceiver();
	}

	@Override
	public synchronized void open() {
		if (state_ != State.CLOSED) {
			return;
		}
		UsbAccessoryInterface[] accessories = usbManager_.getAccessoryList();
		accessory_ = (accessories == null ? null : accessories[0]);
		if (accessory_ != null) {
			if (usbManager_.hasPermission(accessory_)) {
				openStreams();
			} else {
				pendingIntent_ = PendingIntent.getBroadcast(activity_, 0, new Intent(
						ACTION_USB_PERMISSION), 0);
				usbManager_.requestPermission(accessory_, pendingIntent_);
				setState(State.WAIT_PERMISSION);
			}
		} else {
			Log.d(TAG, "No accessory found.");
		}
	}

	@Override
	public void reopen() {
		open();
	}

	@Override
	public synchronized void close() {
		if (state_ == State.OPEN) {
			closeStreams();
		} else if (state_ == State.WAIT_PERMISSION) {
			pendingIntent_.cancel();
		}
		setState(State.CLOSED);
	}

	@Override
	public IOIOConnection createConnection() {
		return new Connection();
	}

	private void registerReceiver() {
		IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
		filter.addAction(usbManager_.ACTION_USB_ACCESSORY_DETACHED);
		// filter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
		activity_.registerReceiver(this, filter);
	}

	private void unregisterReceiver() {
		activity_.unregisterReceiver(this);
	}

	private void openStreams() {
		try {
			fileDescriptor_ = usbManager_.openAccessory(accessory_);
			if (fileDescriptor_ != null) {
				FileDescriptor fd = fileDescriptor_.getFileDescriptor();
				inputStream_ = new FileInputStream(fd);
				outputStream_ = new FileOutputStream(fd);
				setState(State.OPEN);
			} else {
				throw new IOException("Failed to open file descriptor");
			}
		} catch (IOException e) {
			Log.e(TAG, "Failed to open streams", e);
			setState(State.CLOSED);
		}
	}

	private void closeStreams() {
		try {
			fileDescriptor_.close();
		} catch (IOException e) {
			Log.e(TAG, "Failed to proprly close accessory", e);
		}
	}

	@Override
	public synchronized void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		if (usbManager_.ACTION_USB_ACCESSORY_DETACHED.equals(action)) {
			close();
			// } else if
			// (UsbManager.ACTION_USB_ACCESSORY_ATTACHED.equals(action)) {
			// open();
		} else if (ACTION_USB_PERMISSION.equals(action)) {
			if (intent.getBooleanExtra(usbManager_.EXTRA_PERMISSION_GRANTED, false)) {
				openStreams();
			} else {
				Log.e(TAG, "Permission denied");
				setState(State.CLOSED);
			}
		}
	}

	private void setState(State state) {
		state_ = state;
		notifyAll();
	}

	private class Connection implements IOIOConnection {
		private InstanceState instanceState_ = InstanceState.INIT;
		private InputStream localInputStream_;
		private OutputStream localOutputStream_;

		@Override
		public InputStream getInputStream() throws ConnectionLostException {
			return localInputStream_;
		}

		@Override
		public OutputStream getOutputStream() throws ConnectionLostException {
			return localOutputStream_;
		}

		@Override
		public boolean canClose() {
			return false;
		}

		@Override
		public void waitForConnect() throws ConnectionLostException {
			synchronized (AccessoryConnectionBootstrap.this) {
				if (instanceState_ != InstanceState.INIT) {
					throw new IllegalStateException("waitForConnect() may only be called once");
				}
				while (instanceState_ != InstanceState.DEAD && state_ != State.OPEN) {
					try {
						AccessoryConnectionBootstrap.this.wait();
					} catch (InterruptedException e) {
					}
				}
				if (instanceState_ == InstanceState.DEAD) {
					throw new ConnectionLostException();
				}
				// Apparently, some Android devices (e.g. Nexus 5) only support read operations of
				// multiples of the endpoint buffer size. So there you have it!
				localInputStream_ = new FixedReadBufferedInputStream(inputStream_, 1024);
				localOutputStream_ = new BufferedOutputStream(outputStream_, 1024);
			}
			try {
				while (instanceState_ != InstanceState.CONNECTED) {
					if (instanceState_ == InstanceState.DEAD || state_ != State.OPEN) {
						throw new ConnectionLostException();
					}
					// Soft-open the connection
					localOutputStream_.write(0x00);
					localOutputStream_.flush();
					// We're going to block now. We're counting on the IOIO to
					// write back a byte, or otherwise we're locked until
					// physical disconnection. This is a known OpenAccessory
					// bug:
					// http://code.google.com/p/android/issues/detail?id=20545
					if (localInputStream_.read() == 1) {
						instanceState_ = InstanceState.CONNECTED;
					} else {
						trySleep(1000);
					}
				}
			} catch (IOException e) {
				instanceState_ = InstanceState.DEAD;
				// It takes some time between the physical disconnection of
				// an accessory to when it is actually removed from the
				// list and reported to be detached. To avoid thrashing
				// during this period, we sleep after an IOException.
				trySleep(1000);
				throw new ConnectionLostException();
			}
		}

		@Override
		public void disconnect() {
			synchronized (AccessoryConnectionBootstrap.this) {
				instanceState_ = InstanceState.DEAD;
				AccessoryConnectionBootstrap.this.notifyAll();
			}
		}

		private void trySleep(long time) {
			synchronized (AccessoryConnectionBootstrap.this) {
				try {
					AccessoryConnectionBootstrap.this.wait(time);
				} catch (InterruptedException e) {
				}
			}
		}
	}

	@Override
	public void getFactories(Collection<IOIOConnectionFactory> result) {
		result.add(this);
	}

	@Override
	public String getType() {
		return Connection.class.getCanonicalName();
	}

	@Override
	public Object getExtra() {
		return null;
	}
}


text:
from unittest import TestCase
from condorpy import Job, DAG, Node, Templates
import os
import pickle

__author__ = 'sdc50'

class TestTemplates(TestCase):

    def setUp(self):
        Templates.reset()
        self.default_save_location = os.path.join(os.path.dirname(__file__), '../condorpy/condorpy-saved-templates')
        self.custom_save_location = 'saved-templates'

    def tearDown(self):
        for file in (self.custom_save_location, self.default_save_location):
            if os.path.isfile(file):
                os.remove(file)

    def test__init__(self):
        pass

    def test__str__(self):
        pass

    def test__repr__(self):
        pass

    def test___getattribute__(self):
        custom = dict(key='value')
        Templates.custom = custom
        new = Templates.custom
        self.assertIsNot(custom, new)

    def test_save(self):
        file_name = self.default_save_location
        Templates.save()
        with open(file_name, 'rb') as file:
            pdict = pickle.load(file)
        expected = {}
        actual = pdict
        msg = 'testing saving with empty dict'
        self.assertEqual(expected, actual, '%s\nExpected: %s\nActual:   %s\n' % (msg, expected, actual))

        file_name = self.custom_save_location
        Templates.save(file_name)
        with open(file_name, 'rb') as file:
            pdict = pickle.load(file)
        expected = {}
        actual = pdict
        msg = 'testing saving with empty dict to custom location'
        self.assertEqual(expected, actual, '%s\nExpected: %s\nActual:   %s\n' % (msg, expected, actual))

        file_name = self.default_save_location
        self.test___getattribute__()
        Templates.save()
        with open(file_name, 'rb') as file:
            pdict = pickle.load(file)
        expected = {'custom': {'key': 'value'}}
        actual = pdict
        msg = 'testing saving with custom template added'
        self.assertEqual(expected, actual, '%s\nExpected: %s\nActual:   %s\n' % (msg, expected, actual))

    def test_load(self):
        self.test___getattribute__()
        Templates.save()
        expected = Templates.__dict__
        Templates.reset()
        Templates.load()
        actual = Templates.__dict__
        msg = 'testing loading with custom template added'
        self.assertEqual(expected, actual, '%s\nExpected: %s\nActual:   %s\n' % (msg, expected, actual))


text:
package com.microsoft.azure.management.batchai.v2018_05_01;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Caffe2 job settings.
 */
public class Caffe2Settings {
    /**
     * Python script file path.
     * The python script to execute.
     */
    @JsonProperty(value = "pythonScriptFilePath", required = true)
    private String pythonScriptFilePath;

    /**
     * Python interpreter path.
     * The path to the Python interpreter.
     */
    @JsonProperty(value = "pythonInterpreterPath")
    private String pythonInterpreterPath;

    /**
     * Command line arguments.
     * Command line arguments that need to be passed to the python script.
     */
    @JsonProperty(value = "commandLineArgs")
    private String commandLineArgs;

    /**
     * Get the python script to execute.
     *
     * @return the pythonScriptFilePath value
     */
    public String pythonScriptFilePath() {
        return this.pythonScriptFilePath;
    }

    /**
     * Set the python script to execute.
     *
     * @param pythonScriptFilePath the pythonScriptFilePath value to set
     * @return the Caffe2Settings object itself.
     */
    public Caffe2Settings withPythonScriptFilePath(String pythonScriptFilePath) {
        this.pythonScriptFilePath = pythonScriptFilePath;
        return this;
    }

    /**
     * Get the path to the Python interpreter.
     *
     * @return the pythonInterpreterPath value
     */
    public String pythonInterpreterPath() {
        return this.pythonInterpreterPath;
    }

    /**
     * Set the path to the Python interpreter.
     *
     * @param pythonInterpreterPath the pythonInterpreterPath value to set
     * @return the Caffe2Settings object itself.
     */
    public Caffe2Settings withPythonInterpreterPath(String pythonInterpreterPath) {
        this.pythonInterpreterPath = pythonInterpreterPath;
        return this;
    }

    /**
     * Get command line arguments that need to be passed to the python script.
     *
     * @return the commandLineArgs value
     */
    public String commandLineArgs() {
        return this.commandLineArgs;
    }

    /**
     * Set command line arguments that need to be passed to the python script.
     *
     * @param commandLineArgs the commandLineArgs value to set
     * @return the Caffe2Settings object itself.
     */
    public Caffe2Settings withCommandLineArgs(String commandLineArgs) {
        this.commandLineArgs = commandLineArgs;
        return this;
    }

}


text:
<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>

<TemplateDefs>

<TemplateDef id='5' name='t5' file_path='t5.template'/>
<TemplateDef id='6' name='t6' file_path='t6.template'/>

</TemplateDefs>


text:
package space.gatt.GasaiBot.commands.Admin;

import com.google.common.base.Joiner;
import com.google.common.base.Throwables;
import de.btobastian.javacord.DiscordAPI;
import de.btobastian.javacord.entities.Channel;
import de.btobastian.javacord.entities.Server;
import de.btobastian.javacord.entities.User;
import de.btobastian.javacord.entities.message.Message;
import de.btobastian.javacord.entities.message.MessageBuilder;
import de.btobastian.javacord.entities.message.MessageDecoration;
import de.btobastian.javacord.entities.permissions.Role;
import javassist.*;
import space.gatt.JavacordCommander.Settings;
import space.gatt.JavacordCommander.annotations.*;

import java.lang.reflect.Method;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * Created by Zach G on 06-Apr-16.
 */

@Command("addrank")
@Syntax("addrank [rankname] @mentions")
@Usage("addrank Amazing_Owner @Gatt @Mitch")
@Permissions("Bot Commander")
@Description("Gives all users the rank.")
@Group("Admin")
@CommandSettings(deleteInitatingMsg = true, sendResponseViaPM = false)
public class AddRank {
	@IMethod
	public static String command(final DiscordAPI discordAPI, Message message, User user, String[] args) {
	  if (message.getMentions().size() > 0){
  		String name = args[0].replaceAll("_", " ");
  		name = name.trim().toLowerCase();
  		Role r = getRole(name, message.getChannelReceiver().getServer());
  		if (r != null) {
  			try {
  				Message msg = message.reply("Adding the `" + r.getName() + "` role to " + message.getMentions().size() + " users.").get();
  				int id = 0;
  				for (User u : message.getMentions()){
  					id++;
  					try{
  						Exception e = r.addUser(u).get();
  						if (e != null){
  						return sendStack(e, message);
  						}
  					}catch (Exception e){
		  				return sendStack(e, message);
		  			}
  				}
  				return Settings.getMsgStarter() + "Added the `" + r.getName() + "` rank to " + message.getMentions().size() + " users.";
  			}catch (Exception e){
  				return sendStack(e, message);
  			}
  		}else{
  			return Settings.getMsgStarter() + "Couldn't find that rank!";
  		}
	}else{
		return Settings.getMsgStarter() + "Couldn't find any users!";
	}
	}

	private static Role getRole(String role, Server s){
		for (Role r : s.getRoles()){
			if (r.getName().equalsIgnoreCase(role)){
				return r;
			}
		}
		return null;
	}

	private static String sendStack(Throwable e, Message message) {
		String stack = Throwables.getStackTraceAsString(e);
		if (stack.length() < 1989) {
			return "```\n" + stack + "\n```";
		}
		String[] split = stack.split("Caused by:");
		int i = 0;
		for (String piece : split) {
			try {
				message.reply("```\n" + (i++ > 0 ? "Caused by:" : "") + piece + "\n```").get();
			} catch (ExecutionException | InterruptedException ex) {
				ex.printStackTrace();
			}
		}
		return null;
	}

}


text:
package io.cattle.platform.process.network;

import io.cattle.platform.core.constants.AccountConstants;
import io.cattle.platform.core.constants.CommonStatesConstants;
import io.cattle.platform.core.constants.NetworkConstants;
import io.cattle.platform.core.dao.NetworkDao;
import io.cattle.platform.core.model.Account;
import io.cattle.platform.core.model.Network;
import io.cattle.platform.engine.handler.HandlerResult;
import io.cattle.platform.engine.process.ProcessInstance;
import io.cattle.platform.engine.process.ProcessState;
import io.cattle.platform.lock.LockCallbackNoReturn;
import io.cattle.platform.lock.LockManager;
import io.cattle.platform.process.common.handler.AbstractObjectProcessHandler;
import io.cattle.platform.process.lock.DefaultNetworkLock;

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

import org.apache.commons.lang3.ObjectUtils;

@Named
public class DefaultNetworkProcess extends AbstractObjectProcessHandler {

    @Inject
    NetworkDao networkDao;

    @Inject
    LockManager lockManager;

    @Override
    public HandlerResult handle(ProcessState state, ProcessInstance process) {
        final Network network = (Network)state.getResource();
        lockManager.lock(new DefaultNetworkLock(network), new LockCallbackNoReturn() {
            @Override
            public void doWithLockNoResult() {
                setDefaultNetwork(network.getAccountId());
            }
        });
        return null;
    }

    protected void setDefaultNetwork(Long accountId) {
        Account account = objectManager.loadResource(Account.class, accountId);
        if (account == null) {
            return;
        }

        Long defaultNetworkId = account.getDefaultNetworkId();
        Long newDefaultNetworkId = null;
        for (Network network : networkDao.getActiveNetworks(account.getId())) {
            if (network.getKind().startsWith(NetworkConstants.PREFIX_KIND_DOCKER) ||
                    network.getKind().equals("hostOnlyNetwork")) {
                continue;
            }

            if (network.getId().equals(defaultNetworkId)) {
                newDefaultNetworkId = defaultNetworkId;
                break;
            }

            if ((CommonStatesConstants.ACTIVATING.equals(network.getState()) ||
                    CommonStatesConstants.UPDATING_ACTIVE.equals(network.getState())) &&
                    newDefaultNetworkId == null) {
                newDefaultNetworkId = network.getId();
            } else if (CommonStatesConstants.ACTIVE.equals(network.getState())) {
                newDefaultNetworkId = network.getId();
            }
        }

        if (!ObjectUtils.equals(defaultNetworkId, newDefaultNetworkId)) {
            objectManager.setFields(account, AccountConstants.FIELD_DEFAULT_NETWORK_ID, newDefaultNetworkId);
        }
    }

    @Override
    public String[] getProcessNames() {
        return new String[] { "network.*" };
    }

}


text:
package f2utility.tools;

/**
 * Interface Tool stores the style for the border and defines all the needed methods
 *
 * @author Jelmerro
 */
public interface Tool {

    public String ACTIVATED = "-fx-border-color: #ADA;-fx-border-width: 2px;-fx-border-radius: 3px;";
    public String DEACTIVATED = "-fx-border-color: #bbb;-fx-border-width: 2px;-fx-border-radius: 3px;";

    /**
     * Renames the provided string using the tool it's capabilities
     *
     * @param name String
     * @return newName String
     */
    public String processName(String name);

    /**
     * Similar to the process of renaming, but changes the border accordingly
     */
    public void checkActive();

    /**
     * Activates the border/Colors the border green-ish
     */
    public void Activate();

    /**
     * Deactivates the border/Colors the border gray-ish
     */
    public void Deactivate();

    /**
     * Resets all the fields for the Tool and calls checkActive to style the border appropriately
     */
    public void Reset();
}


text:
<!DOCTYPE html>

    <title>Hashtag-Gangsta main page</title>
    <meta charset='utf-8'>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link rel="stylesheet" href="htdocs/bootstrap/css/bootstrap.min.css" type="text/css" >

настройки


text:
<?php
/**
 * The template for displaying Search Results pages.
 *
 * @package sparkling
 */

get_header(); ?>

		<?php
		if ( have_posts() ) : ?>

<?php printf( esc_html__( 'Search Results for: %s', 'sparkling' ), '' . get_search_query() . '' ); ?>

			<?php
			/* Start the Loop */
			while ( have_posts() ) : the_post();

				/**
				 * Run the loop for the search to output the results.
				 * If you want to overload this in a child theme then include a file
				 * called content-search.php and that will be used instead.
				 */
				get_template_part( 'template-parts/content', 'search' );

			endwhile;

			the_posts_pagination( array(
				'prev_text' => ' ' . __( 'Newer posts', 'sparkling' ),
				'next_text' => __( 'Older posts', 'sparkling' ) . ' ',
			) );

		else :

			get_template_part( 'template-parts/content', 'none' );

		endif; ?>

<?php
get_sidebar();
get_footer();


text:
<%#
 Copyright 2013-2017 the original author or authors from the StackStack project.

 This file is part of the StackStack project, see http://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>

    <%_ const keyPrefix = angularAppName + '.'+ entityTranslationKey + '.'; _%>

        <span jhiTranslate="<%= keyPrefix %>home.title"><%= entityClassPluralHumanized %>
        <button class="btn btn-primary float-right jh-create-entity create-<%= entityUrl %>" [routerLink]="['/', { outlets: { popup: ['<%= entityUrl %>-new'] } }]">

            <span <% if (searchEngine === 'elasticsearch') { %>class="hidden-sm-down" <% } %> jhiTranslate="<%= keyPrefix %>home.createLabel">
            Create new <%= entityClassHumanized %>

        </button>

    <<%=jhiPrefix%>-alert></<%=jhiPrefix%>-alert>

        <%_ if (searchEngine === 'elasticsearch') { _%>

            <form name="searchForm" class="form-inline">

                    <input type="text" class="form-control" [(ngModel)]="currentSearch" id="currentSearch" name="currentSearch" placeholder="<% if (enableTranslation) { %>{{ '<%= keyPrefix %>home.search' | translate }}<% } else { %>Query<% } %>">
                    <button class="input-group-addon btn btn-info" (click)="search(currentSearch)">

                    </button>
                    <button class="input-group-addon btn btn-danger" (click)="clear()" *ngIf="currentSearch">

                    </button>

            </form>

        <%_ } _%>

    <div class="table-responsive" *ngIf="<%=entityInstancePlural %>">

            <tr<% if (pagination !== 'no') { %> jhiSort [(predicate)]="predicate" [(ascending)]="reverse" [callback]="<%=pagination !== 'infinite-scroll' ? 'transition.bind(this)' : 'reset.bind(this)'%>"<% } %>>
            <th<% if (pagination !== 'no') { %> jhiSortBy="id"<% } %>>ID<% if (pagination !== 'no') { %> <% } %>
            <%_ for (idx in fields) { _%>
            <th<% if (pagination !== 'no') { %> jhiSortBy="<%= fields[idx].fieldName%>"<% } %>><span jhiTranslate="<%=keyPrefix + fields[idx].fieldName %>"><%= fields[idx].fieldNameHumanized %><% if (pagination !== 'no') { %> <% } %>
            <%_ } _%>
            <%_ for (idx in relationships) { _%>
            <%_ if (relationships[idx].relationshipType === 'many-to-one'
            || (relationships[idx].relationshipType === 'one-to-one' && relationships[idx].ownerSide === true)
            || (relationships[idx].relationshipType === 'many-to-many' && relationships[idx].ownerSide === true && pagination === 'no')) {
            const fieldName = dto === 'no' ? "." + relationships[idx].otherEntityField : relationships[idx].otherEntityFieldCapitalized;_%>
            <th<% if (pagination !== 'no') { %> jhiSortBy="<%=relationships[idx].relationshipName + (fieldName)%>"<% } %>><span jhiTranslate="<%= keyPrefix + relationships[idx].relationshipName%>"><%= relationships[idx].relationshipNameHumanized %><% if (pagination !== 'no') { %> <% } %>
            <%_ } _%>
            <%_ } _%>

            <tbody<% if (pagination === 'infinite-scroll') { %> infinite-scroll (scrolled)="loadPage(page + 1)" [infiniteScrollDisabled]="page >= links['last']" [infiniteScrollDistance]="0"<% } %>>
            <tr *ngFor="let <%=entityInstance %> of <%=entityInstancePlural %> ;trackBy: trackId">
                <a [routerLink]="['../<%= entityUrl %>', <%= entityInstance %>.id ]">{{<%=entityInstance %>.id}}
                <%_ for (idx in fields) {
                const fieldName = fields[idx].fieldName;
                const fieldNameCapitalized = fields[idx].fieldNameCapitalized;
                const fieldType = fields[idx].fieldType;
                const fieldTypeBlobContent = fields[idx].fieldTypeBlobContent; _%>
                <%_ if (['byte[]', 'ByteBuffer'].includes(fieldType) && fieldTypeBlobContent === 'image') { _%>

                    <a *ngIf="<%= entityInstance %>.<%= fieldName %>" (click)="openFile(<%= entityInstance %>.<%= fieldName %>ContentType, <%= entityInstance %>.<%= fieldName %>)">
                        <img [src]="'data:' + <%=entityInstance %>.<%=fieldName%>ContentType + ';base64,' + <%=entityInstance %>.<%=fieldName%>" style="max-height: 30px;" alt="<%=entityInstance %> image"/>

                    <span *ngIf="<%= entityInstance %>.<%= fieldName %>">{{<%= entityInstance %>.<%= fieldName %>ContentType}}, {{byteSize(<%= entityInstance %>.<%= fieldName %>)}}

                <%_ } else if (['byte[]', 'ByteBuffer'].includes(fieldType) && fieldTypeBlobContent === 'any') { _%>

                    <a *ngIf="<%= entityInstance %>.<%= fieldName %>" (click)="openFile(<%= entityInstance %>.<%= fieldName %>ContentType, <%= entityInstance %>.<%= fieldName %>)" jhiTranslate="entity.action.open">open
                    <span *ngIf="<%= entityInstance %>.<%= fieldName %>">{{<%= entityInstance %>.<%= fieldName %>ContentType}}, {{byteSize(<%= entityInstance %>.<%= fieldName %>)}}

                <%_ } else if (fields[idx].fieldIsEnum) { _%>
                <td jhiTranslate="{{'<%= angularAppName %>.<%= fieldType %>.' + <%= entityInstance %>.<%= fieldName %>}}">{{<%= entityInstance %>.<%= fieldName %>}}
                <%_ } else if (['Instant', 'ZonedDateTime'].includes(fieldType)) { _%>
                {{<%=entityInstance %>.<%=fieldName%> | date:'medium'}}
                <%_ } else if (fieldType === 'LocalDate') { _%>
                {{<%=entityInstance %>.<%=fieldName%> | date:'mediumDate'}}
                <%_ } else { _%>
                {{<%=entityInstance %>.<%=fieldName%>}}
                <%_ } _%>
                <%_ } _%>
                <%_ for (idx in relationships) {
                const relationshipType = relationships[idx].relationshipType;
                const ownerSide = relationships[idx].ownerSide;
                const relationshipFieldName = relationships[idx].relationshipFieldName;
                const relationshipFieldNamePlural = relationships[idx].relationshipFieldNamePlural;
                const otherEntityName = relationships[idx].otherEntityName;
                const otherEntityStateName = relationships[idx].otherEntityStateName;
                const otherEntityField = relationships[idx].otherEntityField;
                const otherEntityFieldCapitalized = relationships[idx].otherEntityFieldCapitalized; _%>
                <%_ if (relationshipType === 'many-to-one'
                || (relationshipType === 'one-to-one' && ownerSide === true)
                || (relationshipType === 'many-to-many' && ownerSide === true && pagination === 'no')) { _%>

                    <%_ if (otherEntityName === 'user') { _%>
                        <%_ if (relationshipType === 'many-to-many') { _%>
                    <span *ngFor="let <%= relationshipFieldName %> of <%= entityInstance %>.<%= relationshipFieldNamePlural %>; let last = last">
                            {{<%= relationshipFieldName %>.<%= otherEntityField %>}}{{last ? '' : ', '}}

                        <%_ } else { _%>
                            <%_ if (dto === 'no') { _%>
                    {{<%= entityInstance + "." + relationshipFieldName + "?." + otherEntityField %>}}
                            <%_ } else { _%>
                    {{<%= entityInstance + "." + relationshipFieldName + otherEntityFieldCapitalized %>}}
                            <%_ } _%>
                        <%_ } _%>
                    <%_ } else { _%>
                        <%_ if (relationshipType === 'many-to-many') { _%>
                    <span *ngFor="let <%= relationshipFieldName %> of <%= entityInstance %>.<%= relationshipFieldNamePlural %>; let last = last">
                            <a class="form-control-static" [routerLink]="['../<%= otherEntityStateName %>', <%= relationshipFieldName %>?.id ]">{{<%= relationshipFieldName %>.<%= otherEntityField %>}}{{last ? '' : ', '}}

                        <%_ } else { _%>
                            <%_ if (dto === 'no') { _%>
                    <div *ngIf="<%= entityInstance + "." + relationshipFieldName %>">
                        <a [routerLink]="['../<%= otherEntityStateName %>', <%= entityInstance + "." + relationshipFieldName + "?.id" %> ]" >{{<%= entityInstance + "." + relationshipFieldName + "?." + otherEntityField %>}}

                        <%_ } else { _%>
                    <div *ngIf="<%= entityInstance + "." + relationshipFieldName + "Id" %>">
                        <a [routerLink]="['../<%= otherEntityStateName %>', <%= entityInstance + "." + relationshipFieldName + "Id" %> %> ]" >{{<%= entityInstance + "." + relationshipFieldName + otherEntityFieldCapitalized %>}}

                            <%_ } _%>
                        <%_ } _%>
                    <%_ } _%>

                <%_ } _%>
                <%_ } _%>

                        <button type="submit"
                                [routerLink]="['../<%= entityUrl %>', <%= entityInstance %>.id ]"
                                class="btn btn-info btn-sm">

                            View
                        </button>
                        <button type="submit"
                                [routerLink]="['/', { outlets: { popup: '<%= entityUrl %>/'+ <%= entityInstance %>.id + '/edit'} }]"
                                replaceUrl="true"
                                class="btn btn-primary btn-sm">

                            Edit
                        </button>
                        <button type="submit"
                                [routerLink]="['/', { outlets: { popup: '<%= entityUrl %>/'+ <%= entityInstance %>.id + '/delete'} }]"
                                replaceUrl="true"
                                class="btn btn-danger btn-sm">

                            Delete
                        </button>

    <%_ if (databaseType !== 'cassandra') { _%>
        <%_ if (pagination === 'pager') { _%>

        <div *ngIf="<%=entityInstancePlural %> && <%=entityInstancePlural %>.length">

                <jhi-item-count [page]="page" [total]="queryCount" [itemsPerPage]="itemsPerPage"></jhi-item-count>

                <ngb-pagination [collectionSize]="totalItems" [(page)]="page"  (pageChange)="loadPage(page)"></ngb-pagination>

        <%_ } else if (pagination === 'pagination') { _%>
        <div *ngIf="<%=entityInstancePlural %> && <%=entityInstancePlural %>.length">

                <jhi-item-count [page]="page" [total]="queryCount" [itemsPerPage]="itemsPerPage"></jhi-item-count>

                <ngb-pagination [collectionSize]="totalItems" [(page)]="page" (pageChange)="loadPage(page)"></ngb-pagination>

        <%_ } _%>
    <%_ } _%>