text:
var artistDetails = function(filterCopyrighted) {
    return {
        'cezanne':      { name:'Cézanne',      born:'1839', died:'1906', isMain:true,  license:'public'},
        'monet':        { name:'Monet',        born:'1840', died:'1926', isMain:filterCopyrighted, license:'public'},
        'schiele':      { name:'Schiele',      born:'1890', died:'1918', isMain:true,  license:'public'},
        'rembrandt':    { name:'Rembrandt',    born:'1606', died:'1669', isMain:true,  license:'public'},
        'goya':         { name:'Goya',         born:'1746', died:'1828', isMain:true,  license:'public'},
        'degas':        { name:'Degas',        born:'1834', died:'1917', isMain:filterCopyrighted, license:'public'},
        'basquiat':     { name:'Basquiat',     born:'1960', died:'1988', isMain:false, license:'copyrighted'},
        'caravaggio':   { name:'Caravaggio',   born:'1571', died:'1610', isMain:false, license:'public'},
        'davinci':      { name:'Da Vinci',     born:'1452', died:'1519', isMain:false, license:'public'},
        'doig':         { name:'Doig',         born:'1959', died:'',     isMain:false, license:'copyrighted'},
        'duchamp':      { name:'Duchamp',      born:'1887', died:'1968', isMain:false, license:'copyrighted'},
        'elgreco':      { name:'El Greco',     born:'1541', died:'1614', isMain:false, license:'public'},
        'ernst':        { name:'Ernst',        born:'1891', died:'1976', isMain:false, license:'copyrighted'},
        'fischl':       { name:'Fischl',       born:'1948', died:'',     isMain:false, license:'copyrighted'},
        'freud':        { name:'Freud',        born:'1922', died:'2011', isMain:false, license:'copyrighted'},
        'gauguin':      { name:'Gauguin',      born:'1848', died:'1903', isMain:false, license:'public'},
        'giotto':       { name:'Giotto',       born:'1266', died:'1337', isMain:false, license:'public'},
        'guston':       { name:'Guston',       born:'1913', died:'1980', isMain:false, license:'copyrighted'},
        'huizong':      { name:'Huizong',      born:'1082', died:'1135', isMain:false, license:'copyrighted'},
        'ingres':       { name:'Ingres',       born:'1800', died:'1867', isMain:false, license:'public'},
        'klein':        { name:'Klein',        born:'1928', died:'1962', isMain:false, license:'copyrighted'},
        'klimt':        { name:'Klimt',        born:'1862', died:'1918', isMain:false, license:'public'},
        'kooning':      { name:'Kooning',      born:'1904', died:'1997', isMain:false, license:'copyrighted'},
        'koons':        { name:'Koons',        born:'1955', died:'',     isMain:false, license:'copyrighted'},
        'manray':       { name:'Man Ray',      born:'1890', died:'1976', isMain:false, license:'copyrighted'},
        'matisse':      { name:'Matisse',      born:'1869', died:'1954', isMain:true,  license:'copyrighted'},
        'miro':         { name:'Miró',         born:'1893', died:'1983', isMain:false, license:'copyrighted'},
        'mondrian':     { name:'Mondrian',     born:'1872', died:'1944', isMain:false, license:'copyrighted'},
        'nolde':        { name:'Nolde',        born:'1780', died:'1956', isMain:false, license:'copyrighted'},
        'ofili':        { name:'Ofili',        born:'1968', died:'',     isMain:false, license:'copyrighted'},
        'picasso':      { name:'Picasso',      born:'1881', died:'1973', isMain:true,  license:'copyrighted'},
        'pollock':      { name:'Pollock',      born:'1912', died:'1956', isMain:false, license:'copyrighted'},
        'manet':        { name:'Manet',        born:'1832', died:'1883', isMain:false, license:'public'},
        'michelangelo': { name:'Michelangelo', born:'1475', died:'1564', isMain:false, license:'public'},
        'raphael':      { name:'Raphael',      born:'1483', died:'1520', isMain:false, license:'public'},
        'rousseau':     { name:'Rousseau',     born:'1844', died:'1910', isMain:false, license:'public'},
        'rothko':       { name:'Rothko',       born:'1903', died:'1970', isMain:false, license:'copyrighted'},
        'turner':       { name:'Turner',       born:'1775', died:'1851', isMain:false, license:'public'},
        'tuymans':      { name:'Tuymans',      born:'1958', died:'',     isMain:false, license:'copyrighted'},
        'vangogh':      { name:'Van Gogh',     born:'1853', died:'1890', isMain:false, license:'public'},
        'velazquez':    { name:'Velazquez',    born:'1599', died:'1660', isMain:false, license:'public'},
        'warhol':       { name:'Warhol',       born:'1928', died:'1987', isMain:false, license:'copyrighted'},
        'weiwei':       { name:'Weiwei',       born:'1957', died:'',     isMain:false, license:'copyrighted'},
        'yamagata':     { name:'Yamagata',     born:'1948', died:'',     isMain:false, license:'copyrighted'}
    };
}

var pick = function(obj,keys) {
    var copy = {};
    for(var i = 0; i < keys.length; i++) {
        var key = keys[i];
        if(key in obj) copy[key] = obj[key];
    }
    return copy;
};

var extractData = function(filename, relativePath) {
    // A filename has the form "1905 - Acrobate et jeune arlequin - 105x76cm - Gouache on cardboard.jpg"
    var extension = filename.split(".").slice(-1)[0];
    var chunks = filename.replace("." + extension, "").split(" - ").map(function(chunk) { return chunk.trim(); });
    var size = chunks.length;
    var year = size > 0 ? chunks[0] : "Unknown";
    var title = size > 1 ? chunks[1] : "Unknown";
    var dimensions = size > 2 ? chunks[2] : "Unknown";
    var materials = size > 3 ? chunks[3] : "Unknown";

    var tooltipContents = "
"+year+"

"+title+"
";
    if(dimensions != "Unknown") tooltipContents += "
" + dimensions + "
";
    if(materials != "Unknown") tooltipContents += "
" + materials + "
";

    var fancyboxCaption = year + " - " + title + " - " + ((dimensions == "Unknown") ? "Dimensions: unknown" : dimensions) + " - " + ((materials == "Unknown") ? "Materials: unknown" : materials);

    return {
        file:            relativePath + filename,
        thumbFile:       relativePath + "thumbs/" + filename,
        year:            year,
        title:           title,
        dimensions:      dimensions,
        materials:       materials,
        tooltipContents: tooltipContents,
        fancyboxCaption: fancyboxCaption
    };
}

var getDataFromFolder = function(grunt,folderName) {
    var expanded = grunt.task.normalizeMultiTaskFiles(['build/img/'+folderName+'*'],
                tasks: ['jade'],
            },
            css: {
                files: ['src/css/*', 'src/css/**/*'],
                tasks: ['compass'],
            },
            js: {
                files: ['src/js/*', 'src/js/**/*'],
                tasks: ['coffee'],
            },
            img: {
                files: ['src/img/*', 'src/img/**/*'],
                tasks: ['copy:img'],
            },
            image_resize: {
                files: ['data/**/*'],
                tasks: ['image_resize'],
            },
            static: {
                files: ['src/static/*', 'src/static/**/*'],
                tasks: ['copy'],
            }
        }
    });

    // Load plugins
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-compass');
    grunt.loadNpmTasks('grunt-contrib-cssmin');
    grunt.loadNpmTasks('grunt-contrib-coffee');
    grunt.loadNpmTasks('grunt-contrib-imagemin');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-jade');
    grunt.loadNpmTasks('grunt-image-resize');

    // Default tasks
    grunt.registerTask('default', ['copy:dev','compass:dev','coffee:dev','concat','jade:nofilter']);
    grunt.registerTask('filter', ['copy:dev','compass:dev','coffee:dev','concat','jade:filter']);
    grunt.registerTask('dist', ['copy:dist','compass:dist','coffee:dist','cssmin','uglify','imagemin','image_resize','copy:data','jade:nofilter']);
};


text:
/**
 * Created by Yuicon on 2017/6/27.
 */

import Immutable from 'immutable';

export const Entry = Immutable.Record({
  id: null,
  author: null,
  collectionCount: 0,
  commentsCount: 0,
  content: null,
  createdAt: null,
  english: false,
  original: true,
  originalUrl: null,
  title: null,
  type: null,
  updatedAt: null,
  viewsCount: 0
});

redpajama_set_name: RedPajamaGithub


text:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;

namespace RefactoringEssentials.CSharp.Diagnostics
{
    [ExportCodeFixProvider(LanguageNames.CSharp), System.Composition.Shared]
    public class RedundantExplicitNullableCreationCodeFixProvider : CodeFixProvider
    {
        public override ImmutableArray<string> FixableDiagnosticIds
        {
            get
            {
                return ImmutableArray.Create(CSharpDiagnosticIDs.RedundantExplicitNullableCreationAnalyzerID);
            }
        }

        public override FixAllProvider GetFixAllProvider()
        {
            return WellKnownFixAllProviders.BatchFixer;
        }

        public async override Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var document = context.Document;
            var cancellationToken = context.CancellationToken;
            var span = context.Span;
            var diagnostics = context.Diagnostics;
            var root = await document.GetSyntaxRootAsync(cancellationToken);
            var diagnostic = diagnostics.First();
            var objectCreation = root.FindNode(context.Span, getInnermostNodeForTie: true) as ObjectCreationExpressionSyntax;
            var argumentListArgument = objectCreation.ArgumentList.Arguments.FirstOrDefault();
            if (argumentListArgument == null)
                return;

            context.RegisterCodeFix(CodeActionFactory.Create(objectCreation.Span, diagnostic.Severity, "Redundant explicit nullable type creation", token =>
            {
                var newRoot = root.ReplaceNode(objectCreation,
                    argumentListArgument.Expression.WithLeadingTrivia(objectCreation.GetLeadingTrivia()).WithAdditionalAnnotations(Formatter.Annotation));

                return Task.FromResult(document.WithSyntaxRoot(newRoot));
            }), diagnostic);
        }
    }
}


text:
\hypertarget{classhryky_1_1exclusion_1_1_recursive_mutex}{\section{hryky\-:\-:exclusion\-:\-:Recursive\-Mutex Class Reference}
\label{classhryky_1_1exclusion_1_1_recursive_mutex}\index{hryky\-::exclusion\-::\-Recursive\-Mutex@{hryky\-::exclusion\-::\-Recursive\-Mutex}}
}

exclusion object \-: mutex which can be called recursively.

