text:
package org.teavm.classlib.java.lang;

/**
 *
 * @author Alexey Andreev
 */
public class TInterruptedException extends Exception {
    private static final long serialVersionUID = -7832805114281254695L;
}

redpajama_set_name: RedPajamaGithub


text:
Complete overview of all agreed-upon recommendations for optimal flow.

## Contributing
Contributors should read [`CONTRIBUTING.md`][contributing] in the Fabric root.

## Security
### Git
Git assures we maintain version control over all releases, with our primary
goal being to build Fabric from source and generate a deterministic build.

**The Recommendations:**
1. Use Command Line Git.  It's self-explanatory.  You can do it!
2. When preparing to share something with your peers, follow these steps:
  0. (Initial Git Install) Ensure [your environment][environment-setup] is setup
  1. Run `git status` to check which files have changed locally
  2. Any files with secret information: `git add -i FILENAME`
    1. Ensure to only add non-private information
  3. Any files you want to share: `git add FILENAME`
  4. Commit to your changes:
    1. Create commit locally: `git commit`
      0. Always use a Capital Letter first, highlight defined terms using Capital Letters, and avoid any punctuating marks
      1. Ensure message contents contains
        1. A brief description of the changes (< 80 characters)
    2. Push to your public share: `git push origin`
    3. (If Upstream Project Exists) `git push upstream`
  5. Click the link in the output of `git push upstream` to acquire SUBMIT_PROPOSAL_HTTP
  6. [Submit a Pull Request][submit-a-pull-request]!

[contributing]: /CONTRIBUTING.md
[environment-setup]: https://dev.fabric.pub/documents/environment-setup [404]
[submit-a-pull-request]: https://dev.fabric.pub/documents/submit-a-pull-request [404]


text:
azure.mgmt.datalake.analytics.account.models module
===================================================

.. automodule:: azure.mgmt.datalake.analytics.account.models
    :members:
    :undoc-members:
    :show-inheritance:


text:
title: As We Like It
playwright: Kevin Buxton, Crispin Harris, Joe Bicarregui, Campbell Kay & Mark Hamilton
student_written: true
season: Edinburgh
period: Edinburgh
season_sort: 400
date_start: 1977-08-22
date_end: 1977-09-03
venue: Cathedral Hall, Albany Street

cast:
- name: Sue Candy
- name: Viv Maranzano
- name: Duncan Humphries
- name: Hugh Simon
- name: Jon Turner
- name: Matthew Bannister

crew:
- role: Director
  name: Matthew Bannister
- role: Assistant Director
  name: Kevin Buxton
- role: Assistant Director
  name: Crispin Harris
- role: Band
  name: Paul Woodhouse
- role: Band
  name: Martin Archer
- role: Band
  name: Matthew Bannister
- role: Lighting & Sound
  name: Chris Toms
- role: Lighting & Sound
  name: Alan Jasper
- role: Stage Manager
  name: Heather Peace
- role: Stage Manager
  name: Jacky Boucherat
---


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.eventMap = undefined;

var _global = require('global');

exports.default = {
  alt: false,
  bubbles: true,
  button: 0,
  cancelable: true,
  clientX: 0,
  clientY: 0,
  ctrl: false,
  detail: 1,
  key: '13',
  isTrusted: true,
  meta: false,
  pageX: 0,
  pageY: 0,
  relatedTarget: null,
  touches: [],
  screenX: 0,
  screenY: 0,
  shift: false,
  view: _global.window,
  details: {}
};
var eventMap = exports.eventMap = {
  MouseEvent: ['click', 'dblclick', 'mouseup', 'mousedown', 'mouseenter', 'mousemove', 'mouseleave'],
  KeyboardEvent: ['keypress', 'keydown', 'keyup'],
  TouchEvent: ['touchstart', 'touchmove', 'touchend', 'touchcancel'],
  CustomEvent: []
};


text:
Filesystem/XML Spoke for EIF Work item connectors

### Installation

Add this line to your application's Gemfile:

    gem 'rallyeif-xml'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install rallyeif-xml

### Usage

    $ ruby  rally2_xml_connector.rb  <config XML>  <interval in minutes>

### Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Make changes
4. Commit your changes (`git commit -am 'Add some feature'`)
5. Push to the branch (`git push origin my-new-feature`)
6. Create new Pull Request


text:
package org.apache.camel.processor;

import junit.framework.TestCase;

public class ThroughPutLoggerTest extends TestCase {

    public void testLogStringDurationIsNotZero() throws Exception {
        ThroughputLogger underTest = new ThroughputLogger(10);
        for (int i = 0; i < 25; i++) {
            underTest.process(null);
        }
        String message = (String) underTest.logMessage(null);
        assertTrue("consumed 20 :" + message, message.contains("20"));
    }
}


text:
from tools.load import LoadMatrix
from sg import sg
lm=LoadMatrix()

traindat=lm.load_numbers('../data/fm_train_real.dat')
testdat=lm.load_numbers('../data/fm_test_real.dat')
train_label=lm.load_labels('../data/label_train_twoclass.dat')
parameter_list=[[traindat,testdat, train_label,10,2.1,1.2,1e-5,False],
		[traindat,testdat,train_label,10,2.1,1.3,1e-4,False]]

def classifier_libsvm (fm_train_real=traindat,fm_test_real=testdat,
			label_train_twoclass=train_label,
			size_cache=10, width=2.1,C=1.2,
			epsilon=1e-5,use_bias=False):

	sg('set_features', 'TRAIN', fm_train_real)
	sg('set_kernel', 'GAUSSIAN', 'REAL', size_cache, width)
	sg('set_labels', 'TRAIN', label_train_twoclass)
	sg('new_classifier', 'LIBSVM')
	sg('svm_epsilon', epsilon)
	sg('c', C)
	sg('svm_use_bias', use_bias)
	sg('train_classifier')

	sg('set_features', 'TEST', fm_test_real)
	result=sg('classify')
	kernel_matrix = sg('get_kernel_matrix', 'TEST')
	return result, kernel_matrix

if __name__=='__main__':
	print('LibSVM')
	classifier_libsvm(*parameter_list[0])


text:
class GuideSerializer < BaseSerializer

  has_one :crop
  has_one :user
  attribute :draft
  attribute :name
  attribute :overview
  attribute :featured_image do
    if object.featured_image
      {
        canopy_url: object.pictures[object.featured_image].attachment.url(:canopy),
        image_url: object.pictures[object.featured_image].attachment.url,
        medium_url: object.pictures[object.featured_image].attachment.url(:medium),
        thumbnail_url: object.pictures[object.featured_image].attachment.url(:small)
      }
    elsif object.pictures.count > 0
      {
        canopy_url: object.pictures.first.attachment.url(:canopy),
        image_url: object.pictures.first.attachment.url,
        medium_url: object.pictures.first.attachment.url(:medium),
        thumbnail_url: object.pictures.first.attachment.url(:small)
      }
    end
  end
  attribute :location
  attribute :practices
  attribute :compatibility_score do
    object.compatibility_score(current_user)
  end
  attribute :basic_needs do
    object.basic_needs(current_user)
  end
  attribute :completeness_score
  attribute :popularity_score

  has_many :stages
  has_one :time_span

  has_many :pictures, serializer: PictureSerializer
end


text:
using Cauldron.XAML.Interactivity.Actions;

#if WINDOWS_UWP

using Windows.UI.Xaml.Markup;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml;

#else

using System.Windows.Markup;
using System.Windows;

#endif

namespace Cauldron.XAML.Interactivity
{
    /// <summary>
    /// Provides a Behaviour that can invoke <see cref="ActionBase"/> behaviours.
    /// <para/>
    /// The <see cref="EventTrigger"/> is triggered by an event of the associated <see cref="FrameworkElement"/>
    /// </summary>
#if WINDOWS_UWP

    [ContentProperty(Name = nameof(Actions))]
#else

    [ContentProperty("Actions")]
#endif
    public sealed class EventTrigger : Behaviour<FrameworkElement>, IBehaviour
    {
        #region Dependency Property EventName

        /// <summary>
        /// Identifies the <see cref="EventName" /> dependency property
        /// </summary>
        public static readonly DependencyProperty EventNameProperty = DependencyProperty.Register(nameof(EventName), typeof(string), typeof(EventTrigger), new PropertyMetadata("", EventTrigger.OnEventNameChanged));

        /// <summary>
        /// Gets or sets the <see cref="EventName" /> Property
        /// </summary>
        public string EventName
        {
            get => this.GetValue(EventNameProperty) as string;
            set => this.SetValue(EventNameProperty, value);
        }

        private static void OnEventNameChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
        {
            var d = dependencyObject as EventTrigger;

            if (d == null)
                return;

            d.SetEventHandler();
        }

        #endregion Dependency Property EventName

        private ActionCollection actions;
        private DynamicEventHandler eventHandler;

        /// <summary>
        /// Gets a collection of actions that can be invoked by this behaviour
        /// </summary>
        public ActionCollection Actions
        {
            get
            {
                if (this.actions == null)
                    this.actions = new ActionCollection(this.AssociatedObject);

                return this.actions;
            }
        }

        /// <summary>
        /// Occures when the behavior is attached to the object
        /// </summary>
        protected override void OnAttach() => this.SetEventHandler();

        /// <summary>
        /// Occures after shallow copying the behavior
        /// </summary>
        /// <param name="behaviour">The resulting behavior from <see cref="IBehaviour.Copy"/></param>
        protected override void OnCopy(IBehaviour behaviour)
        {
            var eventTrigger = behaviour as EventTrigger;

            foreach (var item in this.Actions)
                eventTrigger.Actions.Add((item as IBehaviour).Copy() as ActionBase);
        }

        /// <summary>
        /// Occures when the behaviour is detached from the object
        /// </summary>
        protected override void OnDetach() => this.eventHandler?.Dispose();

        private void SetEventHandler()
        {
            if (string.IsNullOrEmpty(this.EventName) || this.AssociatedObject == null)
                return;

            this.eventHandler?.Dispose();
            this.eventHandler = new DynamicEventHandler(this.AssociatedObject, this.EventName, (sender, args) =>
            {
                foreach (var item in this.Actions)
                    item.Invoke(args);
            });
        }
    }
}


text:
namespace blink {
namespace scheduler {

using base::sequence_manager::TaskQueue;

std::unique_ptr<ResourceLoadingTaskRunnerHandleImpl>
ResourceLoadingTaskRunnerHandleImpl::WrapTaskRunner(
    scoped_refptr<MainThreadTaskQueue> task_queue) {
  DCHECK(task_queue);
  return base::WrapUnique(
      new ResourceLoadingTaskRunnerHandleImpl(std::move(task_queue)));
}

ResourceLoadingTaskRunnerHandleImpl::ResourceLoadingTaskRunnerHandleImpl(
    scoped_refptr<MainThreadTaskQueue> task_queue)
    : task_queue_(std::move(task_queue)),
      task_runner_(task_queue_->CreateTaskRunner(TaskType::kNetworking)) {}

ResourceLoadingTaskRunnerHandleImpl::~ResourceLoadingTaskRunnerHandleImpl() =
    default;

void ResourceLoadingTaskRunnerHandleImpl::DidChangeRequestPriority(
    net::RequestPriority priority) {
  // TODO(crbug.com/860545): Decide whether this method should be removed.
}

scoped_refptr<base::SingleThreadTaskRunner>
ResourceLoadingTaskRunnerHandleImpl::GetTaskRunner() const {
  return task_runner_;
}

const scoped_refptr<MainThreadTaskQueue>&
ResourceLoadingTaskRunnerHandleImpl::task_queue() {
  return task_queue_;
}

}  // namespace scheduler
}  // namespace blink


text:
using std::string;
using std::vector;
using namespace boost::archive::iterators; // NOLINT(*)

namespace kudu {

// Hive selectively encodes characters. This is the whitelist of
// characters it will encode.
// See common/src/java/org/apache/hadoop/hive/common/FileUtils.java
// in the Hive source code for the source of this list.
static boost::function<bool (char)> HiveShouldEscape = boost::is_any_of("\"#%\\*/:=?\u00FF"); // NOLINT(*)

// It is more convenient to maintain the complement of the set of
// characters to escape when not in Hive-compat mode.
static boost::function<bool (char)> ShouldNotEscape = boost::is_any_of("-_.~"); // NOLINT(*)

static inline void UrlEncode(const char* in, int in_len, string* out, bool hive_compat) {
  (*out).reserve(in_len);
  std::ostringstream ss;
  for (int i = 0; i < in_len; ++i) {
    const char ch = in[i];
    // Escape the character iff a) we are in Hive-compat mode and the
    // character is in the Hive whitelist or b) we are not in
    // Hive-compat mode, and the character is not alphanumeric or one
    // of the four commonly excluded characters.
    if ((hive_compat && HiveShouldEscape(ch)) ||
        (!hive_compat && !(isalnum(ch) || ShouldNotEscape(ch)))) {
      ss << '%' << std::uppercase << std::hex << static_cast<uint32_t>(ch);
    } else {
      ss << ch;
    }
  }

  (*out) = ss.str();
}

void UrlEncode(const vector<uint8_t>& in, string* out, bool hive_compat) {
  if (in.empty()) {
    *out = "";
  } else {
    UrlEncode(reinterpret_cast<const char*>(&in[0]), in.size(), out, hive_compat);
  }
}

void UrlEncode(const string& in, string* out, bool hive_compat) {
  UrlEncode(in.c_str(), in.size(), out, hive_compat);
}

string UrlEncodeToString(const std::string& in, bool hive_compat) {
  string ret;
  UrlEncode(in, &ret, hive_compat);
  return ret;
}

// Adapted from
// http://www.boost.org/doc/libs/1_40_0/doc/html/boost_asio/
//   example/http/server3/request_handler.cpp
// See http://www.boost.org/LICENSE_1_0.txt for license for this method.
bool UrlDecode(const string& in, string* out, bool hive_compat) {
  out->clear();
  out->reserve(in.size());
  for (size_t i = 0; i < in.size(); ++i) {
    if (in[i] == '%') {
      if (i + 3 <= in.size()) {
        int value = 0;
        std::istringstream is(in.substr(i + 1, 2));
        if (is >> std::hex >> value) {
          (*out) += static_cast<char>(value);
          i += 2;
        } else {
          return false;
        }
      } else {
        return false;
      }
    } else if (!hive_compat && in[i] == '+') { // Hive does not encode ' ' as '+'
      (*out) += ' ';
    } else {
      (*out) += in[i];
    }
  }
  return true;
}

static inline void Base64Encode(const char* in, int in_len, std::ostringstream* out) {
  typedef base64_from_binary<transform_width<const char*, 6, 8> > base64_encode;
  // Base64 encodes 8 byte chars as 6 bit values.
  std::ostringstream::pos_type len_before = out->tellp();
  copy(base64_encode(in), base64_encode(in + in_len), std::ostream_iterator<char>(*out));
  int bytes_written = out->tellp() - len_before;
  // Pad with = to make it valid base64 encoded string
  int num_pad = bytes_written % 4;
  if (num_pad != 0) {
    num_pad = 4 - num_pad;
    for (int i = 0; i < num_pad; ++i) {
      (*out) << "=";
    }
  }
  DCHECK_EQ(out->str().size() % 4, 0);
}

void Base64Encode(const vector<uint8_t>& in, string* out) {
  if (in.empty()) {
    *out = "";
  } else {
    std::ostringstream ss;
    Base64Encode(in, &ss);
    *out = ss.str();
  }
}

void Base64Encode(const vector<uint8_t>& in, std::ostringstream* out) {
  if (!in.empty()) {
    // Boost does not like non-null terminated strings
    string tmp(reinterpret_cast<const char*>(&in[0]), in.size());
    Base64Encode(tmp.c_str(), tmp.size(), out);
  }
}

void Base64Encode(const string& in, string* out) {
  std::ostringstream ss;
  Base64Encode(in.c_str(), in.size(), &ss);
  *out = ss.str();
}

void Base64Encode(const string& in, std::ostringstream* out) {
  Base64Encode(in.c_str(), in.size(), out);
}

bool Base64Decode(const string& in, string* out) {
  typedef transform_width<binary_from_base64<string::const_iterator>, 8, 6> base64_decode;
  string tmp = in;
  // Replace padding with base64 encoded NULL
  replace(tmp.begin(), tmp.end(), '=', 'A');
  try {
    *out = string(base64_decode(tmp.begin()), base64_decode(tmp.end()));
  } catch(std::exception& e) {
    return false;
  }

  // Remove trailing '\0' that were added as padding.  Since \0 is special,
  // the boost functions get confused so do this manually.
  int num_padded_chars = 0;
  for (int i = out->size() - 1; i >= 0; --i) {
    if ((*out)[i] != '\0') break;
    ++num_padded_chars;
  }
  out->resize(out->size() - num_padded_chars);
  return true;
}

void EscapeForHtml(const string& in, std::ostringstream* out) {
  DCHECK(out != nullptr);
  for (const char& c : in) {
    switch (c) {
      case '<': (*out) << "<";
                break;
      case '>': (*out) << ">";
                break;
      case '&': (*out) << "&";
                break;
      default: (*out) << c;
    }
  }
}

std::string EscapeForHtmlToString(const std::string& in) {
  std::ostringstream str;
  EscapeForHtml(in, &str);
  return str.str();
}

} // namespace kudu


text:
package com.microsoft.azure.keyvault.models;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * The contact information for the vault certificates.
 */
public class Contact {
    /**
     * Email addresss.
     */
    @JsonProperty(value = "email")
    private String emailAddress;

    /**
     * Name.
     */
    private String name;

    /**
     * Phone number.
     */
    private String phone;

    /**
     * Get the emailAddress value.
     *
     * @return the emailAddress value
     */
    public String emailAddress() {
        return this.emailAddress;
    }