{\ttfamily \#include $<$exclusion\-\_\-recursive\-\_\-mutex.\-h$>$}

\subsection*{Classes}
\begin{DoxyCompactItemize}
\item
class \hyperlink{classhryky_1_1exclusion_1_1_recursive_mutex_1_1_raw}{Raw}
\begin{DoxyCompactList}\small\item\em retrieves the raw object by limited classes. \end{DoxyCompactList}\end{DoxyCompactItemize}
\subsection*{Public Types}
\begin{DoxyCompactItemize}
\item
\hypertarget{classhryky_1_1exclusion_1_1_recursive_mutex_afc05f6bc3336fc6a5830bd3a7cc9b397}{typedef \hyperlink{classhryky_1_1exclusion_1_1_recursive_mutex}{Recursive\-Mutex} \hyperlink{classhryky_1_1exclusion_1_1_recursive_mutex_afc05f6bc3336fc6a5830bd3a7cc9b397}{this\-\_\-type}}\label{classhryky_1_1exclusion_1_1_recursive_mutex_afc05f6bc3336fc6a5830bd3a7cc9b397}

\begin{DoxyCompactList}\small\item\em self. \end{DoxyCompactList}\end{DoxyCompactItemize}
\subsection*{Public Member Functions}
\begin{DoxyCompactItemize}
\item
\hypertarget{classhryky_1_1exclusion_1_1_recursive_mutex_a60ff5674a9b3ab8a01151450ee99a052}{void \hyperlink{classhryky_1_1exclusion_1_1_recursive_mutex_a60ff5674a9b3ab8a01151450ee99a052}{lock} ()}\label{classhryky_1_1exclusion_1_1_recursive_mutex_a60ff5674a9b3ab8a01151450ee99a052}

\begin{DoxyCompactList}\small\item\em suspends the current thread until the ownership is obtained. \end{DoxyCompactList}\item
\hyperlink{classhryky_1_1exclusion_1_1_recursive_mutex_ad2ca9247d6d3865a04cb792c5e98bf58}{Recursive\-Mutex} ()
\begin{DoxyCompactList}\small\item\em default constructor. \end{DoxyCompactList}\item
void \hyperlink{classhryky_1_1exclusion_1_1_recursive_mutex_aee17540d5f888dee1594f27b074b4078}{unlock} ()
\begin{DoxyCompactList}\small\item\em releases the ownership. \end{DoxyCompactList}\end{DoxyCompactItemize}

\subsection{Detailed Description}
exclusion object \-: mutex which can be called recursively.

\subsection{Constructor \& Destructor Documentation}
\hypertarget{classhryky_1_1exclusion_1_1_recursive_mutex_ad2ca9247d6d3865a04cb792c5e98bf58}{\index{hryky\-::exclusion\-::\-Recursive\-Mutex@{hryky\-::exclusion\-::\-Recursive\-Mutex}!Recursive\-Mutex@{Recursive\-Mutex}}
\index{Recursive\-Mutex@{Recursive\-Mutex}!hryky::exclusion::RecursiveMutex@{hryky\-::exclusion\-::\-Recursive\-Mutex}}
\subsubsection[{Recursive\-Mutex}]{\setlength{\rightskip}{0pt plus 5cm}{\bf hryky\-::exclusion\-::\-Recursive\-Mutex\-::\-Recursive\-Mutex} (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily  \mbox{[}explicit\mbox{]}}}}\label{classhryky_1_1exclusion_1_1_recursive_mutex_ad2ca9247d6d3865a04cb792c5e98bf58}

default constructor.

constructor.

\subsection{Member Function Documentation}
\hypertarget{classhryky_1_1exclusion_1_1_recursive_mutex_aee17540d5f888dee1594f27b074b4078}{\index{hryky\-::exclusion\-::\-Recursive\-Mutex@{hryky\-::exclusion\-::\-Recursive\-Mutex}!unlock@{unlock}}
\index{unlock@{unlock}!hryky::exclusion::RecursiveMutex@{hryky\-::exclusion\-::\-Recursive\-Mutex}}
\subsubsection[{unlock}]{\setlength{\rightskip}{0pt plus 5cm}void {\bf hryky\-::exclusion\-::\-Recursive\-Mutex\-::unlock} (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}}\label{classhryky_1_1exclusion_1_1_recursive_mutex_aee17540d5f888dee1594f27b074b4078}

releases the ownership.

release the ownership.

The documentation for this class was generated from the following files\-:\begin{DoxyCompactItemize}
\item
\hyperlink{exclusion__recursive__mutex_8h}{exclusion\-\_\-recursive\-\_\-mutex.\-h}\item
\hyperlink{exclusion__recursive__mutex_8cpp}{exclusion\-\_\-recursive\-\_\-mutex.\-cpp}\end{DoxyCompactItemize}


text:
package ch.qos.logback.classic.spi;

/**
 * This class provides information about the runtime platform.
 *
 * @author Ceki Gulcu
 * */
public class PlatformInfo {

  private static final int UNINITIALIZED = -1;

  private static int hasJMXObjectName = UNINITIALIZED;

  public static boolean hasJMXObjectName() {
    if (hasJMXObjectName == UNINITIALIZED) {
      try {
        Class.forName("javax.management.ObjectName");
        hasJMXObjectName = 1;
      } catch (Throwable e) {
        hasJMXObjectName = 0;
      }
    }
    return (hasJMXObjectName == 1);
  }
}


text:
namespace content {

// MediaSessionDelegate is an interface abstracting audio focus handling for the
// MediaSession class.
class MediaSessionDelegate {
 public:
  // Factory method returning an implementation of MediaSessionDelegate.
  static std::unique_ptr<MediaSessionDelegate> Create(
      MediaSession* media_session);

  virtual bool RequestAudioFocus(MediaSession::Type type) = 0;
  virtual void AbandonAudioFocus() = 0;
};

}  // namespace content

#endif // CONTENT_BROWSER_MEDIA_SESSION_MEDIA_SESSION_DELEGATE_H_


text:
set :application, 't4c'
set :repo_url, 'git@github.com:sigmike/code4gamecredits.git'

# ask :branch, proc { `git rev-parse --abbrev-ref HEAD`.chomp }

set :deploy_to, "/home/apps/p4c"
set :scm, :git

set :rvm_type, :user
set :rvm_ruby_version, '2.0.0-p247'
set :rvm_custom_path, '~/.rvm'

set :format, :pretty
# set :log_level, :debug
# set :pty, true

set :linked_files, %w{config/database.yml config/config.yml}
set :linked_dirs, %w{log tmp}

# set :default_env, { path: "/opt/ruby/bin:$PATH" }
set :keep_releases, 5

namespace :deploy do

  desc 'Restart application'
  task :restart do
    on roles(:app), in: :sequence, wait: 5 do
      execute :touch, release_path.join('tmp/restart.txt')
    end
  end

  after :restart, :clear_cache do
    on roles(:web), in: :groups, limit: 3, wait: 10 do
      # Here we can do anything such as:
      # within release_path do
      #   execute :rake, 'cache:clear'
      # end
    end
  end

  after :finishing, 'deploy:cleanup'

end


text:
package com.amazonaws.services.appsync.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.appsync.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * Resolver JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ResolverJsonUnmarshaller implements Unmarshaller<Resolver, JsonUnmarshallerContext> {

    public Resolver unmarshall(JsonUnmarshallerContext context) throws Exception {
        Resolver resolver = new Resolver();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("typeName", targetDepth)) {
                    context.nextToken();
                    resolver.setTypeName(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("fieldName", targetDepth)) {
                    context.nextToken();
                    resolver.setFieldName(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("dataSourceName", targetDepth)) {
                    context.nextToken();
                    resolver.setDataSourceName(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("resolverArn", targetDepth)) {
                    context.nextToken();
                    resolver.setResolverArn(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("requestMappingTemplate", targetDepth)) {
                    context.nextToken();
                    resolver.setRequestMappingTemplate(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("responseMappingTemplate", targetDepth)) {
                    context.nextToken();
                    resolver.setResponseMappingTemplate(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("kind", targetDepth)) {
                    context.nextToken();
                    resolver.setKind(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("pipelineConfig", targetDepth)) {
                    context.nextToken();
                    resolver.setPipelineConfig(PipelineConfigJsonUnmarshaller.getInstance().unmarshall(context));
                }
                if (context.testExpression("syncConfig", targetDepth)) {
                    context.nextToken();
                    resolver.setSyncConfig(SyncConfigJsonUnmarshaller.getInstance().unmarshall(context));
                }
                if (context.testExpression("cachingConfig", targetDepth)) {
                    context.nextToken();
                    resolver.setCachingConfig(CachingConfigJsonUnmarshaller.getInstance().unmarshall(context));
                }
                if (context.testExpression("maxBatchSize", targetDepth)) {
                    context.nextToken();
                    resolver.setMaxBatchSize(context.getUnmarshaller(Integer.class).unmarshall(context));
                }
                if (context.testExpression("runtime", targetDepth)) {
                    context.nextToken();
                    resolver.setRuntime(AppSyncRuntimeJsonUnmarshaller.getInstance().unmarshall(context));
                }
                if (context.testExpression("code", targetDepth)) {
                    context.nextToken();
                    resolver.setCode(context.getUnmarshaller(String.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return resolver;
    }

    private static ResolverJsonUnmarshaller instance;

    public static ResolverJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new ResolverJsonUnmarshaller();
        return instance;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<reportDownloadError></reportDownloadError>


text:
require "spec_helper"

RSpec.describe Suspenders::Production::SingleRedirect, type: :generator do
  describe "invoke" do
    it "adds Rack::CanonicalHost to the production middleware" do
      with_fake_app do
        invoke! Suspenders::Production::SingleRedirect

        middleware_canonical_host =
          "config.middleware.use Rack::CanonicalHost, " \
          'ENV.fetch("APPLICATION_HOST")'

        expect("config/environments/production.rb")
          .to match_contents(/#{Regexp.escape(middleware_canonical_host)}/)
      end
    end
  end

  describe "revoke" do
    it "removes Rack::CanonicalHost from the production middleware" do
      with_fake_app do
        invoke_then_revoke! Suspenders::Production::SingleRedirect

        middleware_canonical_host =
          "config.middleware.use Rack::CanonicalHost, " \
          'ENV.fetch("APPLICATION_HOST")'

        expect("config/environments/production.rb")
          .not_to match_contents(/#{Regexp.escape(middleware_canonical_host)}/)
      end
    end
  end
end


text:
Suppose you have a three node replica set. Node 1 is the primary. Node 2 is a secondary, Node 3 is a secondary running with a delay of two hours. All writes to the database are issued with w=majority and j=1 (by which we mean that the getLastError call has those values set).

A write operation (could be insert or update) is initiated from your application using the Node.js driver at time=0. At time=5 seconds, the primary, Node 1, goes down for an hour and node 2 is elected primary. Note that your write operation has not yet returned at the time of the failure. Note also that although you have not received a response from the write, it has been processed and written by Node 1 before the failure. Node 3, since it has a slave delay option set, is lagging.

Will there be a rollback of data on Node 1 when Node 1 comes back up? Choose the best answer.

* Yes, always
* No, never
* Maybe, it depends on whether Node 3 has processed the write
* Maybe, it depends on whether Node 2 has processed the write

### Answer

````
Maybe, it depends on whether Node 2 has processed the write
````


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    android:id="@+id/content_view"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.screens.MainActivity">

</FrameLayout>


text:
package com.game_machine.entity_system.generated;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.List;

import com.dyuproject.protostuff.ByteString;
import com.dyuproject.protostuff.GraphIOUtil;
import com.dyuproject.protostuff.Input;
import com.dyuproject.protostuff.Message;
import com.dyuproject.protostuff.Output;

import java.io.ByteArrayOutputStream;
import com.dyuproject.protostuff.JsonIOUtil;
import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtobufIOUtil;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.runtime.RuntimeSchema;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.game_machine.entity_system.generated.Entity;

import com.dyuproject.protostuff.Pipe;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.UninitializedMessageException;

public final class ObjectdbPut  implements Externalizable, Message<ObjectdbPut>, Schema<ObjectdbPut>
{

    public static Schema<ObjectdbPut> getSchema()
    {
        return DEFAULT_INSTANCE;
    }

    public static ObjectdbPut getDefaultInstance()
    {
        return DEFAULT_INSTANCE;
    }

    static final ObjectdbPut DEFAULT_INSTANCE = new ObjectdbPut();

    public Entity entity;

    public ObjectdbPut()
    {

    }

	public Entity getEntity() {
		return entity;
	}

	public ObjectdbPut setEntity(Entity entity) {
		this.entity = entity;
		return this;
	}

	public Boolean hasEntity()  {
        return entity == null ? false : true;
    }

    // java serialization

    public void readExternal(ObjectInput in) throws IOException
    {
        GraphIOUtil.mergeDelimitedFrom(in, this, this);
    }

    public void writeExternal(ObjectOutput out) throws IOException
    {
        GraphIOUtil.writeDelimitedTo(out, this, this);
    }

    // message method

    public Schema<ObjectdbPut> cachedSchema()
    {
        return DEFAULT_INSTANCE;
    }

    // schema methods

    public ObjectdbPut newMessage()
    {
        return new ObjectdbPut();
    }

    public Class<ObjectdbPut> typeClass()
    {
        return ObjectdbPut.class;
    }

    public String messageName()
    {
        return ObjectdbPut.class.getSimpleName();
    }

    public String messageFullName()
    {
        return ObjectdbPut.class.getName();
    }

    public boolean isInitialized(ObjectdbPut message)
    {
        return true;
    }

    public void mergeFrom(Input input, ObjectdbPut message) throws IOException
    {
        for(int number = input.readFieldNumber(this);; number = input.readFieldNumber(this))
        {
            switch(number)
            {
                case 0:
                    return;

            	case 1:

                	message.entity = input.mergeObject(message.entity, Entity.getSchema());
                    break;

                default:
                    input.handleUnknownField(number, this);
            }
        }
    }

    public void writeTo(Output output, ObjectdbPut message) throws IOException
    {

    	if(message.entity == null)
            throw new UninitializedMessageException(message);

    	if(message.entity != null)
    		output.writeObject(1, message.entity, Entity.getSchema(), false);

    }

    public String getFieldName(int number)
    {
        switch(number)
        {

        	case 1: return "entity";

            default: return null;
        }
    }

    public int getFieldNumber(String name)
    {
        final Integer number = __fieldMap.get(name);
        return number == null ? 0 : number.intValue();
    }

    private static final java.util.HashMap<String,Integer> __fieldMap = new java.util.HashMap<String,Integer>();
    static
    {

    	__fieldMap.put("entity", 1);

    }

   public static List<String> getFields() {
	ArrayList<String> fieldNames = new ArrayList<String>();
	String fieldName = null;
	Integer i = 1;

    while(true) {
		fieldName = ObjectdbPut.getSchema().getFieldName(i);
		if (fieldName == null) {
			break;
		}
		fieldNames.add(fieldName);
		i++;
	}
	return fieldNames;
}

public static ObjectdbPut parseFrom(byte[] bytes) {
	ObjectdbPut message = new ObjectdbPut();
	ProtobufIOUtil.mergeFrom(bytes, message, RuntimeSchema.getSchema(ObjectdbPut.class));
	return message;
}

public ObjectdbPut clone() {
	byte[] bytes = this.toByteArray();
	ObjectdbPut objectdbPut = ObjectdbPut.parseFrom(bytes);
	return objectdbPut;
}

public byte[] toByteArray() {
	return toProtobuf();
	//return toJson();
}

public byte[] toJson() {
	boolean numeric = false;
	ByteArrayOutputStream out = new ByteArrayOutputStream();
	try {
		JsonIOUtil.writeTo(out, this, ObjectdbPut.getSchema(), numeric);
	} catch (IOException e) {
		e.printStackTrace();
		throw new RuntimeException("Json encoding failed");
	}
	return out.toByteArray();
}

public byte[] toProtobuf() {
	LinkedBuffer buffer = LinkedBuffer.allocate(8024);
	byte[] bytes = null;

	try {
		bytes = ProtobufIOUtil.toByteArray(this, RuntimeSchema.getSchema(ObjectdbPut.class), buffer);
		buffer.clear();
	} catch (Exception e) {
		e.printStackTrace();
		throw new RuntimeException("Protobuf encoding failed");
	}
	return bytes;
}

}


text:
package	org.apache.derby.impl.sql.compile;

import org.apache.derby.iapi.services.context.ContextManager;

import org.apache.derby.iapi.services.loader.GeneratedMethod;

import org.apache.derby.iapi.services.compiler.JavaFactory;
import org.apache.derby.iapi.services.compiler.MethodBuilder;

import org.apache.derby.iapi.reference.SQLState;
import org.apache.derby.iapi.error.StandardException;

import org.apache.derby.iapi.sql.compile.C_NodeTypes;

import org.apache.derby.iapi.sql.conn.Authorizer;

import org.apache.derby.iapi.sql.conn.LanguageConnectionContext;
import org.apache.derby.iapi.sql.compile.Visitable;
import org.apache.derby.iapi.sql.compile.Visitor;
import org.apache.derby.iapi.sql.compile.CompilerContext;

import org.apache.derby.iapi.reference.ClassName;

import org.apache.derby.iapi.sql.dictionary.ConglomerateDescriptor;
import org.apache.derby.iapi.sql.dictionary.ConstraintDescriptor;
import org.apache.derby.iapi.sql.dictionary.DataDictionary;
import org.apache.derby.iapi.sql.dictionary.TableDescriptor;
import org.apache.derby.iapi.sql.dictionary.IndexLister;
import org.apache.derby.iapi.sql.dictionary.IndexRowGenerator;
import org.apache.derby.iapi.types.TypeId;

import org.apache.derby.iapi.sql.ResultSet;
import org.apache.derby.iapi.sql.Activation;
import org.apache.derby.iapi.sql.StatementType;

import org.apache.derby.iapi.sql.execute.ConstantAction;

import org.apache.derby.iapi.store.access.StaticCompiledOpenConglomInfo;
import org.apache.derby.iapi.store.access.TransactionController;
import org.apache.derby.iapi.types.RowLocation;

import org.apache.derby.impl.sql.compile.ActivationClassBuilder;
import org.apache.derby.iapi.services.compiler.MethodBuilder;

import org.apache.derby.iapi.services.sanity.SanityManager;

import org.apache.derby.vti.DeferModification;

import org.apache.derby.iapi.services.classfile.VMOpcode;
import org.apache.derby.iapi.util.StringUtil;

import org.apache.derby.catalog.UUID;

import org.apache.derby.impl.sql.execute.FKInfo;

import java.util.Properties;

import org.apache.derby.iapi.services.io.FormatableBitSet;
import org.apache.derby.iapi.util.ReuseFactory;

/**
 * An InsertNode is the top node in a query tree for an
 * insert statement.
 *

 * After parsing, the node contains
 *   targetTableName: the target table for the insert
 *   collist: a list of column names, if specified
 *   queryexpr: the expression being inserted, either
 *				a values clause or a select form; both
 *			    of these are represented via the SelectNode,
 *				potentially with a TableOperatorNode such as
 *				UnionNode above it.
 *

 * After binding, the node has had the target table's
 * descriptor located and inserted, and the queryexpr
 * and collist have been massaged so that they are identical
 * to the table layout.  This involves adding any default
 * values for missing columns, and reordering the columns
 * to match the table's ordering of them.
 *

 * After optimizing, ...
 */
public final class InsertNode extends DMLModStatementNode
{
	public		ResultColumnList	targetColumnList;
	public 		boolean				deferred;
	public		ValueNode			checkConstraints;
	public		Properties			targetProperties;
	public		FKInfo				fkInfo;
	protected	boolean				bulkInsert;
	private 	boolean				bulkInsertReplace;

	protected   RowLocation[] 		autoincRowLocation;
	/**
	 * Initializer for an InsertNode.
	 *
	 * @param targetName	The name of the table/VTI to insert into
	 * @param insertColumns	A ResultColumnList with the names of the
	 *			columns to insert into.  May be null if the
	 *			user did not specify the columns - in this
	 *			case, the binding phase will have to figure
	 *			it out.
	 * @param queryExpression	The query expression that will generate
	 *				the rows to insert into the given table
	 * @param targetProperties	The properties specified on the target table
	 */

	public void init(
			Object targetName,
			Object insertColumns,
			Object queryExpression,
			Object targetProperties)
	{
		/* statementType gets set in super() before we've validated
		 * any properties, so we've kludged the code to get the
		 * right statementType for a bulk insert replace.
		 */
		super.init(
				queryExpression,
				ReuseFactory.getInteger(getStatementType(
												(Properties) targetProperties))
				);
		setTarget((QueryTreeNode) targetName);
		targetColumnList = (ResultColumnList) insertColumns;
		this.targetProperties = (Properties) targetProperties;

		/* Remember that the query expression is the source to an INSERT */
		getResultSetNode().setInsertSource();
	}

	/**
	 * Convert this object to a String.  See comments in QueryTreeNode.java
	 * for how this should be done for tree printing.
	 *
	 * @return	This object as a String
	 */

	public String toString()
	{
		if (SanityManager.DEBUG)
		{
            try {
                return ( (targetTableName!=null) ? targetTableName : targetVTI.getTableName() ).toString() + "\n"
                    + targetProperties + "\n"
                    + super.toString();
            } catch (org.apache.derby.iapi.error.StandardException e) {
                return "tableName: <not_known>\n"
                    + targetProperties + "\n"
                    + super.toString();
            }
		}
		else
		{
			return "";
		}
	}

	public String statementToString()
	{
		return "INSERT";
	}

	/**
	 * Prints the sub-nodes of this object.  See QueryTreeNode.java for
	 * how tree printing is supposed to work.
	 *
	 * @param depth		The depth of this node in the tree
	 */

	public void printSubNodes(int depth)
	{
		if (SanityManager.DEBUG)
		{
			super.printSubNodes(depth);

			if (targetTableName != null)
			{
				printLabel(depth, "targetTableName: ");
				targetTableName.treePrint(depth + 1);
			}

			if (targetColumnList != null)
			{
				printLabel(depth, "targetColumnList: ");
				targetColumnList.treePrint(depth + 1);
			}

			/* RESOLVE - need to print out targetTableDescriptor */
		}
	}

	/**
	 * Bind this InsertNode.  This means looking up tables and columns and
	 * getting their types, and figuring out the result types of all
	 * expressions, as well as doing view resolution, permissions checking,
	 * etc.
	 *

	 * Binding an insert will also massage the tree so that
	 * the collist and select column order/number are the
	 * same as the layout of the table in the store.
	 *
	 *
	 * @exception StandardException		Thrown on error
	 */

	public void bindStatement() throws StandardException
	{
		// We just need select privilege on the expressions
		getCompilerContext().pushCurrentPrivType( Authorizer.SELECT_PRIV);

		FromList	fromList = (FromList) getNodeFactory().getNode(
									C_NodeTypes.FROM_LIST,
									getNodeFactory().doJoinOrderOptimization(),
									getContextManager());

		/* If any underlying ResultSetNode is a SelectNode, then we
		 * need to do a full bind(), including the expressions
		 * (since the fromList may include a FromSubquery).
		 */
        DataDictionary dataDictionary = getDataDictionary();
		super.bindResultSetsWithTables(dataDictionary);

		/*
		** Get the TableDescriptor for the table we are inserting into
		*/
		verifyTargetTable();

		// Check the validity of the targetProperties, if they exist
		if (targetProperties != null)
		{
			verifyTargetProperties(dataDictionary);
		}

		/*
		** Get the resultColumnList representing the columns in the base
		** table or VTI.
		*/
		getResultColumnList();

		/* If we have a target column list, then it must have the same # of
		 * entries as the result set's RCL.
		 */
		if (targetColumnList != null)
		{
			/*
			 * Normalize synonym qualifers for column references.
			 */
			if (synonymTableName != null)
			{
				normalizeSynonymColumns ( targetColumnList, targetTableName );
			}

			/* Bind the target column list */
			getCompilerContext().pushCurrentPrivType( getPrivType());
			if (targetTableDescriptor != null)
			{
				targetColumnList.bindResultColumnsByName(targetTableDescriptor,
														(DMLStatementNode) this);
			}
			else
			{
				targetColumnList.bindResultColumnsByName(targetVTI.getResultColumns(), targetVTI,
														this);
			}
			getCompilerContext().popCurrentPrivType();
		}

		/* Verify that all underlying ResultSets reclaimed their FromList */
		if (SanityManager.DEBUG)
		{
			SanityManager.ASSERT(fromList.size() == 0,
				"fromList.size() is expected to be 0, not " +
				fromList.size() +
				" on return from RS.bindExpressions()");
		}

		/* Replace any DEFAULTs with the associated tree */
		resultSet.replaceDefaults(targetTableDescriptor, targetColumnList);

		/* Bind the expressions now that the result columns are bound
		 * NOTE: This will be the 2nd time for those underlying ResultSets
		 * that have tables (no harm done), but it is necessary for those
		 * that do not have tables.  It's too hard/not work the effort to
		 * avoid the redundancy.
		 */
		super.bindExpressions();

		/*
		** If the result set is a union, it could be a table constructor.
		** Bind any nulls in the result columns of the table constructor
		** to the types of the table being inserted into.
		**
		** The types of ? parameters in row constructors and table constructors
		** in an INSERT statement come from the result columns.
		**
		** If there is a target column list, use that instead of the result
		** columns for the whole table, since the columns in the result set
		** correspond to the target column list.
		*/
		if (targetColumnList != null)
		{
			if (resultSet.getResultColumns().visibleSize() > targetColumnList.size())
				throw StandardException.newException(SQLState.LANG_DB2_INVALID_COLS_SPECIFIED);
			resultSet.bindUntypedNullsToResultColumns(targetColumnList);
			resultSet.setTableConstructorTypes(targetColumnList);
		}
		else
		{
			if (resultSet.getResultColumns().visibleSize() > resultColumnList.size())
				throw StandardException.newException(SQLState.LANG_DB2_INVALID_COLS_SPECIFIED);
			resultSet.bindUntypedNullsToResultColumns(resultColumnList);
			resultSet.setTableConstructorTypes(resultColumnList);
		}

		/* Bind the columns of the result set to their expressions */
		resultSet.bindResultColumns(fromList);

		int resCols = resultSet.getResultColumns().visibleSize();
		DataDictionary dd = getDataDictionary();
		if (targetColumnList != null)
		{
			if (targetColumnList.size() != resCols)
				throw StandardException.newException(SQLState.LANG_DB2_INVALID_COLS_SPECIFIED);
		}
		else
		{
			if (targetTableDescriptor != null &&
						targetTableDescriptor.getNumberOfColumns() != resCols)
				throw StandardException.newException(SQLState.LANG_DB2_INVALID_COLS_SPECIFIED);
		}

		/* See if the ResultSet's RCL needs to be ordered to match the target
		 * list, or "enhanced" to accommodate defaults.  It can only need to
		 * be ordered if there is a target column list.  It needs to be
		 * enhanced if there are fewer source columns than there are columns
		 * in the table.
		 */
		boolean inOrder = true;
		int numTableColumns = resultColumnList.size();

		/* colMap[] will be the size of the target list, which could be larger
		 * than the current size of the source list.  In that case, the source
		 * list will be "enhanced" to include defaults.
		 */
		int[] colMap = new int[numTableColumns];

		// set the fields to an unused value
		for (int i = 0; i < colMap.length; i++)
		{
			colMap[i] = -1;
		}

		/* Create the source/target list mapping */
		if (targetColumnList != null)
		{
			/*
			** There is a target column list, so the result columns might
			** need to be ordered.  Step through the target column list
			** and remember the position in the target table of each column.
			** Remember if any of the columns are out of order.
			*/
			int targetSize = targetColumnList.size();
			for (int index = 0; index < targetSize; index++)
			{
				int position =
					((ResultColumn) (targetColumnList.elementAt(index))).
												columnDescriptor.getPosition();

				if (index != position-1)
				{
					inOrder = false;
				}

				// position is 1-base; colMap indexes and entries are 0-based.
				colMap[position-1] = index;
			}
		}
		else
		{
			/*
			** There is no target column list, so the result columns in the
			** source are presumed to be in the same order as the target
			** table.
			*/
			for (int position = 0;
				position < resultSet.getResultColumns().visibleSize();
				position++)
			{
				colMap[position] = position;
			}
		}

		enhanceAndCheckForAutoincrement(resultSet, inOrder,
				numTableColumns, colMap, dataDictionary,
				targetTableDescriptor, targetVTI);

		resultColumnList.checkStorableExpressions(resultSet.getResultColumns());
		/* Insert a NormalizeResultSetNode above the source if the source
		 * and target column types and lengths do not match.
 		 */
		if (! resultColumnList.columnTypesAndLengthsMatch(
												resultSet.getResultColumns()))
		{
			resultSet = resultSet.genNormalizeResultSetNode(false);
			resultColumnList.copyTypesAndLengthsToSource(resultSet.getResultColumns());
		}

		if (targetTableDescriptor != null)
		{
			/* Get and bind all constraints on the table */
			ResultColumnList sourceRCL = resultSet.getResultColumns();
			sourceRCL.copyResultColumnNames(resultColumnList);
			checkConstraints = bindConstraints(dataDictionary,
												getNodeFactory(),
												targetTableDescriptor,
												null,
												sourceRCL,
												(int[]) null,
												(FormatableBitSet) null,
												false,
											    true);  /* we always include
														 * triggers in core language */

			/* Do we need to do a deferred mode insert */
			/*
		 	** Deferred if:
			**	If the target table is also a source table
			**	Self-referencing foreign key constraint
			**	trigger
			*/
			if (resultSet.referencesTarget(
									targetTableDescriptor.getName(), true) ||
				 requiresDeferredProcessing())
			{
				deferred = true;

				/* Disallow bulk insert replace when target table
				 * is also a source table.
				 */
				if (bulkInsertReplace &&
					resultSet.referencesTarget(
									targetTableDescriptor.getName(), true))
				{
					throw StandardException.newException(SQLState.LANG_INVALID_BULK_INSERT_REPLACE,
									targetTableDescriptor.getQualifiedName());
				}
			}

			/* Get the list of indexes on the table being inserted into */
			getAffectedIndexes(targetTableDescriptor);
			TransactionController tc =
				getLanguageConnectionContext().getTransactionCompile();

			autoincRowLocation =
				dd.computeAutoincRowLocations(tc, targetTableDescriptor);

			if (isPrivilegeCollectionRequired())
			{
				getCompilerContext().pushCurrentPrivType(getPrivType());
				getCompilerContext().addRequiredTablePriv(targetTableDescriptor);
				getCompilerContext().popCurrentPrivType();
			}

		}
		else
		{
            deferred = VTIDeferModPolicy.deferIt( DeferModification.INSERT_STATEMENT,
                                                  targetVTI,
                                                  null,
                                                  resultSet);
		}

		getCompilerContext().popCurrentPrivType();
	}

	/**
	 * Process ResultSet column lists for projection and autoincrement.
	 *
	 * This method recursively descends the result set node tree. When
	 * it finds a simple result set, it processes any autoincrement
	 * columns in that rs by calling checkAutoIncrement. When it finds
	 * a compound result set, like a Union or a PRN, it recursively
	 * descends to the child(ren) nodes. Union nodes can arise due to
	 * multi-rows in VALUES clause), PRN nodes can arise when the set
	 * of columns being inserted is a subset of the set of columns in
	 * the table.
	 *
	 * In addition to checking for autoincrement columns in the result set,
	 * we may need to enhance and re-order the column list to match the
	 * column list of the table we are inserting into. This work is handled
	 * by ResultsetNode.enhanceRCLForInsert.
	 *
	 * Note that, at the leaf level, we need to enhance the RCL first, then
	 * check for autoincrement columns. At the non-leaf levels, we have
	 * to enhance the RCL, but we don't have to check for autoincrement
	 * columns, since they only occur at the leaf level.
	 *
	 * This way, all ColumnDescriptor of all rows will be set properly.
	 *
	 * @param resultSet			current node in the result set tree
	 * @param inOrder			FALSE if the column list needs reordering
	 * @param numTableColumns   # of columns in target RCL
	 * @param colMap            correspondence between RCLs
	 * @param dataDictionary    DataDictionary to use
	 * @param targetTableDescriptor    Table Descriptor for target
	 * @param targetVTI         Target description if it is a VTI
	 *
	 * @exception StandardException Thrown on error
	 */
	private void enhanceAndCheckForAutoincrement(ResultSetNode resultSet,
			boolean inOrder, int numTableColumns, int []colMap,
			DataDictionary dataDictionary,
			TableDescriptor targetTableDescriptor,
			FromVTI targetVTI)
		throws StandardException
	{
		/*
		 * Some implementation notes:
		 *
		 * colmap[x] == y means that column x in the target table
		 * maps to column y in the source result set.
		 * colmap[x] == -1 means that column x in the target table
		 * maps to its default value.
		 * both colmap indexes and values are 0-based.
		 *
		 * if the list is in order and complete, we don't have to change
		 * the tree. If it is not, then we call RSN.enhanceRCLForInsert()
		 * which will reorder ("enhance") the source RCL within the same RSN)
		 *
		 * one thing we do know is that all of the resultsets underneath
		 * us have their resultColumn names filled in with the names of
		 * the target table columns.  That makes generating the mapping
		 * "easier" -- we simply generate the names of the target table columns
		 * that are included.  For the missing columns, we generate default
		 * value expressions.
		 */

		if (resultSet instanceof SingleChildResultSetNode)
		{
			enhanceAndCheckForAutoincrement(
				((SingleChildResultSetNode)resultSet).getChildResult(),
				inOrder, numTableColumns, colMap, dataDictionary,
				targetTableDescriptor, targetVTI);
			if (! inOrder || resultSet.resultColumns.size() < numTableColumns)
				resultSet.enhanceRCLForInsert(
						numTableColumns, colMap, dataDictionary,
						targetTableDescriptor, targetVTI);
		}
		else if (resultSet instanceof UnionNode)
		{
			enhanceAndCheckForAutoincrement(
				((TableOperatorNode)resultSet).getLeftResultSet(),
				inOrder, numTableColumns, colMap, dataDictionary,
				targetTableDescriptor, targetVTI);
			enhanceAndCheckForAutoincrement(
				((TableOperatorNode)resultSet).getRightResultSet(),
				inOrder, numTableColumns, colMap, dataDictionary,
				targetTableDescriptor, targetVTI);
			if (! inOrder || resultSet.resultColumns.size() < numTableColumns)
				resultSet.enhanceRCLForInsert(
						numTableColumns, colMap, dataDictionary,
						targetTableDescriptor, targetVTI);
		}
		else
		{
			if (! inOrder || resultSet.resultColumns.size() < numTableColumns)
				resultSet.enhanceRCLForInsert(
						numTableColumns, colMap, dataDictionary,
						targetTableDescriptor, targetVTI);
			resultColumnList.checkAutoincrement(resultSet.getResultColumns());
		}
	}

	int getPrivType()
	{
		return Authorizer.INSERT_PRIV;
	}

	/**
	 * Return true if the node references SESSION schema tables (temporary or permanent)
	 *
	 * @return	true if references SESSION schema tables, else false
	 *
	 * @exception StandardException		Thrown on error
	 */
	public boolean referencesSessionSchema()
		throws StandardException
	{
		boolean returnValue = false;

		//If this node references a SESSION schema table, then return true.
		if (targetTableDescriptor != null)
			returnValue = isSessionSchema(targetTableDescriptor.getSchemaDescriptor());

		if (returnValue == false)
			returnValue = resultSet.referencesSessionSchema();

		return returnValue;
	}

	/**
	 * Verify that the target properties that we are interested in
	 * all hold valid values.
	 * NOTE: Any target property which is valid but cannot be supported
	 * due to a target database, etc. will be turned off quietly.
	 *
	 * @param dd	The DataDictionary
	 *
	 * @exception StandardException		Thrown on error
	 */
	private void verifyTargetProperties(DataDictionary dd)
		throws StandardException
	{
		// The only property that we're currently interested in is insertMode
		String insertMode = targetProperties.getProperty("insertMode");
		if (insertMode != null)
		{
			String upperValue = StringUtil.SQLToUpperCase(insertMode);
			if (! upperValue.equals("BULKINSERT") &&
				! upperValue.equals("REPLACE"))
			{
				throw StandardException.newException(SQLState.LANG_INVALID_INSERT_MODE,
								insertMode,
								targetTableName);
			}
			else
			{
				/* Turn off bulkInsert if it is on and we can't support it. */
				if (! verifyBulkInsert(dd, upperValue))
				{
					targetProperties.remove("insertMode");
				}
				else
				{
					/* Now we know we're doing bulk insert */
					bulkInsert = true;

					if (upperValue.equals("REPLACE"))
					{
						bulkInsertReplace = true;
					}

					// Validate the bulkFetch property if specified
					String bulkFetchStr = targetProperties.getProperty("bulkFetch");
					if (bulkFetchStr != null)
					{
						int bulkFetch = getIntProperty(bulkFetchStr, "bulkFetch");

						// verify that the specified value is valid
						if (bulkFetch <= 0)
						{
							throw StandardException.newException(SQLState.LANG_INVALID_BULK_FETCH_VALUE,
									String.valueOf(bulkFetch));
						}
					}
				}
			}
		}
	}

	/**
	 * Do the bind time checks to see if bulkInsert is allowed on
	 * this table.  bulkInsert is disallowed at bind time for:
	 *		o  target databases
	 *		o  (tables with triggers?)
	 * (It is disallowed at execution time if the table has at
	 * least 1 row in it or if it is a deferred mode insert.)
	 *
	 * @param dd	The DataDictionary
	 * @param mode	The insert mode
	 *
	 * @return Whether or not bulkInsert is allowed.
	 *
	 * @exception StandardException		Thrown on error
	 */
	private boolean verifyBulkInsert(DataDictionary dd, String mode)
		throws StandardException
	{
		return true;
	}

	/**
	 * Compile constants that Execution will use
	 *
	 * @exception StandardException		Thrown on failure
	 */
	public ConstantAction	makeConstantAction() throws StandardException
	{

		/* Different constant actions for base tables and updatable VTIs */
		if (targetTableDescriptor != null)
		{
			// Base table

			long heapConglomId = targetTableDescriptor.getHeapConglomerateId();
			TransactionController tc =
				getLanguageConnectionContext().getTransactionCompile();
			int numIndexes = (targetTableDescriptor != null) ?
								indexConglomerateNumbers.length : 0;
			StaticCompiledOpenConglomInfo[] indexSCOCIs =
				new StaticCompiledOpenConglomInfo[numIndexes];

			for (int index = 0; index < numIndexes; index++)
			{
				indexSCOCIs[index] = tc.getStaticCompiledConglomInfo(indexConglomerateNumbers[index]);
			}

			/*
			** If we're doing bulk insert, do table locking regardless of
			** what the optimizer decided.  This is because bulk insert is
			** generally done with a large number of rows into an empty table.
			** We also do table locking if the table's lock granularity is
			** set to table.
			*/
			if (bulkInsert ||
				targetTableDescriptor.getLockGranularity() == TableDescriptor.TABLE_LOCK_GRANULARITY)
			{
				lockMode = TransactionController.MODE_TABLE;
			}

			return	getGenericConstantActionFactory().getInsertConstantAction
				( targetTableDescriptor,
				  heapConglomId,
				  tc.getStaticCompiledConglomInfo(heapConglomId),
				  indicesToMaintain,
				  indexConglomerateNumbers,
				  indexSCOCIs,
				  indexNames,
				  deferred,
				  false,
				  targetTableDescriptor.getUUID(),
				  lockMode,
				  null, null,
				  targetProperties,
				  getFKInfo(),
				  getTriggerInfo(),
				  resultColumnList.getStreamStorableColIds(targetTableDescriptor.getNumberOfColumns()),
				  getIndexedCols(),
				  (UUID) null,
				  null,
				  null,
				  resultSet.isOneRowResultSet(),
				  autoincRowLocation
				  );
		}
		else
		{
			/* Return constant action for VTI
			 * NOTE: ConstantAction responsible for preserving instantiated
			 * VTIs for in-memory queries and for only preserving VTIs
			 * that implement Serializable for SPSs.
			 */
			return	getGenericConstantActionFactory().getUpdatableVTIConstantAction( DeferModification.INSERT_STATEMENT,
						deferred);
		}
	}

	/**
	 * Create a boolean[] to track the (0-based) columns which are indexed.
	 *
	 * @return A boolean[] to track the (0-based) columns which are indexed.
	 *
	 * @exception StandardException		Thrown on failure
	 */
	public boolean[] getIndexedCols() throws StandardException
	{
		/* Create a boolean[] to track the (0-based) columns which are indexed */
		boolean[] indexedCols = new boolean[targetTableDescriptor.getNumberOfColumns()];
		for (int index = 0; index < indicesToMaintain.length; index++)
		{
			int[] colIds = indicesToMaintain[index].getIndexDescriptor().baseColumnPositions();

			for (int index2 = 0; index2 < colIds.length; index2++)
			{
				indexedCols[colIds[index2] - 1] = true;
			}
		}

		return indexedCols;
	}

	/**
	 * Code generation for insert
	 * creates an expression for:
	 *   ResultSetFactory.getInsertResultSet(resultSet.generate(ps), this )
	 *
	 * @param acb	The ActivationClassBuilder for the class being built
	 * @param mb the method  for the execute() method to be built
	 *
	 * @exception StandardException		Thrown on error
	 */
	public void generate(ActivationClassBuilder acb,
								MethodBuilder mb)
							throws StandardException
	{
		// If the DML is on the temporary table, generate the code to
		// mark temporary table as modified in the current UOW. After
		// DERBY-827 this must be done in execute() since
		// fillResultSet() will only be called once.
		generateCodeForTemporaryTable(acb, acb.getExecuteMethod());

		/* generate the parameters */
		generateParameterValueSet(acb);
		// Base table
		if (targetTableDescriptor != null)
		{
			/*
			** Generate the insert result set, giving it either the original
			** source or the normalize result set, the constant action,
			** and "this".
			*/

			acb.pushGetResultSetFactoryExpression(mb);

			// arg 1
			resultSet.generate(acb, mb);

			// arg 2 generate code to evaluate CHECK CONSTRAINTS
			generateCheckConstraints( checkConstraints, acb, mb );

			mb.callMethod(VMOpcode.INVOKEINTERFACE, (String) null, "getInsertResultSet", ClassName.ResultSet, 2);
		}
		else
		{
			/* Generate code for the VTI
			 * NOTE: we need to create a dummy cost estimate for the
			 * targetVTI since we never optimized it.
			 * RESOLVEVTI - we will have to optimize it in order to
			 * push predicates into the VTI.
			 */
			targetVTI.assignCostEstimate(resultSet.getNewCostEstimate());

			/*
			** Generate the insert VTI result set, giving it either the original
			** source or the normalize result set, the constant action,
			*/
			acb.pushGetResultSetFactoryExpression(mb);

			// arg 1
			resultSet.generate(acb, mb);

			// arg 2
			targetVTI.generate(acb, mb);

			mb.callMethod(VMOpcode.INVOKEINTERFACE, (String) null, "getInsertVTIResultSet", ClassName.ResultSet, 2);
		}
	}

	/**
	 * Return the type of statement, something from
	 * StatementType.
	 *
	 * @return the type of statement
	 */
	protected final int getStatementType()
	{
		return StatementType.INSERT;
	}

	/**
	 * Return the statement type, where it is dependent on
	 * the targetProperties.  (insertMode = replace causes
	 * statement type to be BULK_INSERT_REPLACE.
	 *
	 * @return the type of statement
	 */
	static final int getStatementType(Properties targetProperties)
	{
		int retval = StatementType.INSERT;

		// The only property that we're currently interested in is insertMode
		String insertMode = (targetProperties == null) ? null : targetProperties.getProperty("insertMode");
		if (insertMode != null)
		{
			String upperValue = StringUtil.SQLToUpperCase(insertMode);
			if (upperValue.equals("REPLACE"))
			{
				retval = StatementType.BULK_INSERT_REPLACE;
			}
		}
		return retval;
	}

	/**
	 * Get the list of indexes on the table being inserted into.  This
	 * is used by INSERT.  This is an optimized version of what
	 * UPDATE and DELETE use.
	 *
	 * @param td	TableDescriptor for the table being inserted into
	 *				or deleted from
	 *
	 * @exception StandardException		Thrown on error
	 */
	private void getAffectedIndexes
	(
		TableDescriptor 	td
	)
					throws StandardException
	{
		IndexLister	indexLister = td.getIndexLister( );

		indicesToMaintain = indexLister.getDistinctIndexRowGenerators();
		indexConglomerateNumbers = indexLister.getDistinctIndexConglomerateNumbers();
		indexNames = indexLister.getDistinctIndexNames();

		/* Add dependencies on all indexes in the list */
		ConglomerateDescriptor[]	cds = td.getConglomerateDescriptors();
		CompilerContext cc = getCompilerContext();

 		for (int index = 0; index < cds.length; index++)
		{
			cc.createDependency(cds[index]);
		}
	}

} // end of class InsertNode


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<meta http-Equiv="Cache-Control" Content="no-cache">
	<meta http-Equiv="Pragma" Content="no-cache">
	<meta http-Equiv="Expires" Content="0">
	<title>Brunel Output</title>

	<link rel="stylesheet" type="text/css" href="https://brunelvis.org/js/brunel.2.6.css" charset="utf-8"/>

0073    data('raw:A,B;a,b;a,c;a,d;b,c;a,e;e,f;g,h;m,n;n,o') edge style('symbol:curved') key(A, B) + data('ra...

Pass: Note curved edges with no arrowheads

<svg id="visualization" width="480" height="330"></svg>


text:
'use strict';

/**
 * Module dependencies.
 */

import * as _ from 'lodash';
import ErrorsController from '../errors.server.controller';
var errorHandler = ErrorsController.getInstance();
import {default as User} from '../../models/user.server.model';
import Config from '../../../config/config';
var config = Config.getInstance();
import * as nodemailer from 'nodemailer';
import * as async from 'async';
import * as crypto from 'crypto';
import DbConfig from '../../../config/db';
var r = DbConfig.getInstance().getThinky().r;

export default class UsersPasswordController {
    /**
     * Forgot for reset password (forgot POST)
     */
    forgot(req, res, next) {
        async.waterfall([
            // Generate random token
            function(done) {
                crypto.randomBytes(20, function(err, buffer) {
                    var token = buffer.toString('hex');
                    done(err, token);
                });
            },
            // Lookup user by username
            function(token, done) {
                if (req.body.username) {
                    User.getByUsername(req.body.username)
                        .without(['salt', 'password'])
                        .run()
                        .then(function(user) {
                        if (user.provider !== 'local') {
                            return res.status(400).send({
                                message: 'It seems like you signed up using your ' + user.provider + ' account'
                            });
                        } else {
                            user.resetPasswordToken = token;
                            user.resetPasswordExpires = Date.now() + 3600000; // 1 hour

                            user.save(function(err) {
                                done(err, token, user);
                            });
                        }
                    })
                        .then(null, function(err) {
                        return res.status(400).send({
                            message: 'No account with that username has been found'
                        });
                    });
                } else {
                    return res.status(400).send({
                        message: 'Username field must not be blank'
                    });
                }
            },
            function(token, user, done) {
                res.render('templates/reset-password-email', {
                    name: user.displayName,
                    appName: config.app.title,
                    url: 'http://' + req.headers.host + '/auth/reset/' + token
                }, function(err, emailHTML) {
                        done(err, emailHTML, user);
                    });
            },
            // If valid email, send reset email using service
            function(emailHTML, user, done) {
                var smtpTransport = nodemailer.createTransport(config.mailer.options);
                var mailOptions = {
                    to: user.email,
                    from: config.mailer.from,
                    subject: 'Password Reset',
                    html: emailHTML
                };
                smtpTransport.sendMail(mailOptions, function(err) {
                    if (!err) {
                        res.send({
                            message: 'An email has been sent to ' + user.email + ' with further instructions.'
                        });
                    }

                    done(err);
                });
            }
        ], function(err) {
                if (err) return next(err);
            });
    }

    /**
     * Reset password GET from email token
     */
    validateResetToken(req, res) {
        User.filter(
            r.row('resetPasswordToken')
                .eq(req.param.token)
                .and(r.row('resetPasswordExpires').gt(Date.now()))
            )
            .limit(1)
            .run()
            .then(function(user) {
            if (!user) {
                return res.redirect('/#!/password/reset/invalid');
            }
            res.redirect('/#!/password/reset/' + req.params.token);
        })
            .then(null, function(err) {
            return res.redirect('/#!/password/reset/invalid');
        });
    }

    /**
     * Reset password POST from email token
     */
    reset(req, res, next) {
        // Init Variables
        var passwordDetails = req.body;

        async.waterfall([

            function(done) {
                User.filter(
                    r.row('resetPasswordToken')
                        .eq(req.param.token)
                        .and(r.row('resetPasswordExpires').gt(Date.now()))
                    )
                    .limit(1)
                    .nth(0)
                    .run()
                    .then(function(user) {
                    if (user) {
                        if (passwordDetails.newPassword === passwordDetails.verifyPassword) {
                            user.password = passwordDetails.newPassword;
                            user.resetPasswordToken = undefined;
                            user.resetPasswordExpires = undefined;

                            user.save(function(err) {
                                if (err) {
                                    return res.status(400).send({
                                        message: errorHandler.getErrorMessage(err)
                                    });
                                } else {
                                    req.login(user, function(err) {
                                        if (err) {
                                            res.status(400).send(err);
                                        } else {
                                            // Return authenticated user
                                            res.json(user);

                                            done(err, user);
                                        }
                                    });
                                }
                            });
                        } else {
                            return res.status(400).send({
                                message: 'Passwords do not match'
                            });
                        }
                    } else {
                        return res.status(400).send({
                            message: 'Password reset token is invalid or has expired.'
                        });
                    }
                })
                    .then(null, function(err) {
                    return res.status(400).send({
                        message: 'Password reset token is invalid or has expired.'
                    });
                });
            },
            function(user, done) {
                res.render('templates/reset-password-confirm-email', {
                    name: user.displayName,
                    appName: config.app.title
                }, function(err, emailHTML) {
                        done(err, emailHTML, user);
                    });
            },
            // If valid email, send reset email using service
            function(emailHTML, user, done) {
                var smtpTransport = nodemailer.createTransport(config.mailer.options);
                var mailOptions = {
                    to: user.email,
                    from: config.mailer.from,
                    subject: 'Your password has been changed',
                    html: emailHTML
                };

                smtpTransport.sendMail(mailOptions, function(err) {
                    done(err, 'done');
                });
            }
        ], function(err) {
                if (err) return next(err);
            });
    }

    /**
     * Change Password
     */
    changePassword(req, res) {
        // Init Variables
        var passwordDetails = req.body;

        if (req.user) {
            if (passwordDetails.newPassword) {
                User.get(req.user.id)
                    .run()
                    .then(function(user) {
                    if (user) {
                        if (user.authenticate(passwordDetails.currentPassword)) {
                            if (passwordDetails.newPassword === passwordDetails.verifyPassword) {
                                user.password = passwordDetails.newPassword;

                                user.save(function(err) {
                                    if (err) {
                                        return res.status(400).send({
                                            message: errorHandler.getErrorMessage(err)
                                        });
                                    } else {
                                        req.login(user, function(err) {
                                            if (err) {
                                                res.status(400).send(err);
                                            } else {
                                                res.send({
                                                    message: 'Password changed successfully'
                                                });
                                            }
                                        });
                                    }
                                });
                            } else {
                                res.status(400).send({
                                    message: 'Passwords do not match'
                                });
                            }
                        } else {
                            res.status(400).send({
                                message: 'Current password is incorrect'
                            });
                        }
                    } else {
                        res.status(400).send({
                            message: 'User is not found'
                        });
                    }
                })
                    .then(null, function(err) {
                    res.status(400).send({
                        message: 'User is not found'
                    });
                });
            } else {
                res.status(400).send({
                    message: 'Please provide a new password'
                });
            }
        } else {
            res.status(400).send({
                message: 'User is not signed in'
            });
        }
    }
}


text:
var through = require('through');

module.exports = filterStream;

function filterStream(coll) {
    return through(function(data) {
        coll.push(data);
    });
}


text:
package com.adeptj.modules.data.jpa;

import com.adeptj.modules.data.jpa.criteria.ConstructorCriteria;
import com.adeptj.modules.data.jpa.criteria.DeleteCriteria;
import com.adeptj.modules.data.jpa.criteria.ReadCriteria;
import com.adeptj.modules.data.jpa.criteria.TupleCriteria;
import com.adeptj.modules.data.jpa.criteria.UpdateCriteria;
import com.adeptj.modules.data.jpa.dto.CrudDTO;
import com.adeptj.modules.data.jpa.dto.ResultSetMappingDTO;
import com.adeptj.modules.data.jpa.query.InParam;
import com.adeptj.modules.data.jpa.query.OutParam;
import com.adeptj.modules.data.jpa.query.QueryParam;
import com.adeptj.modules.data.jpa.query.QueryType;
import org.osgi.annotation.versioning.ConsumerType;

import javax.persistence.EntityManager;
import javax.persistence.Tuple;
import java.io.Serializable;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * JPA 2.2 Repository for CRUD operations to be performed by the application on underlying DB.
 * All the operations defined in the contract throw JpaException which is a wrapped exception
 * of the actual exception thrown by the PersistenceProvider.
 *

 *
 * @param <T>  The {@link BaseEntity} subclass type which this repository is dealing with.
 * @param <ID> The primary key of the JPA entity.
 * @author Rakesh.Kumar, AdeptJ
 */
@ConsumerType
public interface JpaRepository<T extends BaseEntity, ID extends Serializable> {

    /**
     * Inserts the given JPA entity in DB.
     *
     * @param entity the JPA entity instance
     * @return the entity instance having id assigned begin DB
     */
    T insert(T entity);

    /**
     * Inserts the given JPA entities in DB.
     *
     * @param entities  the JPA entity instances
     * @param batchSize the interval with which there is a commit to database
     */
    void batchInsert(List<T> entities, int batchSize);

    /**
     * Updates the given JPA entity in DB.
     *
     * @param entity the JPA entity instance
     * @return Updated JPA entity instance
     */
    T update(T entity);

    /**
     * Updates the given JPA entity using the criteria attributes and setting the update attributes.
     *
     * @param criteria Object composed of the JPA entity class.
     *                 The mapping of entity attributes on which criteria has to be applied using AND operator.
     *                 And the mapping of entity attributes which are to be updated.
     * @return returns how many rows were affected by the update query
     */
    int updateByCriteria(UpdateCriteria<T> criteria);

    /**
     * Deletes the given JPA entity begin DB.
     *
     * @param entity     the JPA entity instance
     * @param primaryKey the primary key of the JPA entity
     */
    void delete(Class<T> entity, ID primaryKey);

    /**
     * Deletes the given JPA entity using the CrudDTO attributes.
     *
     * @param crudDTO DTO holding the JPA entity class object, name of the declared named query
     *                and parameters to set for ?index in the query a.k.a positional parameters
     * @return returns how many rows were deleted
     */
    int deleteByJpaNamedQuery(CrudDTO<T> crudDTO);

    /**
     * Deletes the given JPA entity using Criteria API.
     *
     * @param criteria Object composed of the JPA entity class.
     *                 The mapping of entity attributes on which criteria has to be applied using AND operator.
     * @return returns how many rows were deleted
     */
    int deleteByCriteria(DeleteCriteria<T> criteria);

    /**
     * Deletes all the rows of given JPA entity in DB.
     *

     * Note: This will delete all the rows in DB, you better know what are you doing.
     *
     * @param entity the JPA entity class object
     * @return returns how many rows were deleted
     */
    int deleteAll(Class<T> entity);

    /**
     * Finds the given JPA entity using the primary key.
     *
     * @param entity     the JPA entity class object
     * @param primaryKey the primary key of the JPA entity
     * @return The JPA entity
     */
    T findById(Class<T> entity, ID primaryKey);

    /**
     * Finds the given JPA entity using Criteria API.
     *
     * @param criteria Object composed of the JPA entity class.
     *                 The mapping of entity attributes on which criteria has to be applied using AND operator.
     * @return returns no. of rows found
     */
    List<T> findByCriteria(ReadCriteria<T> criteria);

    /**
     * Finds the given JPA entity using Criteria TupleQuery.
     *
     * @param criteria Object composed of the JPA entity class.
     *                 The mapping of entity attributes on which criteria has to be applied using AND operator.
     *                 List of parameters to bind to query parameters (named or positional)
     * @return returns no. of rows found
     */
    List<Tuple> findByTupleCriteria(TupleCriteria<T> criteria);

    /**
     * Finds the given JPA entity using the named JPA query.
     *
     * @param resultClass the type of the query result.
     * @param name        The name of a query defined in metadata.
     * @param params      And list of parameters to bind to query parameters (named or positional)
     * @return List of entity found by named query execution
     */
    <E> List<E> findByNamedQuery(Class<E> resultClass, String name, QueryParam... params);

    /**
     * Finds all entities of given type.
     *

     * Note: Should never be called for large number of rows as you don't want millions of row in memory.
     *
     * @param entity the JPA entity class object
     * @return All of the rows(Entity instances)
     */
    List<T> findAll(Class<T> entity);

    /**
     * Finds all entities of given type. Helpful wherever pagination is required.
     *

     * Note: Should never be called for large number of rows.
     *

     * First the no. of records can be checked using {@link JpaRepository#countByCriteria(Class)} method
     * and then the pagination query can be fired.
     *
     * @param entity    the JPA entity class object
     * @param startPos  position of the first result
     * @param maxResult maximum number of results to retrieve
     * @return All of the rows(Entity instances)
     */
    List<T> findWithPagination(Class<T> entity, int startPos, int maxResult);

    /**
     * Finds the entity instances of given type using query specified in JPQL format.
     *
     * @param crudDTO DTO holding the JPA entity class object.
     *                The query in JPQL format
     *                The list of parameters to bind to query parameters (named or positional)
     * @return List of entity found by JPA query(JPQL format) execution
     */
    List<T> findByJpaQuery(CrudDTO<T> crudDTO);

    /**
     * Find the given entity using SQL IN operator
     *
     * @param entity        the JPA entity class object
     * @param attributeName entity attribute against which IN has to be applied
     * @param values        values on which IN has to be applied
     * @return List of entity found by criteria
     */
    List<T> findByINOperator(Class<T> entity, String attributeName, List<Object> values);

    /**
     * Finds the entity using given native query and project in the given result class.
     *

     * Note: Use only if the names and the types of the query result match to the entity properties.
     *
     * @param resultClass the type of the query result, basically an entity class.
     * @param nativeQuery the native query string
     * @param params      List of parameters to bind to query parameters (named or positional)
     * @return List of entity found by query execution
     */
    List<T> findByNativeQuery(Class<T> resultClass, String nativeQuery, QueryParam... params);

    /**
     * Finds the entity using given named native query and project in the given result class.
     *
     * @param resultClass the type of the query result, basically an entity class.
     * @param mappingDTO  DTO containing the native query, resultSetMapping and
     *                    List of parameters to bind to query parameters (named or positional)
     * @return List of entity found by query execution
     */
    List<T> findByNativeQuery(Class<T> resultClass, ResultSetMappingDTO mappingDTO);

    /**
     * First find the entity using the given Jpa query and then Map the result to the constructor
     * of type specified as resultClass.
     *
     * @param resultClass the type of the Constructor being mapped
     * @param jpaQuery    query in JPQL format (JPA SELECT NEW syntax)
     * @param params      List of parameters to bind to query parameters (named or positional)
     * @param <E>         Type of returned instance
     * @return List of instances of type as resultClass
     */
    <E> List<E> findByJpaQueryWithDTOProjection(Class<E> resultClass, String jpaQuery, QueryParam... params);

    /**
     * First find the entity using the Jpa criteria and then Map the result to the constructor
     * of type specified by type parameter C.
     *
     * @param criteria Object holding the JPA entity class object.
     *                 Constructor class object.
     *                 Selection of attributes, same as number of parameters of Constructor.
     *                 The mapping of entity attributes on which criteria has to be applied using AND operator.
     * @param <C>      Constructor type
     * @return List of instances of type specified by type parameter C
     */
    <C> List<C> findByCriteriaWithDTOProjection(ConstructorCriteria<T, C> criteria);

    /**
     * Gets the single result against the JPA query.
     *
     * @param <E>         as the type of returned instance
     * @param resultClass the type of the query result
     * @param jpaQuery    the query string
     * @param params      List of parameters to bind to query parameters (named or positional)
     * @return a singular result begin query execution
     */
    <E> E findSingleResultByJpaQuery(Class<E> resultClass, String jpaQuery, QueryParam... params);

    /**
     * Gets the single result against the named query.
     *
     * @param resultClass the type of the query result
     * @param name        the name of a query defined in metadata
     * @param params      List of parameters to bind to query parameters (named or positional)
     * @param <E>         Type of returned instance
     * @return singular result begin query execution
     */
    <E> E findSingleResultByNamedQuery(Class<E> resultClass, String name, QueryParam... params);

    /**
     * Count the no. of rows of given JPA entity.
     *
     * @param entity the JPA entity class object
     * @return count of no. of rows of given JPA entity
     */
    Long countByCriteria(Class<T> entity);

    /**
     * Count the no. of rows of given JPA entity.
     *
     * @param query the query string
     * @param type  type of the JPA or native query
     * @return count of no. of rows of given JPA entity
     */
    Long countByQuery(String query, QueryType type);

    /**
     * Count the no. of rows of given JPA entity.
     *
     * @param name the name of a query defined in metadata.
     * @return count of no. of rows of given JPA entity
     */
    Long countByNamedQuery(String name);

    /**
     * Execute the {@link JpaCallback} action specified by the given action object within an EntityManager without a transaction.
     *
     * @param action callback object that specifies the JPA action
     * @param <E>    the result type
     * @return a result object returned by the action, or null
     */
    <E> E executeCallback(JpaCallback<E> action);

    /**
     * Execute the {@link JpaCallback} action specified by the given action object within an EntityManager in a transaction.
     *
     * @param action callback object that specifies the JPA action
     * @param <E>    the result type
     * @return a result object returned by the action, or null
     */
    <E> E executeCallbackInTransaction(JpaCallback<E> action);

    /**
     * Use the {@link Function} for any specific operation on {@link EntityManager}.
     *
     * @param function    the function which takes {@link EntityManager} as argument.
     * @param requiresTxn whether an entity transaction is needed
     * @param <E>         the result type
     * @return a result object returned by the action, or null
     */
    <E> E doWithEntityManager(Function<EntityManager, E> function, boolean requiresTxn);

    /**
     * Use the {@link Consumer} for any specific operation on {@link EntityManager}.
     *
     * @param consumer    the consumer which takes {@link EntityManager} as argument.
     * @param requiresTxn whether an entity transaction is needed
     */
    void doWithEntityManager(Consumer<EntityManager> consumer, boolean requiresTxn);

    // <<------------------------ StoredProcedure Support ------------------------>>

    /**
     * Execute a named stored procedure defined in metadata or as an annotation on an entity.
     *
     * @param name         the name of the stored procedure defined in metadata or as an annotation on an entity
     * @param params       the IN parameters
     * @param outParamName the OUT parameter name
     * @return result of the stored procedure execution.
     */
    Object executeNamedStoredProcedure(String name, List<InParam> params, String outParamName);

    /**
     * Directly execute a stored procedure from DB.
     *
     * @param procedureName the name of the stored procedure in DB
     * @param params        the IN parameters
     * @param outParam      the {@link OutParam} object containing name and type info
     * @return result of the stored procedure execution.
     */
    Object executeStoredProcedure(String procedureName, List<InParam> params, OutParam outParam);

    /**
     * Find all the records of the type (resultClasses) declared in metadata or annotation on an entity
     *
     * @param name   the name of the stored procedure defined in metadata or as an annotation on an entity
     * @param params the IN parameters
     * @param <E>    the result type
     * @return List of instances of type (resultClasses) declared in metadata or annotation on an entity
     */
    <E> List<E> findByNamedStoredProcedure(String name, InParam... params);

    /**
     * Find all the records of the type specified by type parameter E
     *
     * @param resultClass   the type of result the procedure call returns.
     * @param procedureName the name of the stored procedure in DB
     * @param params        the IN parameters
     * @param <E>           the result type
     * @return List of instances of type resultClass
     */
    <E> List<E> findByStoredProcedure(Class<E> resultClass, String procedureName, InParam... params);
}


text:
FROM mhart/alpine-node:5

WORKDIR /app

ADD package.json /app/package.json

RUN \
  apk update && \
  apk add git python make g++ && \
  npm config set progress false && \
  npm install -d && \
  apk del git python make g++ && \
  rm -rf /var/cache/apk/*

VOLUME /app

ENV PORT 3000
EXPOSE 3000 35729

CMD ["npm", "run", "dev"]


text:
Changelog
=========

0.10dev
-------
* Colored logs
* Improved testing coverage
* Neural network code was simplified considerably
* Added features to Neural networks objects
* Added neural networks to documentation
* Option to create all tensorflow sessions with a specific configuration
* Shortcut in command line to limit GPU memory in all tensorflow sessions (through gpu_options.per_process_gpu_memory_fraction)
* Refactored test suite
* Integrats new triage network (using Keras)

0.9 (2018-05-24)
-----------------
* Added parallelization to batch processor
* Preprocess step now runs in parallel
* Filtering and standarization running in one step to avoid I/O overhead

0.8 (2018-04-19)
-----------------

* It is now possible to save results for every step to resume execution, see `save_results` option
* Fixed a bug that caused excessive logging when logger level was set to DEBUG
* General improvements to the sorting algorithm
* Fixes a bug that was causing and import error in the mfm module (thanks @neil-gallagher for reporting this issue)

0.7 (2018-04-06)
-----------------

* New CLI tool for training neural networks `yass train`
* New CLI tool for exporting results to phy `yass export`
* Separated logic in five steps: preprocess, detect, cluster templates and deconvolute
* Improved Neural Network detector speed
* Improved package organization
* Updated examples
* Added integration tests
* Increased testing coverage
* Some examples include links to Jupyter notebooks
* Errors in documentation building are now tested in Travis
* Improved batch processor
* Simplified configuration file
* Preprocessing speedups

0.6 (2018-02-05)
-----------------
* New stability metric
* New batch module
* Rewritten preprocessor
* A lot of functions were rewritten and documented
* More partial results are saved to improve debugging
* Removed a lot of legacy code
* Removed batching logic from old functions, they are now using the `batch` module
* Rewritten CLI interface `yass` command is now `yass sort`

0.5 (2018-01-31)
-----------------
* Improved logging
* Last release with old codebase

0.4 (2018-01-19)
-----------------
* Fixes bug in preprocessing (#38)
* Increased template size
* Updates deconvolution method

0.3 (2017-11-15)
-----------------
* Adds new neural network module

0.2 (2017-11-14)
-----------------
* Config module refactoring, configuration files are now much simpler
* Fixed bug that was causing spike times to be off due to the buffer
* Various bug fixes
* Updates to input/output structure
* Adds new module for augmented spikes
* Function names changes in score module
* Simplified parameters for score module functions

0.1.1 (2017-11-01)
-------------------
* Minor changes to setup.py for uploading to pypi

0.1 (2017-11-01)
-----------------
* First release


text:
<?php

defined('BASEPATH') or exit('No direct script access allowed');

class Stripe_ideal extends CRM_Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function response($id, $hash)
    {
        $this->load->model('invoices_model');
        check_invoice_restrictions($id, $hash);

        $invoice = $this->invoices_model->get($id);
        load_client_language($invoice->clientid);

        try {
            $source = $this->stripe_ideal_gateway->get_source($this->input->get('source'));

            if ($source->status == 'chargeable') {
                try {
                    $charge = $this->stripe_ideal_gateway->charge($source->id, $source->amount, $source->metadata->invoice_id);

                    if ($charge->status == 'succeeded') {
                        $charge->invoice_id = $source->metadata->invoice_id;
                        $success            = $this->stripe_ideal_gateway->finish_payment($charge);

                        set_alert('success', $success ? _l('online_payment_recorded_success') : _l('online_payment_recorded_success_fail_database'));
                    } elseif ($charge->status == 'pending') {
                        set_alert('success', _l('payment_received_awaiting_confirmation'));
                    } else {
                        $errMsg = _l('invoice_payment_record_failed');
                        if ($charge->failure_message) {
                            $errMsg .= ' - ' . $charge->failure_message;
                        }
                        set_alert('warning', $errMsg);
                    }
                } catch (Exception $e) {
                    set_alert('warning', $e->getMessage());
                }
            } else {
                set_alert('warning', _l('invoice_payment_record_failed'));
            }
        } catch (Exception $e) {
            set_alert('warning', $e->getMessage());
        }

        redirect(site_url('invoice/' . $id . '/' . $hash));
    }

    public function webhook($key)
    {
        $saved_key = $this->stripe_ideal_gateway->getSetting('webhook_key');

        if ($saved_key == $key) {
            $input = json_decode(file_get_contents('php://input'), true);
            $data  = $input['data']['object'];

            $pcrm_gateway = isset($data['metadata']['pcrm-stripe-ideal']) ? $data['metadata']['pcrm-stripe-ideal'] : false;

            if ($pcrm_gateway == true && $data['type'] == 'ideal') {
                if ($data['status'] == 'chargeable') {
                    $invoice_id = intval($data['metadata']['invoice_id']);
                    $charge     = $this->stripe_ideal_gateway->charge($data['id'], $data['amount'], $invoice_id);
                    if ($charge->status == 'succeeded') {
                        $this->stripe_ideal_gateway->finish_payment($charge);
                    }
                }
            }
        } else {
            header('HTTP/1.0 403 Not Authorized');
            echo 'Webhook key is not matching';
        }
    }
}


text:
//
//  LiuXSegmentView.m
//  LiuXSegment
//
//  Created by liuxin on 16/3/18.
//  Copyright © 2016年 liuxin. All rights reserved.
//

#define MAX_TitleNumInWindow 5

#import "LiuXSegmentView.h"

@interface LiuXSegmentView()

@property (nonatomic,strong) NSMutableArray *btns;
@property (nonatomic,strong) NSArray *titles;
@property (nonatomic,strong) UIButton *titleBtn;
@property (nonatomic,strong) UIScrollView *bgScrollView;
@property (nonatomic,strong) UIView *selectLine;
@property (nonatomic,assign) CGFloat btn_w;
@end

@implementation LiuXSegmentView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

-(instancetype)initWithFrame:(CGRect)frame titles:(NSArray *)titleArray clickBlick:(btnClickBlock)block{
    self = [super initWithFrame:frame];
    if (self) {

        self.layer.shadowColor=[UIColor blackColor].CGColor;
        self.layer.shadowOffset=CGSizeMake(2, 2);
        self.layer.shadowRadius=2;
        self.layer.shadowOpacity=.2;

        _btn_w=0.0;
        if (titleArray.count<MAX_TitleNumInWindow+1) {
            _btn_w=MAIN_SCREEN_WIDTH/titleArray.count;
        }else{
            _btn_w=MAIN_SCREEN_WIDTH/MAX_TitleNumInWindow;
        }
        _titles=titleArray;
        _defaultIndex=1;
        _titleFont=[UIFont systemFontOfSize:15];
        _btns=[[NSMutableArray alloc] initWithCapacity:0];
        _titleNomalColor=[UIColor blackColor];
        _titleSelectColor=RGB(242, 179, 32);
        _bgScrollView=[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, MAIN_SCREEN_WIDTH, self.frame.size.height)];
        _bgScrollView.backgroundColor=[UIColor whiteColor];
        _bgScrollView.showsHorizontalScrollIndicator=NO;
        _bgScrollView.contentSize=CGSizeMake(_btn_w*titleArray.count, self.frame.size.height);
        [self addSubview:_bgScrollView];

        _selectLine=[[UIView alloc] initWithFrame:CGRectMake(0, self.frame.size.height-2, _btn_w, 2)];
        _selectLine.backgroundColor=_titleSelectColor;
        [_bgScrollView addSubview:_selectLine];

        for (int i=0; i<titleArray.count; i++) {
            UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame=CGRectMake(_btn_w*i, 0, _btn_w, self.frame.size.height-2);
            btn.tag=i+1;
            [btn setTitle:titleArray[i] forState:UIControlStateNormal];
            [btn setTitleColor:_titleNomalColor forState:UIControlStateNormal];
            [btn setTitleColor:_titleSelectColor forState:UIControlStateSelected];
            [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchDown];
            [btn setBackgroundColor:[UIColor whiteColor]];
            btn.titleLabel.font=_titleFont;
            [_bgScrollView addSubview:btn];
            [_btns addObject:btn];
            if (i==0) {
                _titleBtn=btn;
                btn.selected=YES;
            }
            self.block=block;

        }
    }

    return self;
}

-(void)btnClick:(UIButton *)btn{

    if (self.block) {
        self.block(btn.tag);
    }

    if (btn.tag==_defaultIndex) {
        return;
    }else{
        _titleBtn.selected=!_titleBtn.selected;
        _titleBtn=btn;
        _titleBtn.selected=YES;
        _defaultIndex=btn.tag;
    }

    //计算偏移量
    CGFloat offsetX=btn.frame.origin.x - 2*_btn_w;
    if (offsetX<0) {
        offsetX=0;
    }
    CGFloat maxOffsetX= _bgScrollView.contentSize.width-MAIN_SCREEN_WIDTH;
    if (offsetX>maxOffsetX) {
        offsetX=maxOffsetX;
    }

    [UIView animateWithDuration:.2 animations:^{

        [_bgScrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
        _selectLine.frame=CGRectMake(btn.frame.origin.x, self.frame.size.height-2, btn.frame.size.width, 2);

    } completion:^(BOOL finished) {

    }];

}

-(void)setTitleNomalColor:(UIColor *)titleNomalColor{
    _titleNomalColor=titleNomalColor;
    [self updateView];
}

-(void)setTitleSelectColor:(UIColor *)titleSelectColor{
    _titleSelectColor=titleSelectColor;
    [self updateView];
}

-(void)setTitleFont:(UIFont *)titleFont{
    _titleFont=titleFont;
    [self updateView];
}

-(void)setDefaultIndex:(NSInteger)defaultIndex{
    _defaultIndex=defaultIndex;
    [self updateView];
}

-(void)updateView{
    for (UIButton *btn in _btns) {
        [btn setTitleColor:_titleNomalColor forState:UIControlStateNormal];
        [btn setTitleColor:_titleSelectColor forState:UIControlStateSelected];
        btn.titleLabel.font=_titleFont;
        _selectLine.backgroundColor=_titleSelectColor;

        if (btn.tag-1==_defaultIndex-1) {
            _titleBtn=btn;
            btn.selected=YES;
            _selectLine.frame=CGRectMake(btn.frame.origin.x, self.frame.size.height-2, btn.frame.size.width, 2);
        }else{
            btn.selected=NO;
        }
    }
}

@end