    /**
     * Set the emailAddress value.
     *
     * @param emailAddress the emailAddress value to set
     * @return the Contact object itself.
     */
    public Contact withEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
        return this;
    }

    /**
     * Get the name value.
     *
     * @return the name value
     */
    public String name() {
        return this.name;
    }

    /**
     * Set the name value.
     *
     * @param name the name value to set
     * @return the Contact object itself.
     */
    public Contact withName(String name) {
        this.name = name;
        return this;
    }

    /**
     * Get the phone value.
     *
     * @return the phone value
     */
    public String phone() {
        return this.phone;
    }

    /**
     * Set the phone value.
     *
     * @param phone the phone value to set
     * @return the Contact object itself.
     */
    public Contact withPhone(String phone) {
        this.phone = phone;
        return this;
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using HackathonAPI.Models;

namespace GuessChangeListAuthor.Models
{
    public class AlmaRule : IRule
    {
        private class Dto
        {
            public string Author;

            public Dictionary<string, int> Words = new Dictionary<string, int>();
        }

        private Dictionary<string, Dto> data;
        public void GenerateData(List<ChangeList> allChangeLists)
        {
            var wordsForAuthors = new Dictionary<string, Dto>();

            foreach (var change in allChangeLists)
            {
                if (!wordsForAuthors.ContainsKey(change.Author))
                {
                    wordsForAuthors.Add(change.Author, new Dto
                    {
                        Author = change.Author
                    });
                }

                var wordSplit = change.Description.Split(';', ' ');

                foreach (var word in wordSplit)
                {
                    if (!wordsForAuthors[change.Author].Words.ContainsKey(word))
                    {
                        wordsForAuthors[change.Author].Words.Add(word, 1);
                    }
                    else
                    {
                        wordsForAuthors[change.Author].Words[word]++;
                    }
                }
            }

            data = wordsForAuthors;
        }

        public int Execute(string author, ChangeList cl)
        {
            var words = cl.Description.Split(' ', ';').Distinct();

            // dictionary<word, Dictionary<author, count>>
            var allWordsMentioned = new Dictionary<string, Dictionary<string, double>>();

            foreach (var word in words)
            {
                var authorsWhoMentionWord = new Dictionary<string, double>();

                foreach (var author2 in data.Keys)
                {
                    if (data[author2].Words.ContainsKey(word))
                    {
                        authorsWhoMentionWord.Add(author2, data[author2].Words[word]);
                    }
                }

                allWordsMentioned.Add(word, authorsWhoMentionWord);
            }

            double sum = 0;

            foreach (var word in allWordsMentioned)
            {
                if(word.Value.ContainsKey(author))
                    sum += word.Value[author] / word.Value.Count;
            }

            return (int)sum;
        }
    }
}


text:
'use strict';

var gulp = require('gulp')
  , path = require('path')
  , $ = require('gulp-load-plugins')({
    pattern: [
      'gulp-*',
      'browser-sync'
    ]
  })

  , buildConfig = require('../build.config.js')

  , appFiles = path.join(buildConfig.appDir, '**/*')

gulp.task('browserSync', function () {
  $.browserSync({
    host: buildConfig.host,
    open: false,
    port: buildConfig.port,
    server: {
      baseDir: buildConfig.buildDir
    }
  });
});

gulp.task('watch', function () {
  $.browserSync.reload();
  gulp.watch([appFiles], ['build', $.browserSync.reload]);
});


text:
---
layout: post
title: "Probando HSQLDB"
date: 2013-07-29 00:51:57
categories: hsqldb, Java
---
HSQLDB es un gestor de bases de datos escrito íntegramente en java, con soporte a la última para SQL, bla bla y afirman ser los líderes en su terreno, los más guapos, los más rápidos,... aunque no dicen nada de H2 por si acaso.

Tiene tres modos de funcionamiento:

Memoria: todas las tablas se guardan en la memoria RAM. Acceso local claro está.

Fichero: los datos se almacenan en ficheros. Acceso local obviamente.

Modo servidor: el acceso puede ser remoto.

Puedes iniciar una conexión a una BD y si no existe la crea al vuelo.

¿Qué utilidad puede tener una cosa así? ¡Todo parece que está en el aire!
Como poco, puede resultar muy útil en un entorno de desarrollo o un entorno para hacer pruebas. No precisa instalar
un servidor ni poner en marcha nada en concreto, en ese sentido es como una BD SQLite. Otra cosa interesante es que puedes meterle funciones propias... ¡¡hechas en java!! al final todo queda en casa
Este gestor de BD te lo encuentras muchas veces cuando ves ejemplos de Hibernate o de aplicaciones java con acceso a BD.

Si te descargas HSQLDB trae una serie de utilidades y una "útil" aunque algo espartana es hsqldb-databasemanagerswing. También tienes
la versión awt si eres más espartano que Leonidas. En la distribución linux dispones directamente de ese comando si no es así lo tienes que invocar a mano.

Ahí creas una BD al vuelo, en este caso una BD llamada example con una tabla llamada table1.

create table table1 (
id identity,
name varchar(30),
description varchar(100),
anydate date,
done boolean);

identity viene a ser el autoincrement, autonumeric, you name it..

Meto tres registros y al cerrar me encuentro con dos ficheros: example.log y example.properties

example.log
Contiene los últimos comandos insertados.

CONNECT USER SA
CREATE TABLE table1 (\u000aid identity,\u000aname varchar(30),\u000adescription
varchar(100),\u000aanydate date,\u000adone boolean)
INSERT INTO TABLE1 VALUES(0,'test1','test1 desc','2013-07-29',TRUE)
INSERT INTO TABLE1 VALUES(1,'test2','test2 desc','2013-07-29',TRUE)
INSERT INTO TABLE1 VALUES(2,'test3','test3 desc','2013-07-29',TRUE)

example.properties
Contiene las propiedades de la BD.

#HSQL Database Engine 1.8.0.10
#Mon Jul 29 01:18:19 CEST 2013
hsqldb.script_format=0
runtime.gc_interval=0
sql.enforce_strict_size=false
hsqldb.cache_size_scale=8
readonly=false
hsqldb.nio_data_file=true
hsqldb.cache_scale=14
version=1.8.0
hsqldb.default_table_type=memory
hsqldb.cache_file_scale=1
hsqldb.log_size=200
modified=yes
hsqldb.cache_version=1.7.0
hsqldb.original_version=1.8.0
hsqldb.compatible_version=1.8.0

Siguiente ejecución

Como se puede comprobar, si hacemos un select HSQLDB nos muestra los datos que ya habiamos metido, ya que al iniciarse los recupera mirando el fichero example.log.
Insertamos unos nuevos registros y...

...aparece un nuevo ficehro:

example.script

Este fichero contiene el comando para crear la tabla y los inserts anteriores, es decir, lo que había en el example.log
pasa al fichero .script y en el fichero .log aparece los últimos comandos que se han ejecutado, es decir, los últimos
cambios en la BD.

Siguiente ejecución

Haciendo una select se puede comprobar que efectivamente HSQLDB carga todo desde el ficerho .script y .log
Se supone que en el fichero log se guardan cosas en los casos que la conexión se cierre de forma brusca.

Para asegurarte de que los datos se guardan en el fichero script, utiliza el comando SQL CHECKPOINT.

HsqldbSample.java

Merece la pena hacer una pequeña prueba de acceso desde java para verificar una cosa ¿podemos recuperar el id de un insert? parece que a la
manera tradicional no, al menos en esta prueba me daba Comando no soportado y en muchos sitios dicen que no se puede.
Debemos ejecutar un comando SQL específico de Hsqldb (CALL IDENTITY) y eso no da el dato. Otra cosa curiosa, es que a partir del registro 12 ya no me guardaba en el fichero example.script los últimos insert. He tenido que incluir la directiva shutdown=true en la conexión para que guardara todo. No era cuestión de hacer commit ni nada.

import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.Scanner;

/**
 * Quick and Dirty program te test HSQLDB
 * run: java -cp "hsqldb.jar:." HsqldbSample
 * @author pello_altadill
 *
 */
public class HsqldbSample {

/**
* @param args
*/
public static void main(String[] args) {
	Scanner reader = new Scanner(System.in);
	String name = "";
	String description = "";

  try {
 Class.forName("org.hsqldb.jdbcDriver");
 Connection conn =
 DriverManager.getConnection("jdbc:hsqldb:file:example;shutdown=true","sa","");
 Statement stat;
 ResultSet resultset;

 stat = conn.createStatement();
 resultset = stat.executeQuery("select * from table1;");

   while (resultset.next()) {
     System.out.println("id = " + resultset.getString("id"));
     System.out.println("name = " + resultset.getString("name"));
   }

  System.out.println("Gimme a name");
  name = reader.nextLine();
  System.out.println("Ok, now gimme a desc");
  description = reader.nextLine();

 // INSERT
 String insertQuery =  "insert into table1 (name,description,anydate,done) values('"+name+"','"+description+"',now(),true)";
 int result = stat.executeUpdate(insertQuery);

 // INSERT RECUPERANDO LA ÚLTIMA CLAVE
  System.out.println("Gimme a name");
  name = reader.nextLine();
  System.out.println("Ok, now gimme a desc");
  description = reader.nextLine();

	insertQuery =  "insert into table1 (name,description,anydate,done) values('"+name+"','"+description+"',now(),true)";

	 	result = stat.executeUpdate(insertQuery);

		// Query to retrieve last generated id from HSQLDB
	   PreparedStatement psIdentity = conn.prepareStatement("CALL IDENTITY()");

      ResultSet resultSet = psIdentity.executeQuery();
	   if (   resultSet.next()) {
      	int lastid = resultSet.getInt(1);
	      System.out.println("Last id: "+ lastid);
	      resultSet.close();
      }

   /*
   	// Doesn't work at all
	 //result = stat.executeUpdate(insertQuery,Statement.RETURN_GENERATED_KEYS);
   // Sacamos la clave
   ResultSet rs = stat.getGeneratedKeys();
   if (rs.next()){
       result=rs.getInt(1);
   }

	*/

   resultset = stat.executeQuery("select * from table1;");

   while (resultset.next()) {
     System.out.println("id = " + resultset.getString("id"));
     System.out.println("name = " + resultset.getString("name"));
   }

	resultset.close();
   conn.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}

}

Tras meter mano a este programa y hacer que metiera 10.000 registros, he comprobado que efectivamente, mete 10.000 comandos insert en el fichero example.script. Si no los queremos, basta con editar ese fichero y cargarnos los insert y si acaso retocar el valor del último id generado.


text:
from __future__ import absolute_import

import os
import unittest

import tests.common
import anytemplate.engines.cheetah as TT

class Test(unittest.TestCase):

    def test_12__init__w_kwargs(self):
        if TT.Template is not None:
            self.assertTrue(isinstance(TT.Engine(errorCatcher=None),
                                       TT.Engine))

    def test_20_renders(self):
        tmpl_s = "hello, $name!"
        exp = "hello, John!"

        if TT.Template is not None:
            egn = TT.Engine()
            self.assertEqual(egn.renders(tmpl_s, {"name": "John", }), exp)

    def test_22_renders__no_context(self):
        tmpl_s = "hello world!"

        if TT.Template is not None:
            egn = TT.Engine()
            self.assertEqual(egn.renders(tmpl_s), tmpl_s)

    def test_24_renders__no_context__w_at_path(self):
        tmpl_s = "hello world!"

        if TT.Template is not None:
            egn = TT.Engine()
            self.assertEqual(egn.renders(tmpl_s, at_paths=['.']), tmpl_s)

    def test_26_renders__no_context__w_file(self):
        tmpl_s = "hello world!"

        if TT.Template is not None:
            egn = TT.Engine()
            self.assertEqual(egn.renders(tmpl_s, file="x"), tmpl_s)

    def test_28_renders__with_engine_special_option(self):
        if TT.Template is not None:
            egn = TT.Engine(compilerSettings={'cheetahVarStartToken': '@'})
            self.assertEqual(egn.renders("@a", {'a': ""}), '')

    def test_36_renders_impl__no_context__w_filename(self):
        tmpl_s = "hello world!"

        if TT.Template is not None:
            egn = TT.Engine()
            self.assertEqual(egn.renders_impl(tmpl_s, {}, file="x"), tmpl_s)

class Test10(tests.common.TestsWithWorkdir):

    def test_10_render(self):
        tmpl = os.path.join(self.workdir, "a.t")
        tmpl_s = "$getVar('greeting', 'hello!')"
        ctx = dict(greeting="hello, Cheetah!", )
        open(tmpl, 'w').write(tmpl_s)

        if TT.Template is not None:
            egn = TT.Engine()
            res = egn.render(tmpl, ctx, at_paths=[self.workdir])
            self.assertEqual(res, ctx["greeting"])

    def test_12_render__no_context(self):
        tmpl = os.path.join(self.workdir, "a.t")
        tmpl_s = "$getVar('greeting', 'hello!')"
        open(tmpl, 'w').write(tmpl_s)

        if TT.Template is not None:
            egn = TT.Engine()
            res = egn.render(tmpl)
            self.assertEqual(res, "hello!")

    def test_26_render_impl__w_source(self):
        tmpl = os.path.join(self.workdir, "a.t")
        tmpl_s = "$getVar('greeting', 'hello!')"
        ctx = dict(greeting="hello, Cheetah!", )
        open(tmpl, 'w').write(tmpl_s)

        if TT.Template is not None:
            egn = TT.Engine()
            res = egn.render_impl(tmpl, ctx, at_paths=[self.workdir],
                                  source="aaa")
            self.assertEqual(res, ctx["greeting"])

# vim:sw=4:ts=4:et:


text:
var express = require("express"),
		bodyParser = require("body-parser"),
		multipart = require("connect-multiparty"),
    config = require("./config.json"),
    keenioMiddleware = require('../');

var app = express();

keenioMiddleware.configure(config);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(multipart());
app.use(keenioMiddleware.handleAll());

var router = express.Router();

router.route('/test').get(function (req, res) {
  res.json({
    special: 'hey',
    abc: 4
  });
});

app.use(router);

app.listen(3000);


text:
#ifndef SEASIDECOMMSPAGE_H
#define SEASIDECOMMSPAGE_H

#include <MApplicationPage>
#include <seasidelist.h>
#include <seaside.h>

class SeasideCommsPage : public MApplicationPage
{
    Q_OBJECT
public:
    SeasideCommsPage(SeasidePersonModel *pm, SeasideList::CommCat type);

signals:
    void destSelected(QString);

private slots:
    void onButtonClicked(int id);

private:
    QList<SeasideDetail> m_detailList;
};

#endif // SEASIDECOMMSPAGE_H


text:
package mysns.service;

import java.util.List;

public interface UserService {

}


text:
using System.Collections.Generic;
using SoomlaWpStore.domain;
using SoomlaWpCore.events;
namespace SoomlaWpStore.events
{
    public class MarketItemsRefreshFinishedEvent : SoomlaEvent
    {
        private List<MarketItem> mMarketItems;

        public List<MarketItem> GetMarketItems()
        {
            return mMarketItems;
        }

        public MarketItemsRefreshFinishedEvent(List<MarketItem> marketItems)
            : this(marketItems, null)
        {
        }

        public MarketItemsRefreshFinishedEvent(List<MarketItem> marketItems, object sender)
            : base(sender)
        {
            mMarketItems = marketItems;
        }
    }
}


text:
/**
 * Created by batraa on 1/17/2015.
 */
public class GenericBST<Key extends Comparable<Key>, Value> {

    class Node {
        Key key;
        Value value;
        Node left;
        Node right;
        int count;
    }

    public void put(Node x, Key key, Value val) {

    }

    public void deleteMin() {

    }

    public int rank(Node x) {

        return 0;
    }

    public int rangeCount(Key x, Key y) {

        return 0;
    }

    public int size(Node x) {
        return 0;
    }

    public void inOrderTraversal(Node x) {

    }

    public void deleteMax() {

    }

    public void delete(Key key) {

    }
}


text:
module Azure::ServiceFabric::V6_3_0_9
  module Models
    #
    # Describes a Service Fabric property value of type Binary.
    #
    class BinaryPropertyValue < PropertyValue

      include MsRestAzure

      def initialize
        @Kind = "Binary"
      end

      attr_accessor :Kind

      # @return [Array<Integer>] Array of bytes to be sent as an integer array.
      # Each element of array is a number between 0 and 255.
      attr_accessor :data

      #
      # Mapper for BinaryPropertyValue class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'Binary',
          type: {
            name: 'Composite',
            class_name: 'BinaryPropertyValue',
            model_properties: {
              Kind: {
                client_side_validation: true,
                required: true,
                serialized_name: 'Kind',
                type: {
                  name: 'String'
                }
              },
              data: {
                client_side_validation: true,
                required: true,
                serialized_name: 'Data',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'NumberElementType',
                      type: {
                        name: 'Number'
                      }
                  }
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
$(function(){
	$("#dfecha1, #dfecha2").datepicker({
		 dateFormat: 'yy-mm-dd', //formato de la fecha - dd,mm,yy=dia,mes,año numericos  DD,MM=dia,mes en texto
		 //minDate: '-2Y', maxDate: '+1M +10D', //restringen a un rango el calendario - ej. +10D,-2M,+1Y,-3W(W=semanas) o alguna fecha
		 changeMonth: true, //permite modificar los meses (true o false)
		 changeYear: true, //permite modificar los años (true o false)
		 //yearRange: (fecha_hoy.getFullYear()-70)+':'+fecha_hoy.getFullYear(),
		 numberOfMonths: 1 //muestra mas de un mes en el calendario, depende del numero
	 });

	$("#iframe-reporte").css("height", (window.innerHeight-10) + "px");

	//Asigna autocomplete de Nombre Productos
	$("#dproducto").autocomplete({
		source: base_url+'panel/productos/ajax_get_productos/?tipo=nombre&asig=av',
		minLength: 1,
		selectFirst: true,
		select: function( event, ui ) {
			$("#didproducto").val(ui.item.id);
			$("#dproducto").val(ui.item.item.nombre);
		}
	});

	$("#dproducto").on("keydown", function(event){
		if(event.which == 8 || event == 46){
			$("#didproducto").val("");
			$("#dproducto").val("").css("background-color", "#FFF");
		}
	});});


text:
#ifndef __ZCONFIG_H_INCLUDED__
#define __ZCONFIG_H_INCLUDED__

#ifdef __cplusplus
extern "C" {
#endif

//  Opaque class structure
typedef struct _zconfig_t zconfig_t;

//  @interface
//  Function that executes config
typedef int (zconfig_fct) (zconfig_t *self, void *arg, int level);

//  Create new config item
CZMQ_EXPORT zconfig_t *
    zconfig_new (const char *name, zconfig_t *parent);

//  Destroy a config item and all its children
CZMQ_EXPORT void
    zconfig_destroy (zconfig_t **self_p);

//  Return name of config item
CZMQ_EXPORT char *
    zconfig_name (zconfig_t *self);

//  Return value of config item
CZMQ_EXPORT char *
    zconfig_value (zconfig_t *self);

//  Insert or update configuration key with value
CZMQ_EXPORT void
    zconfig_put (zconfig_t *self, const char *path, const char *value);

//  Set config item name, name may be NULL
CZMQ_EXPORT void
    zconfig_set_name (zconfig_t *self, const char *name);

//  Set new value for config item. The new value may be a string, a printf
//  format, or NULL. Note that if string may possibly contain '%', or if it
//  comes from an insecure source, you must use '%s' as the format, followed
//  by the string.
CZMQ_EXPORT void
    zconfig_set_value (zconfig_t *self, const char *format, ...);

//  Find our first child, if any
CZMQ_EXPORT zconfig_t *
    zconfig_child (zconfig_t *self);

//  Find our first sibling, if any
CZMQ_EXPORT zconfig_t *
    zconfig_next (zconfig_t *self);

//  Find a config item along a path; leading slash is optional and ignored.
CZMQ_EXPORT zconfig_t *
    zconfig_locate (zconfig_t *self, const char *path);

//  Resolve a config path into a string value; leading slash is optional
//  and ignored.
CZMQ_EXPORT char *
    zconfig_resolve (zconfig_t *self, const char *path, const char *default_value);

//  Set config item name, name may be NULL
CZMQ_EXPORT void
    zconfig_set_path (zconfig_t *self, const char *path, const char *value);

//  Locate the last config item at a specified depth
CZMQ_EXPORT zconfig_t *
    zconfig_at_depth (zconfig_t *self, int level);

//  Execute a callback for each config item in the tree
CZMQ_EXPORT int
    zconfig_execute (zconfig_t *self, zconfig_fct handler, void *arg);

//  Add comment to config item before saving to disk. You can add as many
//  comment lines as you like. If you use a null format, all comments are
//  deleted.
CZMQ_EXPORT void
    zconfig_set_comment (zconfig_t *self, const char *format, ...);

//  Return comments of config item, as zlist.
CZMQ_EXPORT zlist_t *
    zconfig_comments (zconfig_t *self);

//  Load a config tree from a specified ZPL text file
CZMQ_EXPORT zconfig_t *
    zconfig_load (const char *filename);

//  Save a config tree to a specified ZPL text file, where a filename
//  "-" means dump to standard output.
CZMQ_EXPORT int
    zconfig_save (zconfig_t *self, const char *filename);

//  Print the config file to open stream
CZMQ_EXPORT void
    zconfig_fprint (zconfig_t *self, FILE *file);

//  Print the config file to stdout
CZMQ_EXPORT void
    zconfig_print (zconfig_t *self);

//  Load a config tree from a memory chunk
CZMQ_EXPORT zconfig_t *
    zconfig_chunk_load (zchunk_t *chunk);

//  Save a config tree to a new memory chunk
CZMQ_EXPORT zchunk_t *
    zconfig_chunk_save (zconfig_t *self);

//  @end
//  Self test of this class
CZMQ_EXPORT void
    zconfig_test (bool verbose);

//  Compiler hints
CZMQ_EXPORT void zconfig_set_value (zconfig_t *self, const char *format, ...) CHECK_PRINTF (2);

#ifdef __cplusplus
}
#endif

//  Deprecated method aliases
#define zconfig_dump(s) zconfig_print(s)

#endif


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

import zinnia_tinymce.models

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='FileModel',
            fields=[
                ('id', models.AutoField(
                    verbose_name='ID', serialize=False,
                    auto_created=True, primary_key=True)),
                ('file_type', models.CharField(
                    max_length=35, verbose_name='file type',
                    choices=[('image', 'Image'), ('file', 'Document')])),
                ('uploaded_file', models.FileField(
                    upload_to=zinnia_tinymce.models.upload_path,
                    verbose_name='file / image')),
                ('creation_date', models.DateTimeField(
                    auto_now_add=True, verbose_name='creation date')),
            ],
            options={
                'ordering': ['-creation_date'],
                'verbose_name': 'file',
                'verbose_name_plural': 'files',
            },
            bases=(models.Model,),
        ),
    ]


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: grpc/file_system_master.proto

package alluxio.grpc;

public interface FreePOptionsOrBuilder extends
    // @@protoc_insertion_point(interface_extends:alluxio.grpc.file.FreePOptions)
    com.google.protobuf.MessageOrBuilder {

  /**
   * optional bool recursive = 1;
   */
  boolean hasRecursive();
  /**
   * optional bool recursive = 1;
   */
  boolean getRecursive();

  /**
   * optional bool forced = 2;
   */
  boolean hasForced();
  /**
   * optional bool forced = 2;
   */
  boolean getForced();

  /**
   * optional .alluxio.grpc.file.FileSystemMasterCommonPOptions commonOptions = 3;
   */
  boolean hasCommonOptions();
  /**
   * optional .alluxio.grpc.file.FileSystemMasterCommonPOptions commonOptions = 3;
   */
  alluxio.grpc.FileSystemMasterCommonPOptions getCommonOptions();
  /**
   * optional .alluxio.grpc.file.FileSystemMasterCommonPOptions commonOptions = 3;
   */
  alluxio.grpc.FileSystemMasterCommonPOptionsOrBuilder getCommonOptionsOrBuilder();
}


text:
<?php

namespace Pim\Bundle\PrestashopConnectorBundle\Webservice;

/**
 * Exception thrown if the client connection to the REST api gone bad.
 *
 */
class ConnectionErrorException extends \Exception
{
}


text:
/*
 * Antonin Bas (antonin@barefootnetworks.com)
 *
 */

#include "error_codes.h"
#include "table_common.h"
#include "utils.h"

#include "PI/frontends/generic/pi.h"
#include "PI/pi.h"

#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char table_set_default_hs[] =
    "Set default entry in a match table: "
    "table_set_default <table name> "
    "[<action name> <action parameters> | <indirect handle>]";

pi_cli_status_t do_table_set_default(char *subcmd) {
  const char *args[1];
  size_t num_args = sizeof(args) / sizeof(char *);
  if (parse_fixed_args(subcmd, args, num_args) < num_args)
    return PI_CLI_STATUS_TOO_FEW_ARGS;
  const char *t_name = args[0];
  pi_p4_id_t t_id = pi_p4info_table_id_from_name(p4info_curr, t_name);
  if (t_id == PI_INVALID_ID) return PI_CLI_STATUS_INVALID_TABLE_NAME;

  pi_cli_status_t status;

  pi_p4_id_t t_imp = pi_p4info_table_get_implementation(p4info_curr, t_id);

  pi_table_entry_t t_entry;
  if (t_imp == PI_INVALID_ID) {
    status = get_entry_direct(&t_entry);
  } else {
    status = get_entry_indirect(&t_entry);
  }
  if (status != PI_CLI_STATUS_SUCCESS) {
    return status;
  }

  t_entry.entry_properties = NULL;
  t_entry.direct_res_config = NULL;

  pi_status_t rc;
  rc = pi_table_default_action_set(sess, dev_tgt, t_id, &t_entry);
  if (rc == PI_STATUS_SUCCESS)
    printf("Default entry was successfully set.\n");
  else
    printf("Error when trying to set default entry.\n");

  if (t_imp == PI_INVALID_ID)
    cleanup_entry_direct(&t_entry);
  else
    cleanup_entry_indirect(&t_entry);

  return (rc == PI_STATUS_SUCCESS) ? PI_CLI_STATUS_SUCCESS
                                   : PI_CLI_STATUS_TARGET_ERROR;
};

char *complete_table_set_default(const char *text, int state) {
  return complete_table(text, state);
}


text:
<?xml version="1.0"?>
<!-- This build file can be used within an IDE environment to bind the JiBX
  binding definition model classes - after building or modifying the model
  classes, run the default "bind" target of this script to compile the internal
  bindings. -->
<project basedir="." default="bind">

  <!-- JiBX binding compiler task definition -->
  <property environment="env"/>
  <property name="jibxhome" value="${basedir}/.."/>
  <taskdef name="bind" classname="org.jibx.binding.ant.CompileTask">
    <classpath>
      <pathelement location="${jibxhome}/lib/bcel.jar"/>
      <pathelement location="${jibxhome}/lib/jibx-bind.jar"/>
      <pathelement location="${jibxhome}/lib/jibx-run.jar"/>
      <pathelement location="${jibxhome}/lib/jibx-extras.jar"/>
      <pathelement location="${jibxhome}/lib/joda-time.jar"/>
      <pathelement location="${jibxhome}/lib/xpp3.jar"/>
    </classpath>
  </taskdef>

  <!-- bind the class files -->
  <target name="bind">
    <echo message="Running binding compiler..."/>
    <bind load="true">
      <bindingfileset dir="${basedir}/src">
        <include name="binding-normal.xml"/>
        <include name="binding-precomp.xml"/>
        <include name="class-customs-binding.xml"/>
        <include name="schema-extract-binding.xml"/>
        <include name="schema-noprefix-binding.xml"/>
        <include name="schema-xsprefix-binding.xml"/>
        <include name="wsdl-binding.xml"/>
        <include name="wsdlgen-customs-binding.xml"/>
        <include name="xsdcodegen-customs-binding.xml"/>
      </bindingfileset>
      <classpathset dir="${jibxhome}/lib/jibx-run.jar"/>
      <classpathset dir="${jibxhome}/lib/jibx-extras.jar"/>
      <classpathset dir="${basedir}/classes/main"/>
    </bind>
  </target>

</project>


text:
var phonecatServices = angular.module('MetroServices', ['ngResource']);

phonecatServices.factory('DelhiMetro', ['$resource',
  function($resource){
    return $resource('data/:metroId.json', {}, {
      query: {method:'GET', params:{metroId:'DelhiMetroStations'}, isArray:true}
    });
  }]);


text:
import {isBlank, isPresent, BaseException} from 'angular2/src/facade/lang';
import {DOM, TemplateElement} from 'angular2/src/facade/dom';
import {MapWrapper, ListWrapper} from 'angular2/src/facade/collection';

import {Parser} from 'angular2/change_detection';

import {CompileStep} from './compile_step';
import {CompileElement} from './compile_element';
import {CompileControl} from './compile_control';
import {StringWrapper} from 'angular2/src/facade/lang';

import {$BANG} from 'angular2/src/change_detection/parser/lexer';

/**
 * Splits views at `<template>` elements or elements with `template` attribute:
 * For `<template>` elements:
 * - moves the content into a new and disconnected `<template>` element
 *   that is marked as view root.
 *
 * For elements with a `template` attribute:
 * - replaces the element with an empty `<template>` element,
 *   parses the content of the `template` attribute and adds the information to that
 *   `<template>` element. Marks the elements as view root.
 *
 * Note: In both cases the root of the nested view is disconnected from its parent element.
 * This is needed for browsers that don't support the `<template>` element
 * as we want to do locate elements with bindings using `getElementsByClassName` later on,
 * which should not descend into the nested view.
 *
 * Fills:
 * - CompileElement#isViewRoot
 * - CompileElement#variableBindings
 * - CompileElement#propertyBindings
 */
export class ViewSplitter extends CompileStep {
  _parser:Parser;
  _compilationUnit:any;
  constructor(parser:Parser, compilationUnit:any) {
    super();
    this._parser = parser;
    this._compilationUnit = compilationUnit;
  }

  process(parent:CompileElement, current:CompileElement, control:CompileControl) {
    if (isBlank(parent)) {
      current.isViewRoot = true;
    } else {
      if (current.element instanceof TemplateElement) {
        if (!current.isViewRoot) {
          var viewRoot = new CompileElement(DOM.createTemplate(''));
          var currentElement:TemplateElement = current.element;
          var viewRootElement:TemplateElement = viewRoot.element;
          this._moveChildNodes(currentElement.content, viewRootElement.content);
          viewRoot.isViewRoot = true;
          control.addChild(viewRoot);
        }
      } else {
        var attrs = current.attrs();
        var templateBindings = MapWrapper.get(attrs, 'template');
        var hasTemplateBinding = isPresent(templateBindings);

        // look for template shortcuts such as !if="condition" and treat them as template="if condition"
        MapWrapper.forEach(attrs, (attrValue, attrName) => {
          if (StringWrapper.charCodeAt(attrName, 0) == $BANG) {
            var key = StringWrapper.substring(attrName, 1);  // remove the bang
            if (hasTemplateBinding) {
              // 2nd template binding detected
              throw new BaseException(`Only one template directive per element is allowed: ` +
                  `${templateBindings} and ${key} cannot be used simultaneously!`);
            } else {
              templateBindings = (attrValue.length == 0) ? key : key + ' ' + attrValue;
              hasTemplateBinding = true;
            }
          }
        });

        if (hasTemplateBinding) {
          var newParent = new CompileElement(DOM.createTemplate(''));
          current.isViewRoot = true;
          this._parseTemplateBindings(templateBindings, newParent);
          this._addParentElement(current.element, newParent.element);

          control.addParent(newParent);
          current.element.remove();
        }
      }
    }
  }

  _moveChildNodes(source, target) {
    while (isPresent(source.firstChild)) {
      DOM.appendChild(target, source.firstChild);
    }
  }

  _addParentElement(currentElement, newParentElement) {
    DOM.insertBefore(currentElement, newParentElement);
    DOM.appendChild(newParentElement, currentElement);
  }

  _parseTemplateBindings(templateBindings:string, compileElement:CompileElement) {
    var bindings = this._parser.parseTemplateBindings(templateBindings, this._compilationUnit);
    for (var i=0; i<bindings.length; i++) {
      var binding = bindings[i];
      if (binding.keyIsVar) {
        compileElement.addVariableBinding(binding.key, binding.name);
      } else if (isPresent(binding.expression)) {
        compileElement.addPropertyBinding(binding.key, binding.expression);
      } else {
        compileElement.element.setAttribute(binding.key, '');
      }
    }
  }
}


text:
<?php
  session_start();
  if(empty($_SESSION['userid'])) exit;

  include_once "base.php";
  include_once "func.php";

    if($_SERVER['REQUEST_METHOD']=='POST' && $_POST['action']=='delete'){

   	    $code=mysql_real_escape_string($_POST['code']);
   	    $sql="DELETE  FROM `brand` WHERE brand_code='$code'";
   	    $result=mysql_query($sql);
   	    if(!$result) die("MySQL Error: ".mysql_error());
   	    exit;

   }
  if($_SERVER['REQUEST_METHOD']=='POST' && $_POST['action']=='save'){

   	    $code=mysql_real_escape_string($_POST['code']);
   	    //check custcode availibilty
   	     if( is_brand_code_exist($code)) {
   	     	 echo "This brand Code had been taken.";
   	     	 exit;
   	     }
   	    $desc=mysql_real_escape_string($_POST['desc']);
   	    $active=mysql_real_escape_string($_POST['active']);

   	    if($active) $active='Y';
   	    else $active='N';
   	    $sql="INSERT INTO `brand`(brand_code,brand_desc,active) VALUES ('$code','$desc','$active')";
   	    $result=mysql_query($sql);
   	    if(!$result) die("MySQL Error: ".mysql_error());
   	    exit;

   }
    if($_SERVER['REQUEST_METHOD']=='POST' && $_POST['action']=='update'){

   	    $code=mysql_real_escape_string($_POST['code']);
   	    $desc=mysql_real_escape_string($_POST['desc']);
   	    $active=mysql_real_escape_string($_POST['active']);
  	    if($active) $active='Y';
   	    else $active='N';
   	    $sql="UPDATE `brand` SET brand_desc='$desc',active='$active' WHERE brand_code='$code'";
   	    $result=mysql_query($sql);
   	    if(!$result) die("MySQL Error: ".mysql_error());
   	    exit;

   }
    if($_SERVER['REQUEST_METHOD']=='POST' && ($_POST['action']=='view' || $_POST['action']=='edit')){
    	$code=$_POST['code'];
    	$sql="SELECT brand_code,brand_desc,active from `brand` WHERE brand_code='$code'";
    	$result=mysql_query($sql);
    	if(!$result) die('MySql Error: '.mysql_error());
    	if(mysql_num_rows($result)>0){
    	 $data = mysql_fetch_array($result);
    	}else{echo "Record Not Found";}

    }

?>
<?php if($_POST['action']=='view'){ ?>

<button style='float:right;' onclick="open_menu('brand_form',{action:'edit',code:'<?php echo $data[0]; ?>'});" type='submit'>Edit</button><button onclick="open_menu('brand_browse');" > Back</button>

brand Code:	<?php echo $data['0']; ?>

Description:	<?php echo $data['1']; ?>

Staus:	<?php if($data['2']=='Y') echo 'ACTIVE'; else echo 'IN-ACTIVE'; ?>

<?php }elseif($_POST['action']=='edit'){ ?>
   <form id='frm' name='frm'>

<button style='float:right;' type='submit'>Save</button>
<button onclick="open_menu('brand_browse');return false;">Cancel</button>

     <input type='checkbox' <?php if($data[2]=='Y')echo 'checked="checked"'; ?> id='active' name='active'></input>Active

brand Code:	<?php echo $data[0]; ?>

Description:	<input maxlength='150' id='desc' name='desc' value="<?php echo $data[1]; ?>" />

	 <button style="width:250px;" class='form deletebutton'>Delete Brand</button>

      <input type='hidden' id='action' name='action' value='update' />
      <input type='hidden' id='code' name='code' value='<?php echo $data[0]; ?>' />

     Delete this Credit brand?

     Save changes?

 </form>
<?php } else { ?>
<form id='frm' name='frm'>

<button style='float:right;' type='submit'>Save</button>
<button onclick="open_menu('brand_browse');return false;">Cancel</button>

     <input type='checkbox' checked="checked" id='active' name='active'></input>Active

brand Code:	<input maxlength='10' id='code' name='code'  />

Description:	<input maxlength='150' id='desc' name='desc'  />

     <input type='hidden' id='action' name='action' value='save' />

 </form>
<?php } ?>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Text;
using OmniSharp.Roslyn;

namespace OmniSharp.Cake.Services.RequestHandlers.Navigation
{
    public static class GotoDefinitionHandlerHelper
    {
        private const int MethodLineOffset = 3;
        private const int PropertyLineOffset = 7;

        internal static async Task<IEnumerable<Alias>> GetAliasFromMetadataAsync(
            OmniSharpWorkspace workspace,
            string fileName,
            int line,
            int timeout,
            MetadataExternalSourceService metadataExternalSourceService)
        {
            var document = workspace.GetDocument(fileName);
            var lineIndex = line + MethodLineOffset;
            int column;

            if (document == null)
            {
                return Enumerable.Empty<Alias>();
            }

            var semanticModel = await document.GetSemanticModelAsync();
            var sourceText = await document.GetTextAsync();
            var sourceLine = sourceText.Lines[lineIndex].ToString();
            if (sourceLine.Contains("(Context"))
            {
                column = sourceLine.IndexOf("(Context", StringComparison.Ordinal);
            }
            else
            {
                lineIndex = line + PropertyLineOffset;
                sourceLine = sourceText.Lines[lineIndex].ToString();
                if (sourceLine.Contains("(Context"))
                {
                    column = sourceLine.IndexOf("(Context", StringComparison.Ordinal);
                }
                else
                {
                    return Enumerable.Empty<Alias>();
                }
            }

            if (column > 0 && sourceLine[column - 1] == '>')
            {
                column = sourceLine.LastIndexOf("<", column, StringComparison.Ordinal);
            }

            var position = sourceText.Lines.GetPosition(new LinePosition(lineIndex, column));
            var symbol = await SymbolFinder.FindSymbolAtPositionAsync(semanticModel, position, workspace);

            if (symbol == null || symbol is INamespaceSymbol)
            {
                return Enumerable.Empty<Alias>();
            }
            if (symbol is IMethodSymbol method)
            {
                symbol = method.PartialImplementationPart ?? symbol;
            }

            var result = new List<Alias>();
            foreach (var location in symbol.Locations)
            {
                if (!location.IsInMetadata)
                {
                    continue;
                }

                var cancellationSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(timeout));
                var (metadataDocument, _) = await metadataExternalSourceService.GetAndAddExternalSymbolDocument(document.Project, symbol, cancellationSource.Token);
                if (metadataDocument == null)
                {
                    continue;
                }

                cancellationSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(timeout));
                var metadataLocation = await metadataExternalSourceService.GetExternalSymbolLocation(symbol, metadataDocument, cancellationSource.Token);
                var lineSpan = metadataLocation.GetMappedLineSpan();

                result.Add(new Alias
                {
                    Document = document,
                    MetadataDocument = metadataDocument,
                    Symbol = symbol,
                    Location = location,
                    LineSpan = lineSpan
                });
            }

            return result;
        }

        internal class Alias
        {
            public Document Document { get; set; }
            public ISymbol Symbol { get; set; }
            public Location Location { get; set; }
            public FileLinePositionSpan LineSpan { get; set; }
            public Document MetadataDocument { get; set; }
        }
    }
}


text:
package net.doubledoordev.torchtools;

import cpw.mods.fml.client.config.IConfigElement;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.doubledoordev.d3core.D3Core;
import net.doubledoordev.d3core.util.ID3Mod;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemTool;
import net.minecraft.network.play.server.S2FPacketSetSlot;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.config.ConfigElement;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import org.apache.logging.log4j.Logger;

import java.util.List;

import static net.minecraftforge.event.entity.player.PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK;

/**
 * Main mod file
 *
 * Thanks for the idea Tinkers Construct
 *
 * @author Dries007
 * @author DoubleDoorDevelopment
 */
@Mod(modid = TorchTools.MODID, name = TorchTools.MODID)
public class TorchTools implements ID3Mod
{
    public static final String MODID = "TorchTools";

    @Mod.Instance(MODID)
    public static TorchTools instance;

    private Logger      logger;
    private int[] slots = {8, 2, 3, 4, 5, 6, 7, 8, -1};
    private Configuration configuration;
    private boolean disableTE = true;

    public TorchTools()
    {
        MinecraftForge.EVENT_BUS.register(this);
    }

    @Mod.EventHandler
    public void preInit(FMLPreInitializationEvent event)
    {
        logger = event.getModLog();
        configuration = new Configuration(event.getSuggestedConfigurationFile());
        syncConfig();
    }

    /**
     * This method is the mod. Everything else is extra
     */
    @SubscribeEvent
    public void playerInteractEventHandler(PlayerInteractEvent event)
    {
        // Server side and on block only.
        if (event.isCanceled() || event.world.isRemote || event.action != RIGHT_CLICK_BLOCK) return;
        ItemStack heldItem = event.entityPlayer.inventory.getCurrentItem();
        // Only tools, not null
        if (heldItem == null || !(heldItem.getItem() instanceof ItemTool)) return;
        // disableTE code
        if (disableTE && event.world.getTileEntity(event.x, event.y, event.z) != null) return;
        // Save old slot id
        int oldSlot = event.entityPlayer.inventory.currentItem;
        // Avoid invalid array indexes
        if (oldSlot < 0 || oldSlot > 8) return;
        // Get the new slot id
        int newSlot = slots[oldSlot];
        // Avoid invalid slots indexes
        if (newSlot < 0 || newSlot > 8) return;
        // Get new item
        ItemStack slotStack = event.entityPlayer.inventory.getStackInSlot(newSlot);
        // No null please
        if (slotStack == null) return;
        // Set current slot to new slot to fool Minecraft
        event.entityPlayer.inventory.currentItem = newSlot;
        // Debug info
        if (D3Core.debug()) logger.info("Player: " + event.entityPlayer.getDisplayName() + "\tOldSlot: " + oldSlot + "\tOldStack: " + slotStack);
        // Fake right click                                                                                Oh look fake values :p
        boolean b = ((EntityPlayerMP) event.entityPlayer).theItemInWorldManager.activateBlockOrUseItem(event.entityPlayer, event.world, slotStack, event.x, event.y, event.z, event.face, 0.5f, 0.5f, 0.5f);
        // Remove empty stacks
        if (slotStack.stackSize <= 0) slotStack = null;
        // Debug info
        if (D3Core.debug()) logger.info("Player: " + event.entityPlayer.getDisplayName() + "\tNewSlot: " + newSlot + "\tNewStack: " + slotStack + "\tResult: " + b);
        // Set old slot back properly
        event.entityPlayer.inventory.currentItem = oldSlot;
        // Update client
        event.entityPlayer.inventory.setInventorySlotContents(newSlot, slotStack);
        ((EntityPlayerMP) event.entityPlayer).playerNetServerHandler.sendPacket(new S2FPacketSetSlot(0, newSlot + 36, slotStack));
        // Prevent derpy doors
        event.setCanceled(true);
    }

    @Override
    public void syncConfig()
    {
        disableTE = configuration.getBoolean("disableTE", MODID.toLowerCase(), disableTE, "This prevents the place effect from occurring when you are right clicking on a tileentity. Use for dupe glitches.");

        if (configuration.hasChanged()) configuration.save();
    }

    @Override
    public void addConfigElements(List<IConfigElement> configElements)
    {
        configElements.add(new ConfigElement(configuration.getCategory(MODID.toLowerCase())));
    }
}


text:
package org.hisp.dhis.webapi.controller;

import org.hisp.dhis.chart.Chart;
import org.hisp.dhis.common.AnalyticalObject;
import org.hisp.dhis.common.IdentifiableObjectManager;
import org.hisp.dhis.dataset.DataSet;
import org.hisp.dhis.dxf2.webmessage.WebMessageException;
import org.hisp.dhis.dxf2.webmessage.WebMessageUtils;
import org.hisp.dhis.eventchart.EventChart;
import org.hisp.dhis.eventreport.EventReport;
import org.hisp.dhis.interpretation.Interpretation;
import org.hisp.dhis.interpretation.InterpretationComment;
import org.hisp.dhis.interpretation.InterpretationService;
import org.hisp.dhis.mapping.Map;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.period.Period;
import org.hisp.dhis.period.PeriodType;
import org.hisp.dhis.reporttable.ReportTable;
import org.hisp.dhis.schema.descriptors.InterpretationSchemaDescriptor;
import org.hisp.dhis.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;

/**
 * @author Lars Helge Overland
 */
@Controller
@RequestMapping( value = InterpretationSchemaDescriptor.API_ENDPOINT )
public class InterpretationController
    extends AbstractCrudController<Interpretation>
{
    @Autowired
    private InterpretationService interpretationService;

    @Autowired
    private IdentifiableObjectManager idObjectManager;

    // -------------------------------------------------------------------------
    // Intepretation create
    // -------------------------------------------------------------------------

    @RequestMapping( value = "/reportTable/{uid}", method = RequestMethod.POST, consumes = { "text/html", "text/plain" } )
    public void writeReportTableInterpretation(
        @PathVariable( "uid" ) String reportTableUid,
        @RequestParam( value = "pe", required = false ) String isoPeriod,
        @RequestParam( value = "ou", required = false ) String orgUnitUid,
        @RequestBody String text,
        HttpServletResponse response, HttpServletRequest request ) throws WebMessageException
    {
        ReportTable reportTable = idObjectManager.get( ReportTable.class, reportTableUid );

        if ( reportTable == null )
        {
            throw new WebMessageException( WebMessageUtils.conflict( "Report table does not exist or is not accessible: " + reportTableUid ) );
        }

        Period period = PeriodType.getPeriodFromIsoString( isoPeriod );

        OrganisationUnit orgUnit = getUserOrganisationUnit( orgUnitUid, reportTable, currentUserService.getCurrentUser() );

        createIntepretation( new Interpretation( reportTable, period, orgUnit, text ), request, response );
    }

    @RequestMapping( value = "/chart/{uid}", method = RequestMethod.POST, consumes = { "text/html", "text/plain" } )
    public void writeChartInterpretation(
        @PathVariable( "uid" ) String uid,
        @RequestParam( value = "ou", required = false ) String orgUnitUid,
        @RequestBody String text,
        HttpServletResponse response, HttpServletRequest request ) throws WebMessageException
    {
        Chart chart = idObjectManager.get( Chart.class, uid );

        if ( chart == null )
        {
            throw new WebMessageException( WebMessageUtils.conflict( "Chart does not exist or is not accessible: " + uid ) );
        }

        OrganisationUnit orgUnit = getUserOrganisationUnit( orgUnitUid, chart, currentUserService.getCurrentUser() );

        createIntepretation( new Interpretation( chart, orgUnit, text ), request, response );
    }

    @RequestMapping( value = "/map/{uid}", method = RequestMethod.POST, consumes = { "text/html", "text/plain" } )
    public void writeMapInterpretation(
        @PathVariable( "uid" ) String uid,
        @RequestBody String text,
        HttpServletResponse response, HttpServletRequest request ) throws WebMessageException
    {
        Map map = idObjectManager.get( Map.class, uid );

        if ( map == null )
        {
            throw new WebMessageException( WebMessageUtils.conflict( "Map does not exist or is not accessible: " + uid ) );
        }

        createIntepretation( new Interpretation( map, text ), request, response );
    }

    @RequestMapping( value = "/eventReport/{uid}", method = RequestMethod.POST, consumes = { "text/html", "text/plain" } )
    public void writeEventReportInterpretation(
        @PathVariable( "uid" ) String uid,
        @RequestParam( value = "ou", required = false ) String orgUnitUid,
        @RequestBody String text,
        HttpServletResponse response, HttpServletRequest request ) throws WebMessageException
    {
        EventReport eventReport = idObjectManager.get( EventReport.class, uid );

        if ( eventReport == null )
        {
            throw new WebMessageException( WebMessageUtils.conflict( "Event report does not exist or is not accessible: " + uid ) );
        }

        OrganisationUnit orgUnit = getUserOrganisationUnit( orgUnitUid, eventReport, currentUserService.getCurrentUser() );

        createIntepretation( new Interpretation( eventReport, orgUnit, text ), request, response );
    }

    @RequestMapping( value = "/eventChart/{uid}", method = RequestMethod.POST, consumes = { "text/html", "text/plain" } )
    public void writeEventChartInterpretation(
        @PathVariable( "uid" ) String uid,
        @RequestParam( value = "ou", required = false ) String orgUnitUid,
        @RequestBody String text,
        HttpServletResponse response, HttpServletRequest request ) throws WebMessageException
    {
        EventChart eventChart = idObjectManager.get( EventChart.class, uid );

        if ( eventChart == null )
        {
            throw new WebMessageException( WebMessageUtils.conflict( "Event chart does not exist or is not accessible: " + uid ) );
        }

        OrganisationUnit orgUnit = getUserOrganisationUnit( orgUnitUid, eventChart, currentUserService.getCurrentUser() );

        createIntepretation( new Interpretation( eventChart, orgUnit, text ), request, response );
    }

    @RequestMapping( value = "/dataSetReport/{uid}", method = RequestMethod.POST, consumes = { "text/html", "text/plain" } )
    public void writeDataSetReportInterpretation(
        @PathVariable( "uid" ) String dataSetUid,
        @RequestParam( "pe" ) String isoPeriod,
        @RequestParam( "ou" ) String orgUnitUid,
        @RequestBody String text,
        HttpServletResponse response, HttpServletRequest request ) throws WebMessageException
    {
        DataSet dataSet = idObjectManager.get( DataSet.class, dataSetUid );

        if ( dataSet == null )
        {
            throw new WebMessageException( WebMessageUtils.conflict( "Data set does not exist or is not accessible: " + dataSetUid ) );
        }

        Period period = PeriodType.getPeriodFromIsoString( isoPeriod );

        if ( period == null )
        {
            throw new WebMessageException( WebMessageUtils.conflict( "Period identifier not valid: " + isoPeriod ) );
        }

        OrganisationUnit orgUnit = idObjectManager.get( OrganisationUnit.class, orgUnitUid );

        if ( orgUnit == null )
        {
            throw new WebMessageException( WebMessageUtils.conflict( "Organisation unit does not exist or is not accessible: " + orgUnitUid ) );
        }

        createIntepretation( new Interpretation( dataSet, period, orgUnit, text ), request, response );
    }

    /**
     * Returns the organisation unit with the given identifier. If not existing,
     * returns the user organisation unit if the analytical object specifies
     * a user organisation unit. If not, returns null.
     */
    private OrganisationUnit getUserOrganisationUnit( String uid, AnalyticalObject analyticalObject, User user )
        throws WebMessageException
    {
        OrganisationUnit unit = null;

        if ( uid != null )
        {
            unit = idObjectManager.get( OrganisationUnit.class, uid );

            if ( unit == null )
            {
                throw new WebMessageException( WebMessageUtils.conflict( "Organisation unit does not exist or is not accessible: " + uid ) );
            }

            return unit;
        }
        else if ( analyticalObject.hasUserOrgUnit() && user.hasOrganisationUnit() )
        {
            unit = user.getOrganisationUnit();
        }

        return unit;
    }

    /**
     * Saves the given interpretation, adds location header and returns a web
     * message response.
     */
    private void createIntepretation( Interpretation interpretation, HttpServletRequest request, HttpServletResponse response )
    {
        interpretationService.saveInterpretation( interpretation );

        response.addHeader( "Location", InterpretationSchemaDescriptor.API_ENDPOINT + "/" + interpretation.getUid() );

        webMessageService.send( WebMessageUtils.created( "Interpretation created" ), response, request );
    }

    // -------------------------------------------------------------------------
    // Interpretation update
    // -------------------------------------------------------------------------

    @RequestMapping( value = "/{uid}", method = RequestMethod.PUT )
    @ResponseStatus( HttpStatus.NO_CONTENT )
    public void updateInterpretation( @PathVariable( "uid" ) String uid, @RequestBody String text,
        HttpServletResponse response ) throws WebMessageException
    {
        Interpretation interpretation = interpretationService.getInterpretation( uid );

        if ( interpretation == null )
        {
            throw new WebMessageException( WebMessageUtils.notFound( "Interpretation does not exist: " + uid ) );
        }

        if ( !currentUserService.getCurrentUser().equals( interpretation.getUser() ) &&
            !currentUserService.currentUserIsSuper() )
        {
            throw new AccessDeniedException( "You are not allowed to update this interpretation." );
        }

        interpretation.setText( text );

        interpretationService.updateInterpretation( interpretation );
    }

    @Override
    public void deleteObject( @PathVariable String uid, HttpServletRequest request, HttpServletResponse response ) throws Exception
    {
        Interpretation interpretation = interpretationService.getInterpretation( uid );

        if ( interpretation == null )
        {
            throw new WebMessageException( WebMessageUtils.notFound( "Interpretation does not exist: " + uid ) );
        }

        if ( !currentUserService.getCurrentUser().equals( interpretation.getUser() ) &&
            !currentUserService.currentUserIsSuper() )
        {
            throw new AccessDeniedException( "You are not allowed to delete this interpretation." );
        }

        interpretationService.deleteInterpretation( interpretation );
    }

    // -------------------------------------------------------------------------
    // Comment
    // -------------------------------------------------------------------------

    @RequestMapping( value = "/{uid}/comments", method = RequestMethod.POST, consumes = { "text/html", "text/plain" } )
    public void postComment(
        @PathVariable( "uid" ) String uid,
        @RequestBody String text, HttpServletResponse response, HttpServletRequest request ) throws WebMessageException
    {
        Interpretation interpretation = interpretationService.getInterpretation( uid );

        if ( interpretation == null )
        {
            throw new WebMessageException( WebMessageUtils.conflict( "Interpretation does not exist: " + uid ) );
        }

        InterpretationComment comment = interpretationService.addInterpretationComment( uid, text );

        String builder = InterpretationSchemaDescriptor.API_ENDPOINT + "/" + uid +
            "/comments/" + comment.getUid();

        response.addHeader( "Location", builder );
        webMessageService.send( WebMessageUtils.created( "Commented created" ), response, request );
    }

    @RequestMapping( value = "/{uid}/comments/{cuid}", method = RequestMethod.PUT )
    @ResponseStatus( HttpStatus.NO_CONTENT )
    public void updateComment( @PathVariable( "uid" ) String uid, @PathVariable( "cuid" ) String cuid, HttpServletResponse response,
        @RequestBody String content ) throws WebMessageException
    {
        Interpretation interpretation = interpretationService.getInterpretation( uid );

        if ( interpretation == null )
        {
            throw new WebMessageException( WebMessageUtils.conflict( "Interpretation does not exist: " + uid ) );
        }

        for ( InterpretationComment comment : interpretation.getComments() )
        {
            if ( comment.getUid().equals( cuid ) )
            {
                if ( !currentUserService.getCurrentUser().equals( comment.getUser() ) &&
                    !currentUserService.currentUserIsSuper() )
                {
                    throw new AccessDeniedException( "You are not allowed to update this comment." );
                }

                comment.setText( content );
            }
        }

        interpretationService.updateInterpretation( interpretation );
    }

    @RequestMapping( value = "/{uid}/comments/{cuid}", method = RequestMethod.DELETE )
    @ResponseStatus( HttpStatus.NO_CONTENT )
    public void deleteComment( @PathVariable( "uid" ) String uid, @PathVariable( "cuid" ) String cuid, HttpServletResponse response ) throws WebMessageException
    {
        Interpretation interpretation = interpretationService.getInterpretation( uid );

        if ( interpretation == null )
        {
            throw new WebMessageException( WebMessageUtils.conflict( "Interpretation does not exist: " + uid ) );
        }

        Iterator<InterpretationComment> iterator = interpretation.getComments().iterator();

        while ( iterator.hasNext() )
        {
            InterpretationComment comment = iterator.next();

            if ( comment.getUid().equals( cuid ) )
            {
                if ( !currentUserService.getCurrentUser().equals( comment.getUser() ) &&
                    !currentUserService.currentUserIsSuper() )
                {
                    throw new AccessDeniedException( "You are not allowed to delete this comment." );
                }

                iterator.remove();
            }
        }

        interpretationService.updateInterpretation( interpretation );
    }

    // -------------------------------------------------------------------------
    // Likes
    // -------------------------------------------------------------------------

    @RequestMapping( value = "/{uid}/like", method = RequestMethod.POST )
    public void like( @PathVariable( "uid" ) String uid,
        HttpServletResponse response, HttpServletRequest request ) throws WebMessageException
    {
        Interpretation interpretation = interpretationService.getInterpretation( uid );

        if ( interpretation == null )
        {
            throw new WebMessageException( WebMessageUtils.conflict( "Interpretation does not exist: " + uid ) );
        }

        boolean like = interpretationService.likeInterpretation( interpretation.getId() );

        if ( like )
        {
            webMessageService.send( WebMessageUtils.created( "Like added to interpretation" ), response, request );
        }
        else
        {
            webMessageService.send( WebMessageUtils.conflict( "Could not add like, user had already liked interpretation" ), response, request );
        }
    }

    @RequestMapping( value = "/{uid}/like", method = RequestMethod.DELETE )
    public void unlike( @PathVariable( "uid" ) String uid,
        HttpServletResponse response, HttpServletRequest request ) throws WebMessageException
    {
        Interpretation interpretation = interpretationService.getInterpretation( uid );

        if ( interpretation == null )
        {
            throw new WebMessageException( WebMessageUtils.conflict( "Interpretation does not exist: " + uid ) );
        }

        boolean like = interpretationService.unlikeInterpretation( interpretation.getId() );

        if ( like )
        {
            webMessageService.send( WebMessageUtils.created( "Like removed from interpretation" ), response, request );
        }
        else
        {
            webMessageService.send( WebMessageUtils.conflict( "Could not remove like, user had not previously liked interpretation" ), response, request );
        }
    }
}


text:
package persist;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

import com.sleepycat.bind.EntryBinding;
import com.sleepycat.bind.serial.SerialBinding;
import com.sleepycat.bind.serial.StoredClassCatalog;
import com.sleepycat.bind.tuple.IntegerBinding;
import com.sleepycat.bind.tuple.LongBinding;
import com.sleepycat.db.Cursor;
import com.sleepycat.db.Database;
import com.sleepycat.db.DatabaseConfig;
import com.sleepycat.db.DatabaseEntry;
import com.sleepycat.db.DatabaseException;
import com.sleepycat.db.DatabaseType;
import com.sleepycat.db.Environment;
import com.sleepycat.db.EnvironmentConfig;
import com.sleepycat.db.OperationStatus;
import com.sleepycat.db.SecondaryConfig;
import com.sleepycat.db.SecondaryCursor;
import com.sleepycat.db.SecondaryDatabase;
import com.sleepycat.db.SecondaryKeyCreator;
import com.sleepycat.db.Transaction;

/**
 * EventExample is a trivial example which stores Java objects that represent
 * an event. Events are primarily indexed by a timestamp, but have other
 * attributes, such as price, account reps, customer name and quantity.
 * Some of those other attributes are indexed.
 *

 * The example simply shows the creation of a BDB environment and database,
 * inserting some events, and retrieving the events.
 *

 * This example is meant to be paired with its twin, EventExampleDPL.java.
 * EventExample.java and EventExampleDPL.java perform the same functionality,
 * but use the Base API and the Direct Persistence Layer API, respectively.
 * This may be a useful way to compare the two APIs.
 *

 * To run the example:
 *

 * cd jehome/examples
 * javac je/EventExample.java
 * java je.EventExample -h <environmentDirectory>
 *

 */
public class EventExample {

    /*
     * The Event class embodies our example event and is the application
     * data. BDB data records are represented at key/data tuples. In this
     * example, the key portion of the record is the event time, and the data
     * portion is the Event instance.
     */
    static class Event implements Serializable {

        /* This example will add secondary indices on price and accountReps. */
        private int price;
        private Set<String> accountReps;

        private String customerName;
        private int quantity;

        Event(int price,
              String customerName) {

            this.price = price;
            this.customerName = customerName;
            this.accountReps = new HashSet<String>();
        }

        void addRep(String rep) {
            accountReps.add(rep);
        }

        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            sb.append(" price=").append(price);
            sb.append(" customerName=").append(customerName);
            sb.append(" reps=");
            if (accountReps.size() == 0) {
                sb.append("none");
            } else {
                for (String rep: accountReps) {
                    sb.append(rep).append(" ");
                }
            }
            return sb.toString();
        }

        int getPrice() {
            return price;
        }
    }

    /* A BDB environment is roughly equivalent to a relational database. */
    private Environment env;

    /*
     * A BDB table is roughly equivalent to a relational table with a
     * primary index.
     */
    private Database eventDb;

    /* A secondary database indexes an additional field of the data record */
    private SecondaryDatabase eventByPriceDb;

    /*
     * The catalogs and bindings are used to convert Java objects to the byte
     * array format used by BDB key/data in the base API. The Direct
     * Persistence Layer API supports Java objects as arguments directly.
     */
    private Database catalogDb;
    private EntryBinding eventBinding;

    /* Used for generating example data. */
    private Calendar cal;

    /*
     * First manually make a directory to house the BDB environment.
     * Usage: java EventExample -h <envHome>
     * All BDB on-disk storage is held within envHome.
     */
    public static void main(String[] args)
        throws DatabaseException, FileNotFoundException {

        if (args.length != 2 || !"-h".equals(args[0])) {
            System.err.println
                ("Usage: java " + EventExample.class.getName() +
                 " -h <envHome>");
            System.exit(2);
        }
        EventExample example = new EventExample(new File(args[1]));
        example.run();
        example.close();
    }

    private EventExample(File envHome)
        throws DatabaseException, FileNotFoundException {

        /* Open a transactional Berkeley DB engine environment. */
        System.out.println("-> Creating a BDB environment");
        EnvironmentConfig envConfig = new EnvironmentConfig();
        envConfig.setAllowCreate(true);
        envConfig.setTransactional(true);
        envConfig.setInitializeCache(true);
        envConfig.setInitializeLocking(true);
        env = new Environment(envHome, envConfig);

        init();
        cal = Calendar.getInstance();
    }

    /**
     * Create all primary and secondary indices.
     */
    private void init()
        throws DatabaseException, FileNotFoundException {

        System.out.println("-> Creating a BDB database");
        DatabaseConfig dbConfig = new DatabaseConfig();
        dbConfig.setTransactional(true);
        dbConfig.setAllowCreate(true);
        dbConfig.setType(DatabaseType.BTREE);
        eventDb = env.openDatabase(null,      // use auto-commit txn
                                   "eventDb", // file name
                                   null,      // database name
                                   dbConfig);

        /*
         * In our example, the database record is composed of a key portion
         * which represents the event timestamp, and a data portion holds an
         * instance of the Event class.
         *
         * BDB's base API accepts and returns key and data as byte arrays, so
         * we need some support for marshaling between objects and byte arrays.
         * We call this binding, and supply a package of helper classes to
         * support this. It's entirely possible to do all binding on your own.
         *
         * A class catalog database is needed for storing class descriptions
         * for the serial binding used below. This avoids storing class
         * descriptions redundantly in each record.
         */
        DatabaseConfig catalogConfig = new DatabaseConfig();
        catalogConfig.setTransactional(true);
        catalogConfig.setAllowCreate(true);
        catalogConfig.setType(DatabaseType.BTREE);
        catalogDb = env.openDatabase(null, "catalogDb", null, catalogConfig);
        StoredClassCatalog catalog = new StoredClassCatalog(catalogDb);

        /*
         * Create a serial binding for Event data objects.  Serial
         * bindings can be used to store any Serializable object.
         * We can use some pre-defined binding classes to convert
         * primitives like the long key value to the a byte array.
         */
        eventBinding = new SerialBinding(catalog, Event.class);

        /*
         * Open a secondary database to allow accessing the primary
         * database a secondary key value. In this case, access events
         * by price.
         */
        SecondaryConfig secConfig = new SecondaryConfig();
        secConfig.setTransactional(true);
        secConfig.setAllowCreate(true);
        secConfig.setType(DatabaseType.BTREE);
        secConfig.setSortedDuplicates(true);
        secConfig.setKeyCreator(new PriceKeyCreator(eventBinding));
        eventByPriceDb = env.openSecondaryDatabase(null,
                                                   "priceDb",
                                                   null,
                                                   eventDb,
                                                   secConfig);

    }

    private void run()
        throws DatabaseException {

        Random rand = new Random();

        /* DatabaseEntry represents the key and data of each record */
        DatabaseEntry key = new DatabaseEntry();
        DatabaseEntry data = new DatabaseEntry();

        /*
         * Create a set of events. Each insertion is a separate, auto-commit
         * transaction.
         */
        System.out.println("-> Inserting 4 events");
        LongBinding.longToEntry(makeDate(1), key);
        eventBinding.objectToEntry(new Event(100, "Company_A"),
                                   data);
        eventDb.put(null, key, data);

        LongBinding.longToEntry(makeDate(2), key);
        eventBinding.objectToEntry(new Event(2, "Company_B"),
                                   data);
        eventDb.put(null, key, data);

        LongBinding.longToEntry(makeDate(3), key);
        eventBinding.objectToEntry(new Event(20, "Company_C"),
                                   data);
        eventDb.put(null, key, data);

        LongBinding.longToEntry(makeDate(4), key);
        eventBinding.objectToEntry(new Event(40, "CompanyD"),
                                   data);
        eventDb.put(null, key, data);

        /* Load a whole set of events transactionally. */
        Transaction txn = env.beginTransaction(null, null);
        int maxPrice = 50;
        System.out.println("-> Inserting some randomly generated events");
        for (int i = 0; i < 25; i++) {
            long time = makeDate(rand.nextInt(365));
            Event e = new Event(rand.nextInt(maxPrice),"Company_X");
            if ((i%2) ==0) {
                e.addRep("Jane");
                e.addRep("Nikunj");
            } else {
                e.addRep("Yongmin");
            }
            LongBinding.longToEntry(time, key);
            eventBinding.objectToEntry(e, data);
            eventDb.put(txn, key, data);
        }
        txn.commitWriteNoSync();

        /*
         * Windows of events - display the events between June 1 and Aug 31
         */
        System.out.println("\n-> Display the events between June 1 and Aug 31");
        long endDate = makeDate(Calendar.AUGUST, 31);

        /* Position the cursor and print the first event. */
        Cursor eventWindow = eventDb.openCursor(null, null);
        LongBinding.longToEntry(makeDate(Calendar.JUNE, 1), key);

        if ((eventWindow.getSearchKeyRange(key,  data, null)) !=
            OperationStatus.SUCCESS) {
            System.out.println("No events found!");
            eventWindow.close();
            return;
        }
        try {
            printEvents(key, data, eventWindow, endDate);
        } finally {
            eventWindow.close();
        }

        /*
         * Display all events, ordered by a secondary index on price.
         */
        System.out.println("\n-> Display all events, ordered by price");
        SecondaryCursor priceCursor =
            eventByPriceDb.openSecondaryCursor(null, null);
        try {
            printEvents(priceCursor);
        } finally {
            priceCursor.close();
        }
    }

    private void close()
        throws DatabaseException {

        eventByPriceDb.close();
        eventDb.close();
        catalogDb.close();
        env.close();
    }

    /**
     * Print all events covered by this cursor up to the end date.  We know
     * that the cursor operates on long keys and Event data items, but there's
     * no type-safe way of expressing that within the BDB base API.
     */
    private void printEvents(DatabaseEntry firstKey,
                             DatabaseEntry firstData,
                             Cursor cursor,
                             long endDate)
        throws DatabaseException {

        System.out.println("time=" +
                           new Date(LongBinding.entryToLong(firstKey)) +
                           eventBinding.entryToObject(firstData));
        DatabaseEntry key = new DatabaseEntry();
        DatabaseEntry data = new DatabaseEntry();

        while (cursor.getNext(key, data, null) ==
               OperationStatus.SUCCESS) {
            if (LongBinding.entryToLong(key) > endDate) {
                break;
            }
            System.out.println("time=" +
                               new Date(LongBinding.entryToLong(key)) +
                               eventBinding.entryToObject(data));
        }
    }

    private void printEvents(SecondaryCursor cursor)
        throws DatabaseException {
        DatabaseEntry timeKey = new DatabaseEntry();
        DatabaseEntry priceKey = new DatabaseEntry();
        DatabaseEntry eventData = new DatabaseEntry();

        while (cursor.getNext(priceKey, timeKey, eventData, null) ==
               OperationStatus.SUCCESS) {
            System.out.println("time=" +
                               new Date(LongBinding.entryToLong(timeKey)) +
                               eventBinding.entryToObject(eventData));
        }
    }

    /**
     * Little utility for making up java.util.Dates for different days, just
     * to generate test data.
     */
    private long makeDate(int day) {

        cal.set((Calendar.DAY_OF_YEAR), day);
        return cal.getTime().getTime();
    }
    /**
     * Little utility for making up java.util.Dates for different days, just
     * to make the test data easier to read.
     */
    private long makeDate(int month, int day) {

        cal.set((Calendar.MONTH), month);
        cal.set((Calendar.DAY_OF_MONTH), day);
        return cal.getTime().getTime();
    }

    /**
     * A key creator that knows how to extract the secondary key from the data
     * entry of the primary database.  To do so, it uses both the dataBinding
     * of the primary database and the secKeyBinding.
     */
    private static class PriceKeyCreator implements SecondaryKeyCreator {

        private EntryBinding dataBinding;

        PriceKeyCreator(EntryBinding eventBinding) {
            this.dataBinding = eventBinding;
        }

        public boolean createSecondaryKey(SecondaryDatabase secondaryDb,
                                          DatabaseEntry keyEntry,
                                          DatabaseEntry dataEntry,
                                          DatabaseEntry resultEntry)
            throws DatabaseException {

            /*
             * Convert the data entry to an Event object, extract the secondary
             * key value from it, and then convert it to the resulting
             * secondary key entry.
             */
            Event e  = (Event) dataBinding.entryToObject(dataEntry);
            int price = e.getPrice();
            IntegerBinding.intToEntry(price, resultEntry);
            return true;
        }
    }
}


text:
using Microsoft.AspNetCore.Razor.TagHelpers;
using OrchardCore.DisplayManagement;
using OrchardCore.DisplayManagement.TagHelpers;

namespace OrchardCore.Demo.TagHelpers
{
    [HtmlTargetElement("baz")]
    public class BazTagHelper : BaseShapeTagHelper
    {
        public BazTagHelper(IShapeFactory shapeFactory, IDisplayHelper displayHelper) :
            base(shapeFactory, displayHelper)
        {
            Type = "Baz";
        }
    }
}


text: Foutief paswoord of sessie-ID in gebruik. Controleer gebruikersnaam en paswoord en log opnieuw in.