text:
package com.fasterxml.jackson.databind.jsontype.ext;

import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;

import com.fasterxml.jackson.databind.BaseMapTest;
import com.fasterxml.jackson.databind.ObjectMapper;

// Tests for External type id, one that exists at same level as typed Object,
// that is, property is not within typed object but a member of its parent.
public class ExternalTypeId96Test extends BaseMapTest
{
    // for [databind#96]
    static class ExternalBeanWithDefault
    {
        @JsonTypeInfo(use=Id.CLASS, include=As.EXTERNAL_PROPERTY, property="extType",
                defaultImpl=ValueBean.class)
        public Object bean;

        public ExternalBeanWithDefault() { }
        public ExternalBeanWithDefault(int v) {
            bean = new ValueBean(v);
        }
    }

    @JsonTypeName("vbean")
    static class ValueBean {
        public int value;

        public ValueBean() { }
        public ValueBean(int v) { value = v; }
    }

    /*
    /**********************************************************
    /* Unit tests, deserialization
    /**********************************************************
     */

    private final ObjectMapper MAPPER = new ObjectMapper();

    // For [databind#96]: should allow use of default impl, if property missing
    /* 18-Jan-2013, tatu: Unfortunately this collides with [databind#118], and I don't
     *   know what the best resolution is. For now at least
     */
    public void testWithDefaultAndMissing() throws Exception
    {
        ExternalBeanWithDefault input = new ExternalBeanWithDefault(13);
        // baseline: include type, verify things work:
        String fullJson = MAPPER.writeValueAsString(input);
        ExternalBeanWithDefault output = MAPPER.readValue(fullJson, ExternalBeanWithDefault.class);
        assertNotNull(output);
        assertNotNull(output.bean);
        // and then try without type info...
        ExternalBeanWithDefault defaulted = MAPPER.readValue("{\"bean\":{\"value\":13}}",
                ExternalBeanWithDefault.class);
        assertNotNull(defaulted);
        assertNotNull(defaulted.bean);
        assertSame(ValueBean.class, defaulted.bean.getClass());
    }
}

redpajama_set_name: RedPajamaGithub


text:
function resizing(graph){

	// some types of the elements need resizing after they are dropped
	graph.on('add', function(cell, collection, opt) {

		if (!opt.stencil) return;
		if(cell.get('type') === 'link') return;

		//Set font-size
		cell.attr('.name-text/font-size', 12);

		var type = cell.get('type');

		var originalSize = cell.get('size');

		if(cell.get('subType') === "Junction"){
			cell.set('size', {
				width: originalSize.width/2,
				height: originalSize.height/2
			});
		}
		else if(cell.get('subType') === "Business Service" || cell.get('subType') === "Application Service" || cell.get('subType') === "Infrastructure Service"  || cell.get('subType') === "Value"){
			cell.set('size', {
				width: originalSize.width * 2,
				height: (originalSize.height * 2)/1.5
			});
		}
		else{
			cell.set('size', {
				width: originalSize.width * 2,
				height: originalSize.height * 2
			});
		}

		// configuration of resizing
//		var sizeMultiplier = {
//				'basic.Generic': 2,
//		}[type];

//		if (sizeMultiplier) {
//			var originalSize = cell.get('size');
//
//			if(cell.get('subType') === "Business Service" || cell.get('subType') === "Application Service" || cell.get('subType') === "Infrastructure Service"  || cell.get('subType') === "Value"){
//				cell.set('size', {
//					width: originalSize.width * 2,
//					height: (originalSize.height * 2)/1.5
//				});
//			}
//			else{
//				cell.set('size', {
//					width: originalSize.width * 2,
//					height: originalSize.height * 2
//				});
//			}
//		}
//
//		sizeMultiplier = 0;
	}, this);

};


text:
package com.groupon.jenkins.dynamic.build.cause;

import com.groupon.jenkins.git.GitBranch;
import java.util.Collections;
import org.kohsuke.github.GHCommit;
import org.kohsuke.stapler.export.Exported;

public class UnknownBuildCause extends BuildCause {

    private final String sha;
    private final GitBranch branch;
    private String parentSha;
    private final CommitInfo commitInfo;

    public UnknownBuildCause(GitBranch branch, GHCommit commit, String parentSha) {
        this.branch = branch;
        this.parentSha = parentSha;
        this.sha = commit.getSHA1();
        this.commitInfo = new CommitInfo(commit,branch);
    }

    @Override
    public String getSha() {
        return sha;
    }

    @Override
    public String getParentSha() {
        return parentSha;
    }

    @Override
    public String getPusher() {
        return "unknown";
    }

    @Override
    public String getPullRequestNumber() {
        return branch.isPullRequest() ? branch.pullRequestNumber() + "" : null;
    }

    @Override
    public CommitInfo getCommitInfo() {
        return commitInfo;
    }

    @Override
    public String getName() {
        return "UNKNOWN";
    }

    @Override
    public GitBranch getBranch() {
        return branch;
    }

    @Override
    public Iterable<GithubLogEntry> getChangeLogEntries() {
        return Collections.emptyList();
    }

    @Override
    @Exported(visibility = 3)
    public String getShortDescription() {
        return "";
    }

}


text:
CSC 435 - Distributed Systems HTTP Server Assignment

# Assignment details:

Task	Complete?
Paul Hester	Yes
--------------- ADMINISTRATION -----------------
Created ZIP file, sent to D2L	Yes
Downloaded your D2L submission to verify not corrupt	Yes
Submitted all files except checklist, concatenated together, to D2L TII link	Yes
All files correctly named, in single directory	Yes
MyWebServer compiles as one file.	Yes
"javac *.java" in one directory compiles all code.	Yes
MyWebServer tested with required FireFox browser	Yes
Written the correct headers for source files?	Yes
--------------- THE PROGRAM -----------------
Implemented basic security by restricting access to directory tree	Yes
MyWebServer serves files from DIRECTORY IN WHICH SERVER IS STARTED	Yes
MyWebServer, with this name, runs at port 2540	Yes
Extensive Comments in Source for MyWebServer.java	Yes
MyListener is fully functional	Yes
Captured http stream from browser with MyListener or other method	Yes
MyTelnet is fully functional	Yes
Captured http stream from some webserver with MyTelnet or other method	Yes
Collected HTTP streams from MyListener and MyTelnet into http-streams.txt	Yes
Return txt files with MIME from MyWebServer	Yes
Return html files with MIME from MyWebServer	Yes
Return HTML directory	Yes
Return HTML directory with hotlinks	Yes
Fully, recursively, navigates directories and files	Yes
Returns form input from fake-cgi	Yes


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace piola\exceptions;

/**
 * Description of RecoverableErrorException
 *
 * @author Pablo
 */
class RecoverableErrorException extends \ErrorException {
    //put your code here
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>org.primaresearch.web.gwt.client.user (PrimaGwt API)</title>
<meta name="date" content="2017-10-03">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

org.primaresearch.web.gwt.client.user

Interfaces

UserManager.LogOnListener

UserService

UserServiceAsync

Classes

UserManager


text:
using NUnit.Framework;
using SharpDiff.FileStructure;

namespace SharpDiff.Tests
{
    [TestFixture]
    public class IndexExtendedHeaderTests : AbstractParserTestFixture
    {
        [Test]
        public void IndexExtendedHeaderIsParsed()
        {
            var result = Parse<IndexHeader>("index c750789..f1c2d64 100644", x => x.IndexHeader);

            Assert.That(result, Is.Not.Null);
            Assert.That(result.Range, Is.Not.Null);
            Assert.That(result.Range.Start, Is.EqualTo("c750789"));
            Assert.That(result.Range.End, Is.EqualTo("f1c2d64"));
            Assert.That(result.Mode, Is.EqualTo(100644));
        }
    }
}


text:
**This will be VERY bold**
*This will be italic*

```
this is some code
on multiple lines
```

[click here!!!!!!](www.google.com)

![Pairs Coding](https://github.com/nataliecodes/phase-0-gps-1/blob/master/natalie-nicola.png)


text:
module Mysql2
  class Client
    attr_reader :query_options, :read_timeout
    @@default_query_options = {
      :as => :hash,                   # the type of object you want each row back as; also supports :array (an array of values)
      :async => false,                # don't wait for a result after sending the query, you'll have to monitor the socket yourself then eventually call Mysql2::Client#async_result
      :cast_booleans => false,        # cast tinyint(1) fields as true/false in ruby
      :symbolize_keys => false,       # return field names as symbols instead of strings
      :database_timezone => :local,   # timezone Mysql2 will assume datetime objects are stored in
      :application_timezone => nil,   # timezone Mysql2 will convert to before handing the object back to the caller
      :cache_rows => true,            # tells Mysql2 to use it's internal row cache for results
      :connect_flags => REMEMBER_OPTIONS | LONG_PASSWORD | LONG_FLAG | TRANSACTIONS | PROTOCOL_41 | SECURE_CONNECTION,
      :cast => true,
      :default_file => nil,
      :default_group => nil
    }

    def initialize(opts = {})
      opts = Mysql2::Util.key_hash_as_symbols( opts )
      @read_timeout = nil
      @query_options = @@default_query_options.dup
      @query_options.merge! opts

      initialize_ext

      # Set default connect_timeout to avoid unlimited retries from signal interruption
      opts[:connect_timeout] = 120 unless opts.key?(:connect_timeout)

      [:reconnect, :connect_timeout, :local_infile, :read_timeout, :write_timeout, :default_file, :default_group, :secure_auth, :init_command].each do |key|
        next unless opts.key?(key)
        case key
        when :reconnect, :local_infile, :secure_auth
          send(:"#{key}=", !!opts[key])
        when :connect_timeout, :read_timeout, :write_timeout
          send(:"#{key}=", opts[key].to_i)
        else
          send(:"#{key}=", opts[key])
        end
      end

      # force the encoding to utf8
      self.charset_name = opts[:encoding] || 'utf8'

      ssl_options = opts.values_at(:sslkey, :sslcert, :sslca, :sslcapath, :sslcipher)
      ssl_set(*ssl_options) if ssl_options.any?

      if [:user,:pass,:hostname,:dbname,:db,:sock].any?{|k| @query_options.has_key?(k) }
        warn "============= WARNING FROM mysql2 ============="
        warn "The options :user, :pass, :hostname, :dbname, :db, and :sock will be deprecated at some point in the future."
        warn "Instead, please use :username, :password, :host, :port, :database, :socket, :flags for the options."
        warn "============= END WARNING FROM mysql2 ========="
      end

      user     = opts[:username] || opts[:user]
      pass     = opts[:password] || opts[:pass]
      host     = opts[:host] || opts[:hostname]
      port     = opts[:port]
      database = opts[:database] || opts[:dbname] || opts[:db]
      socket   = opts[:socket] || opts[:sock]
      flags    = opts[:flags] ? opts[:flags] | @query_options[:connect_flags] : @query_options[:connect_flags]

      # Correct the data types before passing these values down to the C level
      user = user.to_s unless user.nil?
      pass = pass.to_s unless pass.nil?
      host = host.to_s unless host.nil?
      port = port.to_i unless port.nil?
      database = database.to_s unless database.nil?
      socket = socket.to_s unless socket.nil?

      connect user, pass, host, port, database, socket, flags
    end

    def self.default_query_options
      @@default_query_options
    end

    if Thread.respond_to?(:handle_interrupt)
      def query(sql, options = {})
        Thread.handle_interrupt(::Mysql2::Util::TimeoutError => :never) do
          _query(sql, @query_options.merge(options))
        end
      end
    else
      def query(sql, options = {})
        _query(sql, @query_options.merge(options))
      end
    end

    def query_info
      info = query_info_string
      return {} unless info
      info_hash = {}
      info.split.each_slice(2) { |s| info_hash[s[0].downcase.delete(':').to_sym] = s[1].to_i }
      info_hash
    end

    def info
      self.class.info
    end

    private
      def self.local_offset
        ::Time.local(2010).utc_offset.to_r / 86400
      end
  end
end


text:
FBShareDialog
=============

A JavaScript plugin to share stories to Facebook's wall

This is an interface component for websites and Facebook applications which allows your users to make a selection of one of their friend or themself to share stories on the wall. The friend is returned as an array of Facebook ID, the post_id is returned as an object after successful post.

![This is what it looks like.](http://oleksandrvladymyrov.github.io/FBShareDialog/pic/design.png)

## Viewing the example

You can view the example at [page](http://oleksandrvladymyrov.github.io/FBShareDialog/), or you can check out this repository and run it yourself. You'll need to put the files on a web server - Facebook apps won't run off the local file system.

Just edit `example.js` and set your Facebook `appId`.

## Using the plugin

### Include required HTML

- Copy the `div` element with the ID `FBShareDialog` (and all of its children) from `index.html`.
- There is some text in the HTML. This is where you can localise the plugin to the desired language.

### Include required CSS

- Include the `fbsharedialog.css` stylesheet in your document.

### Include required JavaScript

- Include jQuery in your document.
- Include the Facebook [JavaScript SDK](http://developers.facebook.com/docs/reference/javascript/). (Technically, this step is optional. We have provided a `setFriends` function if you have loaded the friends on the serverside and want to avoid the JavaScript SDK.)
- Include [Bootstrap](http://getbootstrap.com/) in your document.
- Include `fbsharedialog.js`.
- Optional: We are using an HTML5 placeholder attribute on the search field. If you want the placeholder to work in older browsers, include a [placeholder polyfill](https://github.com/mathiasbynens/Placeholder-jQuery-Plugin).
- Note: we haven't minified the script for you but you might like to [minify it](http://refresh-sf.com/yui/) and concatenate it into a single file with your other plugins.

### The fun stuff (using the plugin)

1 - Create a Facebook application, as shown below.
![This is what it looks like.](http://oleksandrvladymyrov.github.io/FBShareDialog/pic/facebook_app.png)

1.1 - Make sure your user has authenticated your Facebook app.

2 - Initialise the plugin. Here you can set options like toggling debug messages, your preferred classnames, etc.

	FBShareDialog.init({debug: true});

3 - Create an instance of the plugin. We allow multiple instances per page because sometimes you will need users to select friends for more than one thing. You can pass in options here which will only effect this instance, for example a callback to deal with the friends that are selected.

	selector1 = FBShareDialog.newInstance({
		callbackSubmit: function(selectedFriendIds) {
			console.log("The following friends were selected: " + selectedFriendIds.join(", "));
		}
	});

4 - Display the plugin instance when you need it. The plugin will automatically load the Facebook friends of the logged in user (and they will be cached and reused across all instances on the page).

	$("#btnSelect1").click(function (e) {
		e.preventDefault();
		selector1.showFriendSelector();
	});

5 - According to the dimension(width) of browser's window there are two options of design. We called it desktop and mobile. The desktop design will automatically deployed with width of browser's window >=768px otherwise will be deployed mobile design. The mobile design is oriented to use with touchscreen interface, but can be used on desktop as well.

![This is what it looks like.](http://oleksandrvladymyrov.github.io/FBShareDialog/pic/design.png)

6 - According to design, the library propose different types of the share dialog

![This is what it looks like.](http://oleksandrvladymyrov.github.io/FBShareDialog/pic/dialog.png)

7 - Events

Library exposes a few events for hooking into modal functionality.

     	Event Type	Description

    1	FBShareDialog:share	This event fires immediately when the answer from Facebook received

    2	FBShareDialog:friendSelected	This event is fired when friend selected

    3	FBShareDialog:friendUnselected	This event is fired when friend unselected

     $("#FBShareDialog").on('FBShareDialog:share', function (e, eventInfo){
        // do something…
    });
     $("#FBShareDialog").on('FBShareDialog:friendSelected', function (e, eventInfo){
        // do something…
     });
     $("#FBShareDialog").on('FBShareDialog:friendUnselected', function (e, eventInfo){
        // do something…
    });

8 - CallBacks

   The library provides the opportunity to interact through a callback function

- callbackFriendSelected
- callbackFriendUnselected
- callbackSubmit
- callbackCancel

9 - Using fbredirect.html and fbredirect.php

 They are required(one of them on your choice) to return control to your application after share story to Facebook's wall at desktop design.

10 - Parameters

 You can specify all parameters that support [Feed and Share Dialogs](https://developers.facebook.com/docs/reference/dialogs/feed/).
If you don't specify the 'display' property or set `auto` than in desktop design will be applied `iframe` display type and `touch` in mobile as well. You can also force the `popup` or `page` or `dialog` or `iframe` or `touch` display types, if necessary.

## Thanks

This library was wrote on [These Days Labs Facebook-friend-selector](https://github.com/thesedays/Facebook-friend-selector) base.


text:
// Copyright (c) 2013-2015 Rapptz and contributors

// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#ifndef SOL_DEFAULT_CONSTRUCTOR_HPP
#define SOL_DEFAULT_CONSTRUCTOR_HPP

#include <memory>
#include "traits.hpp"

namespace old_sol {
struct default_construct {
    template<typename T, typename... Args>
    void operator()(T&& obj, Args&&... args) const {
        std::allocator<Unqualified<T>> alloc{};
        alloc.construct(obj, std::forward<Args>(args)...);
    }
};

template <typename T>
struct placement_construct {
    T obj;

    template <typename... Args>
    placement_construct( Args&&... args ) : obj(std::forward<Args>(args)...) {

    }

    template<typename... Args>
    void operator()(Args&&... args) const {
        std::allocator<Unqualified<T>> alloc{};
        alloc.construct(obj, std::forward<Args>(args)...);
    }
};

} // old_sol

#endif // SOL_DEFAULT_CONSTRUCTOR_HPP


text:
Profile

            <img class="img-circle center-block img-profile " src="<?=base_url()?>assets/images/profile/<?=$photo_url?>">

            <?php echo form_open_multipart('profile/do_upload');?>

            <input type="file" class="btn btn-primary center-block" name="userfile" size="20">

            <input type="submit" class="btn btn-primary center-block" value="upload" />

            </form>

                   Name:

                   <input type="text" class="hidden" value="<?= $name ?>" id="name">
                    <span  value="<?=$name?>" id="name"><?=$name?>

                   Email:

                   <input type="text" class="hidden" value="<?= $email ?>" id="email">
                    <span value="<?=$email?>" id="email"><?=$email?>

                    Address:

                   <input type="text" class="hidden" value="<?= $address ?>" id="address">
                    <span  value="<?=$address?>" id="address"><?=$address?>

                    Birthdate:

                   <input type="text" class="hidden" value="<?= $birthdate ?>" id="birthdate">
                    <span  value="<?=$birthdate?>"id="birthdate"><?=$birthdate?>

                    Contact(s):

                   <?php
                      if(is_array($contacts))
                      {
                          foreach($contacts as $contact)
                              echo $contact->getNumber()."  ";
                      }
                       else
                       echo $contact->getNumber();
                   ?>

           <?php
           if($room_number!="") {
               ?>

                       Room Number:

                           <?=$room_number?>

               <?php
           }
           ?>


text:
require "spec_helper"
require "metric_fu/metrics/rcov/rcov_line"

describe MetricFu::RCovLine do
  describe "#to_h" do
    it "returns a hash with the content and was_run" do
      rcov_line = RCovLine.new("some content", 1)

      expect(rcov_line.to_h).to eq(content: "some content", was_run: 1)
    end
  end

  describe "#covered?" do
    it "returns true if was_run is 1" do
      rcov_line = RCovLine.new("", 1)

      expect(rcov_line.covered?).to eq(true)
    end

    it "returns false if was_run is 0" do
      rcov_line = RCovLine.new("", 0)

      expect(rcov_line.covered?).to eq(false)
    end

    it "returns false if was_run is nil" do
      rcov_line = RCovLine.new("", nil)

      expect(rcov_line.covered?).to eq(false)
    end
  end

  describe "#missed?" do
    it "returns true if was_run is 0" do
      rcov_line = RCovLine.new("", 0)

      expect(rcov_line.missed?).to eq(true)
    end

    it "returns false if was_run is 1" do
      rcov_line = RCovLine.new("", 1)

      expect(rcov_line.missed?).to eq(false)
    end

    it "returns false if was_run is nil" do
      rcov_line = RCovLine.new("", nil)

      expect(rcov_line.missed?).to eq(false)
    end
  end

  describe "#ignored?" do
    it "returns true if was_run is nil" do
      rcov_line = RCovLine.new("", nil)

      expect(rcov_line.ignored?).to eq(true)
    end

    it "returns false if was_run is 1" do
      rcov_line = RCovLine.new("", 1)

      expect(rcov_line.ignored?).to eq(false)
    end

    it "returns false if was_run is 0" do
      rcov_line = RCovLine.new("", 0)

      expect(rcov_line.ignored?).to eq(false)
    end
  end

  describe "#css_class" do
    it "returns 'rcov_run' for an ignored line" do
      rcov_line = RCovLine.new("", nil)
      expect(rcov_line.css_class).to eq("rcov_run")
    end

    it "returns 'rcov_not_run' for a missed line" do
      rcov_line = RCovLine.new("", 0)
      expect(rcov_line.css_class).to eq("rcov_not_run")
    end

    it "returns 'rcov_run' for a covered line" do
      rcov_line = RCovLine.new("", 1)
      expect(rcov_line.css_class).to eq("rcov_run")
    end
  end
end


text:
'use strict';

const Command = require('../command');

class PkgfilesCommand extends Command {
  constructor(rawArgv) {
    super(rawArgv);
    this.usage = 'Usage: egg-bin pkgfiles';
    this.options = {
      check: {
        description: 'assert whether it\'s same',
      },
    };
  }

  get description() {
    return 'Generate pkg.files automatically';
  }

  * run({ cwd, argv }) {
    const args = [
      '--entry', 'app',
      '--entry', 'config',
      '--entry', '*.js',
    ];
    if (argv.check) args.push('--check');
    const pkgfiles = require.resolve('ypkgfiles/bin/ypkgfiles.js');
    yield this.helper.forkNode(pkgfiles, args, { cwd });
  }
}

module.exports = PkgfilesCommand;


text:
<?php

namespace BCLib\Subjectify;

use BCLib\LCCallNumbers\LCCallNumber;

interface Store
{
    public function insertTopic(Topic $topic);
    public function insertLCCRange(LCCallNumber $low_lc, LCCallNumber $high_lc, Topic $topic);
    public function search(LCCallNumber $call_number);
}


text:
package ingressclass

import (
	"context"

	apiequality "k8s.io/apimachinery/pkg/api/equality"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/util/validation/field"
	"k8s.io/apiserver/pkg/storage/names"
	utilfeature "k8s.io/apiserver/pkg/util/feature"
	"k8s.io/kubernetes/pkg/api/legacyscheme"
	"k8s.io/kubernetes/pkg/apis/networking"
	"k8s.io/kubernetes/pkg/apis/networking/validation"
	"k8s.io/kubernetes/pkg/features"
)

// ingressClassStrategy implements verification logic for IngressClass
// resources.
type ingressClassStrategy struct {
	runtime.ObjectTyper
	names.NameGenerator
}

// Strategy is the default logic that applies when creating and updating
// IngressClass objects.
var Strategy = ingressClassStrategy{legacyscheme.Scheme, names.SimpleNameGenerator}

// NamespaceScoped returns false because IngressClass is a non-namespaced
// resource.
func (ingressClassStrategy) NamespaceScoped() bool {
	return false
}

// PrepareForCreate prepares an IngressClass for creation.
func (ingressClassStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {
	ingressClass := obj.(*networking.IngressClass)
	ingressClass.Generation = 1

	if !utilfeature.DefaultFeatureGate.Enabled(features.IngressClassNamespacedParams) {
		dropIngressClassParametersReferenceScope(ingressClass)
	}
}

// PrepareForUpdate clears fields that are not allowed to be set by end users on
// update.
func (ingressClassStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {
	newIngressClass := obj.(*networking.IngressClass)
	oldIngressClass := old.(*networking.IngressClass)

	// Any changes to the spec increment the generation number.
	// See metav1.ObjectMeta description for more information on Generation.
	if !apiequality.Semantic.DeepEqual(oldIngressClass.Spec, newIngressClass.Spec) {
		newIngressClass.Generation = oldIngressClass.Generation + 1
	}

	if !utilfeature.DefaultFeatureGate.Enabled(features.IngressClassNamespacedParams) && !scopeInUse(oldIngressClass) {
		dropIngressClassParametersReferenceScope(newIngressClass)
	}
}

// Validate validates a new IngressClass.
func (ingressClassStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {
	ingressClass := obj.(*networking.IngressClass)
	return validation.ValidateIngressClass(ingressClass)
}

// Canonicalize normalizes the object after validation.
func (ingressClassStrategy) Canonicalize(obj runtime.Object) {
}

// AllowCreateOnUpdate is false for IngressClass; this means POST is needed to
// create one.
func (ingressClassStrategy) AllowCreateOnUpdate() bool {
	return false
}

// ValidateUpdate is the default update validation for an end user.
func (ingressClassStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {
	newIngressClass := obj.(*networking.IngressClass)
	oldIngressClass := old.(*networking.IngressClass)

	return validation.ValidateIngressClassUpdate(newIngressClass, oldIngressClass)
}

// AllowUnconditionalUpdate is the default update policy for IngressClass
// objects.
func (ingressClassStrategy) AllowUnconditionalUpdate() bool {
	return true
}

func scopeInUse(ingressClass *networking.IngressClass) bool {
	return ingressClass.Spec.Parameters != nil && ingressClass.Spec.Parameters.Scope != nil
}

// Drops Scope and Namespace field from IngressClass's parameters.
func dropIngressClassParametersReferenceScope(ingressClass *networking.IngressClass) {
	if ingressClass.Spec.Parameters != nil {
		ingressClass.Spec.Parameters.Scope = nil
		ingressClass.Spec.Parameters.Namespace = nil
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html;charset=utf-8" /><title>
AggregateFunction
</title><link rel="stylesheet" type="text/css" href="../../../stylesheet.css" />

AggregateFunction

A user-defined aggregate function needs to implement this interface.
 The class must be public and must have a public non-argument constructor.

Methods

void
add(Object value)

This method is called once for each row.

void
add(Object value) throws SQLException

This method is called once for each row.
 If the aggregate function is called with multiple parameters,
 those are passed as array.

Parameters:

value - the value(s) for this row

Object
getResult()

This method returns the computed aggregate value.

Object
getResult() throws SQLException

This method returns the computed aggregate value.

Returns:

the aggregated value

int
getType(int[] inputTypes)

This method must return the SQL type of the method, given the SQL type of
 the input data.

int
getType(int[] inputTypes) throws SQLException

This method must return the SQL type of the method, given the SQL type of
 the input data. The method should check here if the number of parameters
 passed is correct, and if not it should throw an exception.

Parameters:

inputTypes - the SQL type of the parameters

Returns:

the SQL type of the result

void
init(Connection conn)

This method is called when the aggregate function is used.

void
init(Connection conn) throws SQLException

This method is called when the aggregate function is used.
 A new object is created for each invocation.

Parameters:

conn - a connection to the database


text:
    Two new Pebble functions are now provided to easily bundle your Javascript files together and your CSS files together,
    directly from an HTML template.

    The jsBundle(...) function
    allows you to concatenate and optimize multiple .js files. The result can then be served as a single
    bundle that is quick to download for the client. This Pebble function is provided by the
    Spincast JS Closure Compiler plugin.

    The cssBundle(...) is similar but
    target your .css files. It is provided by the
    Spincast CSS YUI Compressor plugin.


text:
package org.openfact.pe.services.resources.admin;

import org.apache.commons.io.IOUtils;
import org.jboss.logging.Logger;
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
import org.openfact.common.ClientConnection;
import org.openfact.events.admin.OperationType;
import org.openfact.events.admin.ResourceType;
import org.openfact.models.*;
import org.openfact.models.types.DestinyType;
import org.openfact.models.types.DocumentType;
import org.openfact.models.types.InternetMediaType;
import org.openfact.models.types.SendEventStatus;
import org.openfact.models.utils.ModelToRepresentation;
import org.openfact.pe.models.utils.SunatRepresentationToType;
import org.openfact.pe.models.utils.SunatTypeToModel;
import org.openfact.pe.representations.idm.*;
import org.openfact.pe.ubl.types.SunatDocumentType;
import org.openfact.pe.ubl.types.SunatRequiredAction;
import org.openfact.pe.ubl.types.TipoDocumentoRelacionadoBaja;
import org.openfact.pe.ws.sunat.ConsultaTicketResult;
import org.openfact.pe.ws.sunat.SunatSenderManager;
import org.openfact.services.ErrorResponse;
import org.openfact.services.ModelErrorResponseException;
import org.openfact.services.managers.DocumentManager;
import org.openfact.services.managers.EventStoreManager;
import org.openfact.services.managers.OrganizationManager;
import org.openfact.services.resource.security.OrganizationAuth;
import org.openfact.services.resource.security.Resource;
import org.openfact.services.resource.security.SecurityContextProvider;
import org.openfact.services.resources.admin.AdminEventBuilder;
import org.openfact.ubl.UBLReaderWriter;
import org.openfact.ubl.utils.UBLUtil;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.validation.Valid;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@Stateless
@Consumes(MediaType.APPLICATION_JSON)
public class SunatDocumentsAdminResource {

    private static final String UPLOAD_FILE_NAME = "file";

    private static final Logger logger = Logger.getLogger(SunatDocumentsAdminResource.class);

    @Context
    protected UriInfo uriInfo;

    @Context
    protected OpenfactSession session;

    @Context
    protected ClientConnection clientConnection;

    @Inject
    private DocumentManager documentManager;

    @Inject
    private OrganizationManager organizationManager;

    @Inject
    private EventStoreManager eventStoreManager;

    @Inject
    private SecurityContextProvider securityContext;

    @Inject
    private FileProvider fileProvider;

    @Inject
    private UBLUtil ublUtil;

    @Inject
    private SunatRepresentationToType representationToType;

    @Inject
    private ModelToRepresentation modelToRepresentation;

    @Inject
    private SunatSenderManager sunatSenderManager;

    @Inject
    private SunatResourceManager sunatResourceManager;

    private OrganizationModel getOrganizationModel() {
        String organizationName = session.getContext().getOrganization().getName();
        OrganizationModel organization = organizationManager.getOrganizationByName(organizationName);
        if (organization == null) {
            throw new NotFoundException("Organization " + organizationName + " not found.");
        }
        return organization;
    }

    private boolean validateOrganizationInfo(OrganizationModel organization) {
        if (organization.getAdditionalAccountId() == null || organization.getAdditionalAccountId().trim().isEmpty()
                || organization.getAssignedIdentificationId() == null || organization.getAssignedIdentificationId().trim().isEmpty()
                || organization.getRegistrationName() == null || organization.getRegistrationName().trim().isEmpty()
                || organization.getSupplierName() == null || organization.getSupplierName().trim().isEmpty()
                || organization.getStreetName() == null || organization.getStreetName().trim().isEmpty()
                || organization.getCitySubdivisionName() == null || organization.getCitySubdivisionName().trim().isEmpty()
                || organization.getCityName() == null || organization.getCityName().trim().isEmpty()
                || organization.getCountrySubentity() == null || organization.getCountrySubentity().trim().isEmpty()
                || organization.getDistrict() == null || organization.getDistrict().trim().isEmpty()
                || organization.getCountryIdentificationCode() == null || organization.getCountryIdentificationCode().trim().isEmpty()) {
            return false;
        }
        return true;
    }

    private DocumentModel getDocument(String documentIdPk, OrganizationModel organization) {
        DocumentModel document = documentManager.getDocumentById(documentIdPk, organization);
        if (document == null) {
            throw new NotFoundException("Document not found.");
        }
        return document;
    }

    private OrganizationAuth getAuth(OrganizationModel organization) {
        List<OrganizationModel> permittedOrganizations = securityContext.getPermittedOrganizations(session);
        if (!securityContext.getClientUser(session).hasAppRole(AdminRoles.ADMIN) && !permittedOrganizations.contains(organization)) {
            throw new ForbiddenException();
        }
        return securityContext.getClientUser(session).organizationAuth(Resource.DOCUMENT);
    }

    private AdminEventBuilder getAdminEvent(OrganizationModel organization) {
        return new AdminEventBuilder(organization, securityContext.getClientUser(session), session, clientConnection).resource(ResourceType.DOCUMENT);
    }

    private void checkSerieAndNumber(String serie, String numero, String documentType, OrganizationModel organization) throws ModelErrorResponseException {
        if (serie != null || numero != null) {
            if (serie != null && numero != null) {
                // Double-check duplicated documentId
                if (documentManager.getDocumentByTypeAndDocumentId(documentType, serie + "-" + numero, organization) != null) {
                    throw new ModelErrorResponseException("Document exists with same documentId", Response.Status.CONFLICT);
                }
            } else {
                throw new ModelErrorResponseException("Invalid number and/or serie", Response.Status.BAD_REQUEST);
            }
        }
    }

    private List<InputPart> getInputs(MultipartFormDataInput multipartFormDataInput) {
        Map<String, List<InputPart>> uploadForm = multipartFormDataInput.getFormDataMap();
        return uploadForm.get(UPLOAD_FILE_NAME);
    }

    private <T> T readFile(InputPart inputPart, String documentType, Class<T> tClass) throws IOException {
        InputStream inputStream = inputPart.getBody(InputStream.class, null);
        byte[] bytes = IOUtils.toByteArray(inputStream);

        UBLReaderWriter<T> readerWriter = (UBLReaderWriter<T>) ublUtil.getReaderWriter(documentType).reader();
        T t = readerWriter.reader().read(bytes);
        if (t == null) {
            throw new ModelRuntimeException("Could not read file");
        }
        return t;
    }

    @POST
    @Path("/documents/invoices")
    @Produces(MediaType.APPLICATION_JSON)
    public Response createInvoice(@QueryParam("async") @DefaultValue("false") Boolean async, @Valid final DocumentRepresentation rep) throws ModelErrorResponseException, ModelException {
        OrganizationModel organization = getOrganizationModel();
        OrganizationAuth auth = getAuth(organization);

        auth.requireManage();
        checkSerieAndNumber(rep.getSerie(), rep.getNumero(), DocumentType.INVOICE.toString(), organization);

        if (!validateOrganizationInfo(organization)) {
            throw new ModelErrorResponseException("Datos de organizacion insuficientes", Response.Status.BAD_REQUEST);
        }

        try {
            DocumentModel document = sunatResourceManager.createInvoice(organization, rep);

            sendDocumentToThirdParty(organization, document, rep.isEnviarAutomaticamenteASunat(), rep.isEnviarAutomaticamenteAlCliente(), async);

            URI location = uriInfo.getAbsolutePathBuilder().path(document.getId()).build();
            eventStoreManager.send(organization, getAdminEvent(organization)
                    .operation(OperationType.CREATE)
                    .resourcePath(uriInfo, document.getId())
                    .representation(rep)
                    .getEvent());
            return Response.created(location).entity(modelToRepresentation.toRepresentation(document, false)).build();
        } catch (ModelDuplicateException e) {
            throw new ModelErrorResponseException("Invoice exists with same documentId", Response.Status.CONFLICT);
        } catch (ModelException e) {
            throw new ModelErrorResponseException("Invoice could not be created", Response.Status.INTERNAL_SERVER_ERROR);
        }
    }

    @PUT
    @Path("/documents/invoices/{documentPkId}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response updateInvoice(@PathParam("documentPkId") String documentPkId, @QueryParam("async") @DefaultValue("false") Boolean async, @Valid final DocumentRepresentation rep) throws ModelErrorResponseException, ModelException {
        OrganizationModel organization = getOrganizationModel();
        OrganizationAuth auth = getAuth(organization);

        auth.requireManage();

        if (!validateOrganizationInfo(organization)) {
            throw new ModelErrorResponseException("Datos de organizacion insuficientes", Response.Status.BAD_REQUEST);
        }

        try {
            DocumentModel document = documentManager.getDocumentById(documentPkId, organization);
            if (document.isClosed()) {
                throw new ModelErrorResponseException("Documento cerrado, no se puede editar", Response.Status.BAD_REQUEST);
            }
            document = sunatResourceManager.updateInvoice(organization, rep, documentPkId);

            sendDocumentToThirdParty(organization, document, rep.isEnviarAutomaticamenteASunat(), rep.isEnviarAutomaticamenteAlCliente(), async);

            URI location = uriInfo.getAbsolutePathBuilder().path(document.getId()).build();
            eventStoreManager.send(organization, getAdminEvent(organization)
                    .operation(OperationType.UPDATE)
                    .resourcePath(uriInfo, document.getId())
                    .representation(rep)
                    .getEvent());
            return Response.ok(location).entity(modelToRepresentation.toRepresentation(document, false)).build();
        } catch (ModelDuplicateException e) {
            throw new ModelErrorResponseException("Invoice exists with same documentId", Response.Status.CONFLICT);
        } catch (ModelException e) {
            throw new ModelErrorResponseException("Invoice could not be created", Response.Status.INTERNAL_SERVER_ERROR);
        }
    }

    private void sendDocumentToThirdParty(OrganizationModel organization, DocumentModel document, boolean enviarASunat, boolean enviarACliente, boolean async) throws ModelErrorResponseException {
        if (enviarASunat) {
            Future<Boolean> future = sunatResourceManager.sendDocumentToThirdParty(organization.getId(), document.getId());
            if (!async) {
                try {
                    future.get();
                } catch (InterruptedException | ExecutionException e) {
                    logger.error(e);
                }
            }
        }
        if (enviarACliente) {
            Future<Boolean> future = sunatResourceManager.sendDocumentToCustomer(organization.getId(), document.getId());
            if (!async) {
                try {
                    future.get();
                } catch (InterruptedException | ExecutionException e) {
                    logger.error(e);
                }
            }
        }
    }

    @POST
    @Path("/documents/credit-notes")
    @Produces(MediaType.APPLICATION_JSON)
    public Response createCreditNote(@QueryParam("async") @DefaultValue("false") Boolean async, @Valid final DocumentRepresentation rep) throws ModelErrorResponseException {
        OrganizationModel organization = getOrganizationModel();
        OrganizationAuth auth = getAuth(organization);

        auth.requireManage();
        checkSerieAndNumber(rep.getSerie(), rep.getNumero(), DocumentType.CREDIT_NOTE.toString(), organization);

        if (!validateOrganizationInfo(organization)) {
            throw new ModelErrorResponseException("Datos de organizacion insuficientes", Response.Status.BAD_REQUEST);
        }

        try {
            DocumentModel document = sunatResourceManager.createCreditNote(organization, rep);

            sendDocumentToThirdParty(organization, document, rep.isEnviarAutomaticamenteASunat(), rep.isEnviarAutomaticamenteAlCliente(), async);

            URI location = uriInfo.getAbsolutePathBuilder().path(document.getId()).build();
            eventStoreManager.send(organization, getAdminEvent(organization)
                    .operation(OperationType.CREATE)
                    .resourcePath(uriInfo, document.getId())
                    .representation(rep)
                    .getEvent());
            return Response.created(location).entity(modelToRepresentation.toRepresentation(document, false)).build();
        } catch (ModelDuplicateException e) {
            throw new ModelErrorResponseException("Credit note exists with same documentId", Response.Status.CONFLICT);
        } catch (ModelException e) {
            throw new ModelErrorResponseException("Credit note could not be created", Response.Status.INTERNAL_SERVER_ERROR);
        }
    }

    @PUT
    @Path("/documents/credit-notes/{documentPkId}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response updateCreditNote(@PathParam("documentPkId") String documentPkId, @QueryParam("async") @DefaultValue("false") Boolean async, @Valid final DocumentRepresentation rep) throws ModelErrorResponseException {
        OrganizationModel organization = getOrganizationModel();
        OrganizationAuth auth = getAuth(organization);

        auth.requireManage();

        if (!validateOrganizationInfo(organization)) {
            throw new ModelErrorResponseException("Datos de organizacion insuficientes", Response.Status.BAD_REQUEST);
        }

        try {
            DocumentModel document = documentManager.getDocumentById(documentPkId, organization);
            if (document.isClosed()) {
                throw new ModelErrorResponseException("Documento cerrado, no se puede editar", Response.Status.BAD_REQUEST);
            }
            document = sunatResourceManager.updateCreditNote(organization, rep, documentPkId);

            sendDocumentToThirdParty(organization, document, rep.isEnviarAutomaticamenteASunat(), rep.isEnviarAutomaticamenteAlCliente(), async);

            URI location = uriInfo.getAbsolutePathBuilder().path(document.getId()).build();
            eventStoreManager.send(organization, getAdminEvent(organization)
                    .operation(OperationType.UPDATE)
                    .resourcePath(uriInfo, document.getId())
                    .representation(rep)
                    .getEvent());
            return Response.ok(location).entity(modelToRepresentation.toRepresentation(document, false)).build();
        } catch (ModelDuplicateException e) {
            throw new ModelErrorResponseException("Credit Note exists with same documentId", Response.Status.CONFLICT);
        } catch (ModelException e) {
            throw new ModelErrorResponseException("Credit Note could not be created", Response.Status.INTERNAL_SERVER_ERROR);
        }
    }

    @POST
    @Path("/documents/debit-notes")
    @Produces(MediaType.APPLICATION_JSON)
    public Response createDebitNote(@QueryParam("async") @DefaultValue("false") Boolean async, @Valid final DocumentRepresentation rep) throws ModelErrorResponseException {
        OrganizationModel organization = getOrganizationModel();
        OrganizationAuth auth = getAuth(organization);

        auth.requireManage();
        checkSerieAndNumber(rep.getSerie(), rep.getNumero(), DocumentType.DEBIT_NOTE.toString(), organization);

        if (!validateOrganizationInfo(organization)) {
            throw new ModelErrorResponseException("Datos de organizacion insuficientes", Response.Status.BAD_REQUEST);
        }

        try {
            DocumentModel document = sunatResourceManager.createDebitNote(organization, rep);

            sendDocumentToThirdParty(organization, document, rep.isEnviarAutomaticamenteASunat(), rep.isEnviarAutomaticamenteAlCliente(), async);

            URI location = uriInfo.getAbsolutePathBuilder().path(document.getId()).build();
            eventStoreManager.send(organization, getAdminEvent(organization)
                    .operation(OperationType.CREATE)
                    .resourcePath(uriInfo, document.getId())
                    .representation(rep)
                    .getEvent());
            return Response.created(location).entity(modelToRepresentation.toRepresentation(document, false)).build();
        } catch (ModelDuplicateException e) {
            throw new ModelErrorResponseException("Debit note exists with same documentId", Response.Status.CONFLICT);
        } catch (ModelException e) {
            throw new ModelErrorResponseException("Debit note could not be created", Response.Status.INTERNAL_SERVER_ERROR);
        }
    }

    @PUT
    @Path("/documents/debit-notes/{documentPkId}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response updateDebitNote(@PathParam("documentPkId") String documentPkId, @QueryParam("async") @DefaultValue("false") Boolean async, @Valid final DocumentRepresentation rep) throws ModelErrorResponseException {
        OrganizationModel organization = getOrganizationModel();
        OrganizationAuth auth = getAuth(organization);

        auth.requireManage();

        if (!validateOrganizationInfo(organization)) {
            throw new ModelErrorResponseException("Datos de organizacion insuficientes", Response.Status.BAD_REQUEST);
        }

        try {
            DocumentModel document = documentManager.getDocumentById(documentPkId, organization);
            if (document.isClosed()) {
                throw new ModelErrorResponseException("Documento cerrado, no se puede editar", Response.Status.BAD_REQUEST);
            }
            document = sunatResourceManager.updateDebitNote(organization, rep, documentPkId);

            sendDocumentToThirdParty(organization, document, rep.isEnviarAutomaticamenteASunat(), rep.isEnviarAutomaticamenteAlCliente(), async);

            URI location = uriInfo.getAbsolutePathBuilder().path(document.getId()).build();
            eventStoreManager.send(organization, getAdminEvent(organization)
                    .operation(OperationType.UPDATE)
                    .resourcePath(uriInfo, document.getId())
                    .representation(rep)
                    .getEvent());
            return Response.ok(location).entity(modelToRepresentation.toRepresentation(document, false)).build();
        } catch (ModelDuplicateException e) {
            throw new ModelErrorResponseException("Debit Note exists with same documentId", Response.Status.CONFLICT);
        } catch (ModelException e) {
            throw new ModelErrorResponseException("Debit Note could not be created", Response.Status.INTERNAL_SERVER_ERROR);
        }
    }

    @POST
    @Path("/documents/despatch-advices")
    @Produces(MediaType.APPLICATION_JSON)
    public Response createDespatchAdvice(@QueryParam("async") @DefaultValue("false") Boolean async, @Valid final DespatchAdviceRepresentation rep) throws ModelErrorResponseException {
        OrganizationModel organization = getOrganizationModel();
        OrganizationAuth auth = getAuth(organization);

        auth.requireManage();
        checkSerieAndNumber(rep.getSerie(), rep.getNumero(), DocumentType.DESPATCH_ADVICE.toString(), organization);

        if (!validateOrganizationInfo(organization)) {
            throw new ModelErrorResponseException("Datos de organizacion insuficientes", Response.Status.BAD_REQUEST);
        }

        try {
            DocumentModel document = sunatResourceManager.createDespatchAdvice(organization, rep);

            sendDocumentToThirdParty(organization, document, rep.isEnviarAutomaticamenteASunat(), rep.isEnviarAutomaticamenteAlCliente(), async);

            URI location = uriInfo.getAbsolutePathBuilder().path(document.getId()).build();
            eventStoreManager.send(organization, getAdminEvent(organization)
                    .operation(OperationType.CREATE)
                    .resourcePath(uriInfo, document.getId())
                    .representation(rep)
                    .getEvent());
            return Response.created(location).entity(modelToRepresentation.toRepresentation(document, false)).build();
        } catch (ModelDuplicateException e) {
            throw new ModelErrorResponseException("Despatch advice exists with same documentId", Response.Status.CONFLICT);
        } catch (ModelException e) {
            throw new ModelErrorResponseException("Despatch advice could not be created", Response.Status.INTERNAL_SERVER_ERROR);
        }
    }

    @PUT
    @Path("/documents/despatch-advices/{documentPkId}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response updateDespatchAdvice(@PathParam("documentPkId") String documentPkId, @QueryParam("async") @DefaultValue("false") Boolean async, @Valid final DespatchAdviceRepresentation rep) throws ModelErrorResponseException {
        OrganizationModel organization = getOrganizationModel();
        OrganizationAuth auth = getAuth(organization);

        auth.requireManage();

        if (!validateOrganizationInfo(organization)) {
            throw new ModelErrorResponseException("Datos de organizacion insuficientes", Response.Status.BAD_REQUEST);
        }

        try {
            DocumentModel document = documentManager.getDocumentById(documentPkId, organization);
            if (document.isClosed()) {
                throw new ModelErrorResponseException("Documento cerrado, no se puede editar", Response.Status.BAD_REQUEST);
            }
            document = sunatResourceManager.updateDespatchAdvice(organization, rep, documentPkId);

            sendDocumentToThirdParty(organization, document, rep.isEnviarAutomaticamenteASunat(), rep.isEnviarAutomaticamenteAlCliente(), async);

            URI location = uriInfo.getAbsolutePathBuilder().path(document.getId()).build();
            eventStoreManager.send(organization, getAdminEvent(organization)
                    .operation(OperationType.UPDATE)
                    .resourcePath(uriInfo, document.getId())
                    .representation(rep)
                    .getEvent());
            return Response.ok(location).entity(modelToRepresentation.toRepresentation(document, false)).build();
        } catch (ModelDuplicateException e) {
            throw new ModelErrorResponseException("Despatch advice exists with same documentId", Response.Status.CONFLICT);
        } catch (ModelException e) {
            throw new ModelErrorResponseException("Despatch advice could not be created", Response.Status.INTERNAL_SERVER_ERROR);
        }
    }
//    @POST
//    @Path("/documents/extensions/upload/perceptions")
//    @Consumes("multipart/form-data")
//    @Produces(MediaType.APPLICATION_JSON)
//    public Response uploadPerception(final MultipartFormDataInput input) throws ModelErrorResponseException {
//        OrganizationModel organization = getOrganizationModel();
//        OrganizationAuth auth = getAuth(organization);
//
//        auth.requireManage();
//
//        List<InputPart> inputParts = getInputs(input);
//
//        for (InputPart inputPart : inputParts) {
//            try {
//                PerceptionType perceptionType = readFile(inputPart, SunatDocumentType.PERCEPTION.toString(), PerceptionType.class);
//
//                // Double-check duplicated documentId
//                if (perceptionType.getId() != null && perceptionType.getId().getValue() != null && documentManager.getDocumentByTypeAndDocumentId(SunatDocumentType.PERCEPTION.toString(), perceptionType.getId().getValue(), organization) != null) {
//                    throw new ModelDuplicateException("Perception exists with same documentId[" + perceptionType.getId().getValue() + "]");
//                }
//
//                setPerceptionIDType(organization, perceptionType);
//
//                DocumentModel document = documentManager.addDocument(organization, perceptionType.getId().getValue(), SunatDocumentType.PERCEPTION.toString(), perceptionType);
//                eventStoreManager.send(organization, getAdminEvent(organization)
//                        .operation(OperationType.CREATE)
//                        .resourcePath(uriInfo, document.getId())
//                        .representation(perceptionType)
//                        .getEvent());
//            } catch (IOException e) {
//                logger.error("Error reading input data", e);
//                throw new ModelErrorResponseException("Error Reading data", Response.Status.BAD_REQUEST);
//            } catch (ModelDuplicateException e) {
//                throw new ModelErrorResponseException("Perception exists with same documentId");
//            } catch (ModelException e) {
//                throw new ModelErrorResponseException("Could not create document");
//            }
//        }
//
//        return Response.ok().build();
//    }

//    @POST
//    @Path("/documents/extensions/upload/retentions")
//    @Consumes("multipart/form-data")
//    @Produces(MediaType.APPLICATION_JSON)
//    public Response uploadRetention(final MultipartFormDataInput input) throws ModelErrorResponseException {
//        OrganizationModel organization = getOrganizationModel();
//        OrganizationAuth auth = getAuth(organization);
//
//        auth.requireManage();
//
//        List<InputPart> inputParts = getInputs(input);
//
//        for (InputPart inputPart : inputParts) {
//            try {
//                RetentionType retentionType = readFile(inputPart, SunatDocumentType.RETENTION.toString(), RetentionType.class);
//
//                // Double-check duplicated documentId
//                if (retentionType.getId() != null && retentionType.getId().getValue() != null && documentManager.getDocumentByTypeAndDocumentId(SunatDocumentType.RETENTION.toString(), retentionType.getId().getValue(), organization) != null) {
//                    throw new ModelDuplicateException("Perception exists with same documentId[" + retentionType.getId().getValue() + "]");
//                }
//
//                setRetentionIDType(organization, retentionType);
//
//                DocumentModel document = documentManager.addDocument(organization, retentionType.getId().getValue(), SunatDocumentType.RETENTION.toString(), retentionType);
//                eventStoreManager.send(organization, getAdminEvent(organization)
//                        .operation(OperationType.CREATE)
//                        .resourcePath(uriInfo, document.getId())
//                        .representation(retentionType)
//                        .getEvent());
//            } catch (IOException e) {
//                logger.error("Error reading input data", e);
//                throw new ModelErrorResponseException("Error Reading data", Response.Status.BAD_REQUEST);
//            } catch (ModelDuplicateException e) {
//                throw new ModelErrorResponseException("Retention exists with same documentId");
//            } catch (ModelException e) {
//                throw new ModelErrorResponseException("Could not create document");
//            }
//        }
//
//        return Response.ok().build();
//    }

//    @POST
//    @Path("/documents/extensions/upload/voided-documents")
//    @Consumes("multipart/form-data")
//    @Produces(MediaType.APPLICATION_JSON)
//    public Response uploadVoidedDocument(final MultipartFormDataInput input) throws ModelErrorResponseException {
//        OrganizationModel organization = getOrganizationModel();
//        OrganizationAuth auth = getAuth(organization);
//
//        auth.requireManage();
//
//        List<InputPart> inputParts = getInputs(input);
//
//        for (InputPart inputPart : inputParts) {
//            try {
//                VoidedDocumentsType voidedDocumentsType = readFile(inputPart, SunatDocumentType.VOIDED_DOCUMENTS.toString(), VoidedDocumentsType.class);
//
//                // Double-check duplicated documentId
//                if (voidedDocumentsType.getID() != null && voidedDocumentsType.getID().getValue() != null && documentManager.getDocumentByTypeAndDocumentId(SunatDocumentType.RETENTION.toString(), voidedDocumentsType.getID().getValue(), organization) != null) {
//                    throw new ModelDuplicateException("Voided document exists with same documentId[" + voidedDocumentsType.getID().getValue() + "]");
//                }
//
//                setVoidedDocumentIDType(organization, voidedDocumentsType);
//
//                DocumentModel document = documentManager.addDocument(organization, voidedDocumentsType.getID().getValue(), SunatDocumentType.VOIDED_DOCUMENTS.toString(), voidedDocumentsType);
//                eventStoreManager.send(organization, getAdminEvent(organization)
//                        .operation(OperationType.CREATE)
//                        .resourcePath(uriInfo, document.getId())
//                        .representation(voidedDocumentsType)
//                        .getEvent());
//            } catch (IOException e) {
//                logger.error("Error reading input data", e);
//                throw new ModelErrorResponseException("Error Reading data", Response.Status.BAD_REQUEST);
//            } catch (ModelDuplicateException e) {
//                throw new ModelErrorResponseException("Retention exists with same documentId");
//            } catch (ModelException e) {
//                throw new ModelErrorResponseException("Could not create document");
//            }
//        }
//
//        return Response.ok().build();
//    }

    @POST
    @Path("/documents/perceptions")
    @Produces(MediaType.APPLICATION_JSON)
    public Response createPerception(@QueryParam("async") @DefaultValue("false") Boolean async, DocumentoSunatRepresentation rep) throws ModelErrorResponseException {
        OrganizationModel organization = getOrganizationModel();
        OrganizationAuth auth = getAuth(organization);

        auth.requireManage();
        checkSerieAndNumber(rep.getSerieDocumento(), rep.getNumeroDocumento(), SunatDocumentType.PERCEPTION.toString(), organization);

        if (!validateOrganizationInfo(organization)) {
            throw new ModelErrorResponseException("Datos de organizacion insuficientes", Response.Status.BAD_REQUEST);
        }

        try {
            DocumentModel document = sunatResourceManager.createPerception(organization, rep);

            sendDocumentToThirdParty(organization, document, rep.isEnviarAutomaticamenteASunat(), rep.isEnviarAutomaticamenteAlCliente(), async);

            URI location = uriInfo.getAbsolutePathBuilder().path(document.getId()).build();
            eventStoreManager.send(organization, getAdminEvent(organization)
                    .operation(OperationType.CREATE)
                    .resourcePath(uriInfo, document.getId())
                    .representation(rep)
                    .getEvent());
            return Response.created(location).entity(modelToRepresentation.toRepresentation(document, false)).build();
        } catch (ModelDuplicateException e) {
            throw new ModelErrorResponseException("Perception exists with same documentId", Response.Status.CONFLICT);
        } catch (ModelException e) {
            throw new ModelErrorResponseException("Perception could not be created", Response.Status.INTERNAL_SERVER_ERROR);
        }
    }

    @PUT
    @Path("/documents/perceptions/{documentPkId}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response updatePerception(@PathParam("documentPkId") String documentPkId, @QueryParam("async") @DefaultValue("false") Boolean async, DocumentoSunatRepresentation rep) throws ModelErrorResponseException {
        OrganizationModel organization = getOrganizationModel();
        OrganizationAuth auth = getAuth(organization);

        auth.requireManage();

        if (!validateOrganizationInfo(organization)) {
            throw new ModelErrorResponseException("Datos de organizacion insuficientes", Response.Status.BAD_REQUEST);
        }

        try {
            DocumentModel document = documentManager.getDocumentById(documentPkId, organization);
            if (document.isClosed()) {
                throw new ModelErrorResponseException("Documento cerrado, no se puede editar", Response.Status.BAD_REQUEST);
            }
            document = sunatResourceManager.updatePerception(organization, rep, documentPkId);

            sendDocumentToThirdParty(organization, document, rep.isEnviarAutomaticamenteASunat(), rep.isEnviarAutomaticamenteAlCliente(), async);

            URI location = uriInfo.getAbsolutePathBuilder().path(document.getId()).build();
            eventStoreManager.send(organization, getAdminEvent(organization)
                    .operation(OperationType.UPDATE)
                    .resourcePath(uriInfo, document.getId())
                    .representation(rep)
                    .getEvent());
            return Response.ok(location).entity(modelToRepresentation.toRepresentation(document, false)).build();
        } catch (ModelDuplicateException e) {
            throw new ModelErrorResponseException("Perception exists with same documentId", Response.Status.CONFLICT);
        } catch (ModelException e) {
            throw new ModelErrorResponseException("Perception could not be created", Response.Status.INTERNAL_SERVER_ERROR);
        }
    }

    @POST
    @Path("/documents/retentions")
    @Produces(MediaType.APPLICATION_JSON)
    public Response createRetention(@QueryParam("async") @DefaultValue("false") Boolean async, DocumentoSunatRepresentation rep) throws ModelErrorResponseException {
        OrganizationModel organization = getOrganizationModel();
        OrganizationAuth auth = getAuth(organization);

        auth.requireManage();
        checkSerieAndNumber(rep.getSerieDocumento(), rep.getNumeroDocumento(), SunatDocumentType.RETENTION.toString(), organization);

        if (!validateOrganizationInfo(organization)) {
            throw new ModelErrorResponseException("Datos de organizacion insuficientes", Response.Status.BAD_REQUEST);
        }

        try {
            DocumentModel document = sunatResourceManager.createRetention(organization, rep);

            sendDocumentToThirdParty(organization, document, rep.isEnviarAutomaticamenteASunat(), rep.isEnviarAutomaticamenteAlCliente(), async);

            URI location = uriInfo.getAbsolutePathBuilder().path(document.getId()).build();
            eventStoreManager.send(organization, getAdminEvent(organization)
                    .operation(OperationType.CREATE)
                    .resourcePath(uriInfo, document.getId())
                    .representation(rep)
                    .getEvent());
            return Response.created(location).entity(modelToRepresentation.toRepresentation(document, false)).build();
        } catch (ModelDuplicateException e) {
            throw new ModelErrorResponseException("Perception exists with same documentId", Response.Status.CONFLICT);
        } catch (ModelException e) {
            throw new ModelErrorResponseException("Perception could not be created", Response.Status.INTERNAL_SERVER_ERROR);
        }
    }

    @PUT
    @Path("/documents/retentions/{documentPkId}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response updateRetention(@PathParam("documentPkId") String documentPkId, @QueryParam("async") @DefaultValue("false") Boolean async, DocumentoSunatRepresentation rep) throws ModelErrorResponseException {
        OrganizationModel organization = getOrganizationModel();
        OrganizationAuth auth = getAuth(organization);

        auth.requireManage();

        if (!validateOrganizationInfo(organization)) {
            throw new ModelErrorResponseException("Datos de organizacion insuficientes", Response.Status.BAD_REQUEST);
        }

        try {
            DocumentModel document = documentManager.getDocumentById(documentPkId, organization);
            if (document.isClosed()) {
                throw new ModelErrorResponseException("Documento cerrado, no se puede editar", Response.Status.BAD_REQUEST);
            }
            document = sunatResourceManager.updateRetention(organization, rep, documentPkId);

            sendDocumentToThirdParty(organization, document, rep.isEnviarAutomaticamenteASunat(), rep.isEnviarAutomaticamenteAlCliente(), async);

            URI location = uriInfo.getAbsolutePathBuilder().path(document.getId()).build();
            eventStoreManager.send(organization, getAdminEvent(organization)
                    .operation(OperationType.UPDATE)
                    .resourcePath(uriInfo, document.getId())
                    .representation(rep)
                    .getEvent());
            return Response.ok(location).entity(modelToRepresentation.toRepresentation(document, false)).build();
        } catch (ModelDuplicateException e) {
            throw new ModelErrorResponseException("Retention exists with same documentId", Response.Status.CONFLICT);
        } catch (ModelException e) {
            throw new ModelErrorResponseException("Retention could not be created", Response.Status.INTERNAL_SERVER_ERROR);
        }
    }

    @POST
    @Path("/documents/voided-documents")
    @Produces(MediaType.APPLICATION_JSON)
    public Response voidedDocument(@QueryParam("async") @DefaultValue("false") Boolean async, VoidedRepresentation rep) throws ModelErrorResponseException {
        OrganizationModel organization = getOrganizationModel();
        OrganizationAuth auth = getAuth(organization);

        auth.requireManage();
        checkSerieAndNumber(rep.getSerieDocumento(), rep.getNumeroDocumento(), SunatDocumentType.VOIDED_DOCUMENTS.toString(), organization);

        if (!validateOrganizationInfo(organization)) {
            throw new ModelErrorResponseException("Datos de organizacion insuficientes", Response.Status.BAD_REQUEST);
        }

        try {
            for (int i = 0; i < rep.getDetalle().size(); i++) {
                VoidedLineRepresentation lineRepresentation = rep.getDetalle().get(i);
                if (lineRepresentation.getTipoDocumentoRelacionado().equals(TipoDocumentoRelacionadoBaja.BOLETA.getCodigo())) {
                    DocumentModel invoice = documentManager.getDocumentByTypeAndDocumentId(TipoDocumentoRelacionadoBaja.FACTURA.getDocumentType(), lineRepresentation.getNumeroDocumentoRelacionado(), organization);
                    if (invoice != null) {
                        invoice.setBajaEnProceso();
                        invoice.summaryVoided();
                    }
                    rep.getDetalle().remove(i);
                }
                if (lineRepresentation.getTipoDocumentoRelacionado().equals(TipoDocumentoRelacionadoBaja.NOTA_CREDITO.getCodigo()) && lineRepresentation.getNumeroDocumentoRelacionado().toUpperCase().startsWith("B")) {
                    DocumentModel creditNote = documentManager.getDocumentByTypeAndDocumentId(TipoDocumentoRelacionadoBaja.NOTA_CREDITO.getDocumentType(), lineRepresentation.getNumeroDocumentoRelacionado(), organization);
                    if (creditNote != null) {
                        creditNote.setBajaEnProceso();
                        creditNote.summaryVoided();
                    }
                    rep.getDetalle().remove(i);
                }
                if (lineRepresentation.getTipoDocumentoRelacionado().equals(TipoDocumentoRelacionadoBaja.NOTA_DEBITO.getCodigo()) && lineRepresentation.getNumeroDocumentoRelacionado().toUpperCase().startsWith("B")) {
                    DocumentModel debitNote = documentManager.getDocumentByTypeAndDocumentId(TipoDocumentoRelacionadoBaja.NOTA_DEBITO.getDocumentType(), lineRepresentation.getNumeroDocumentoRelacionado(), organization);
                    if (debitNote != null) {
                        debitNote.setBajaEnProceso();
                        debitNote.summaryVoided();
                    }
                    rep.getDetalle().remove(i);
                }
            }
            if (!rep.getDetalle().isEmpty()) {
                DocumentModel document = sunatResourceManager.createVoidedDocuments(organization, rep);
                sendDocumentToThirdParty(organization, document, rep.isEnviarAutomaticamenteASunat(), rep.isEnviarAutomaticamenteAlCliente(), async);
                URI location = uriInfo.getAbsolutePathBuilder().path(document.getId()).build();
                eventStoreManager.send(organization, getAdminEvent(organization)
                        .operation(OperationType.CREATE)
                        .resourcePath(uriInfo, document.getId())
                        .representation(rep)
                        .getEvent());
                return Response.created(location).entity(modelToRepresentation.toRepresentation(document, false)).build();
            } else {
             /*   DocumentRepresentation representation = new DocumentRepresentation();
                representation.setId(UUID.randomUUID().toString());
                URI location = uriInfo.getAbsolutePathBuilder().path(representation.getId()).build();*/
                return Response.ok().build();//.created(location).(representation).build();
            }
        } catch (ModelDuplicateException e) {
            throw new ModelErrorResponseException("Voided Documents exists with same documentId", Response.Status.CONFLICT);
        } catch (ModelException e) {
            throw new ModelErrorResponseException("Voided Documents could not be created", Response.Status.INTERNAL_SERVER_ERROR);
        }
    }

    @GET
    @Path("/documents/{documentId}/cdr")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response getCdr(@PathParam("documentId") final String documentIdPk) {
        OrganizationModel organization = getOrganizationModel();
        OrganizationAuth auth = getAuth(organization);

        auth.requireView();
        DocumentModel document = getDocument(documentIdPk, organization);

        // Para las nuevas versiones donde los cdr se guardan en los mismos documentos
        FileModel cdr = document.getCdrFile();
        if (cdr != null) {
            Response.ResponseBuilder response = Response.ok(cdr.getFile());
            String internetMediaType = InternetMediaType.getMymeTypeFromExtension(cdr.getExtension());
            if (internetMediaType != null && !internetMediaType.isEmpty()) response.type(internetMediaType);
            response.header("content-disposition", "attachment; filename=\"" + cdr.getFileName() + "\"");
            return response.build();
        }

        // Para las versiones anteriores donde los cdr se guardaban en los sendEvents
        Map<String, String> params = new HashMap<>();
        params.put(DocumentModel.SEND_EVENT_DESTINY, DestinyType.THIRD_PARTY.toString());
        params.put(DocumentModel.SEND_EVENT_STATUS, SendEventStatus.SUCCESS.toString());

        List<SendEventModel> sendEvents = document.searchForSendEvent(params);
        if (sendEvents.isEmpty()) {
            return ErrorResponse.error("No se encontro un envio valido a SUNAT", Response.Status.BAD_REQUEST);
        } else {
            SendEventModel sendEvent = sendEvents.get(0);
            List<String> fileIds = sendEvent.getAttachedFileIds();
            if (fileIds.isEmpty()) {
                return ErrorResponse.error("Cdr no encontrado", Response.Status.NOT_FOUND);
            } else {
                FileModel cdrFile = fileProvider.getFileById(organization, fileIds.get(fileIds.size() - 1));
                Response.ResponseBuilder response = Response.ok(cdrFile.getFile());
                String internetMediaType = InternetMediaType.getMymeTypeFromExtension(cdrFile.getExtension());
                if (internetMediaType != null && !internetMediaType.isEmpty()) response.type(internetMediaType);
                response.header("content-disposition", "attachment; filename=\"" + cdrFile.getFileName() + "\"");
                return response.build();
            }
        }
    }

    @GET
    @Path("/documents/{documentId}/check-ticket")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response checkTicket(@PathParam("documentId") final String documentIdPk) throws ModelErrorResponseException {
        OrganizationModel organization = getOrganizationModel();
        OrganizationAuth auth = getAuth(organization);

        auth.requireView();
        DocumentModel document = getDocument(documentIdPk, organization);

        if (document.getRequiredActions().contains(SunatRequiredAction.CONSULTAR_TICKET.toString())) {

            Map<String, String> params = new HashMap<>();
            params.put(DocumentModel.SEND_EVENT_DESTINY, DestinyType.THIRD_PARTY.toString());
            params.put(DocumentModel.SEND_EVENT_STATUS, SendEventStatus.SUCCESS.toString());

            List<SendEventModel> sendEvents = document.searchForSendEvent(params);
            if (sendEvents.isEmpty()) {
                throw new ModelErrorResponseException("No existe ningun sendEvent que consultar", Response.Status.BAD_REQUEST);
            } else {
                SendEventModel sendEvent = sendEvents.get(0); // obtener el primero

                String ticket = sendEvent.getAttribute(SunatTypeToModel.NUMERO_TICKET);
                if (ticket == null) {
                    throw new ModelErrorResponseException("No existe ningun ticket que consultar", Response.Status.BAD_REQUEST);
                }

                try {
                    sunatSenderManager.checkTicket(organization, document, sendEvent);
                } catch (ModelException e) {
                    throw new ModelErrorResponseException("Error interno al consultar ticket", Response.Status.BAD_REQUEST);
                }

                return getCdr(documentIdPk);
            }
        }

        return getCdr(documentIdPk);
    }

}


text:
'use strict'

var i18next    = require('i18next'),
	debug      = require('debug')('metalsmith-i18next'),
	helpers    = require('./helpers'),
	localise   = require('./localise')

/**

 Forks multiple versions of the website (one for each locale).

 @param {Object} options
 @param {String|String[]} pattern      - A list of patterns to match files against.
 @param {String|String[]} namespaces   - A list of i18next namespaces to load.
 @param {String}          nsPath       - String to pass i18next as the resGetPath parameter.
 @param {String}          path         - String to expand the localized path to. Defaults to ':locale/:path'.

      Given the original path /folder/file.html and an 'en' locale, the
      following variables are available for substitution:

        :file     => /folder/file.html
        :ext      => .html
        :base     => file.html
        :dir      => /folder
        :name     => file
        :locale   => en

 Frontmatters can define the following properties:

	i18nNamespace           i18next namespace to lookup for the key.
 	i18nPrefix				tt function will be the same as t but with key prefix to reduces noise in the code.

 Templates and layouts have access to the following helper functions:

   t(key, options) 			i18next.t function with a preset locale that can be overriden in the options.
   tt(key, options)         i18next.t function with a preset locale and key prefix (see i18nPrefix above).
   tpath(path) 				Prefixes an absolute path with the /:locale. Relative paths are unchanged.

*/

module.exports = function(options) {

	// ------------------------------------------------------------------------
	// Set default values on the options
	// ------------------------------------------------------------------------

	options = Object.assign({
		locales:     [],
		pattern:    '**/*',
		path:       ':locale/:file',
		namespaces: ['translation'],
		nsPath:     './locales/__lng__/__ns__.json',
		resGetPath: '/locales/__lng__/__ns__.json',
		helpers:    'scripts/i18n-helpers.js',
		engine:     'hamlc', // also accepts 'handlebars'
    fallbackLng: false
	}, options || {})

	debug('Options are %j', options)

	// ------------------------------------------------------------------------
	// Do some minimal validation on the options
	// ------------------------------------------------------------------------

	var locales    = options.locales,
		pattern    = options.pattern,
		pathpat    = options.path,
		namespaces = options.namespaces,
		resGetPath = options.nsPath,
		engine     = options.engine,
    fallbackLng = options.fallbackLng

	if (typeof locales != 'string' && !Array.isArray(locales))
		throw new TypeError('metalsmith-i18next locales option should be a string or an array of strings')

	if (typeof pattern !== 'string' && !Array.isArray(pattern))
		throw new TypeError('metalsmith-i18next pattern option should be a string or an array of strings')

	if (typeof pathpat !== 'string')
		throw new TypeError('metalsmith-i18next path option should be a string')

	if (typeof namespaces !== 'string' && !Array.isArray(namespaces))
		throw new TypeError('metalsmith-i18next namespaces option should be a string or an array of strings')

	if (typeof resGetPath !== 'string')
		throw new TypeError('metalsmith-i18next resGetPath option should be a string')

	if (typeof engine !== 'string')
		throw new TypeError('metalsmith-i18next engine option should be a string')

	if (typeof fallbackLng !== 'string' && typeof fallbackLng !== 'boolean')
		throw new TypeError('metalsmith-i18next fallbackLng option should be a string')

	if (locales.indexOf(fallbackLng) === -1 && typeof fallbackLng !== 'boolean')
		throw new TypeError('metalsmith-i18next fallbackLng option must be included in locales')

	if (!Array.isArray(locales))
		locales = [locales]

	if (locales.length === 0)
		throw new Error('metalsmith-i18next locales options thould contain at least one locale')

	if (!Array.isArray(namespaces))
		namespaces = [namespaces]

	if (!namespaces.length)
		throw new Error('metalsmith-i18next namespaces option should be a string or an array of strings')

	// ------------------------------------------------------------------------
	// Setup i18next
	// ------------------------------------------------------------------------

	var serverConfig = {
		lng: locales[0],
		resGetPath,
		ns: {namespaces, defaultNs:namespaces[0]},
		preload: locales,
		getAsync: false,
		fallbackLng: fallbackLng
		// debug: true
	}

	i18next.init(serverConfig)

	return localise(debug, i18next, options)
}


text:
package com.ultra.imageloader;

/**
 * 图片保存监听器
 * Created by Administrator on 2017/7/5 0005.
 */
public interface ImageSaveListener {

    void onSaveSuccess();

    void onSaveFail();
}


text:
package com.example.dthesiya.lab1;

import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import com.example.dthesiya.lab1.R;

public class MainActivity extends AppCompatActivity {

    private Button reset, next;
    private ViewHoldr vh;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        vh = (ViewHoldr) findViewById(R.id.gameboard);
        vh.setGridX(getResources().getInteger(R.integer.grid_x));
        vh.setGridY(getBaseContext().getResources().getInteger(R.integer.grid_y));
        reset = (Button) findViewById(R.id.reset);
        next = (Button) findViewById(R.id.next);
        final TextView tv = (TextView) findViewById(R.id.label);
        tv.setText("" + getResources().getText(R.string.seekbar_value) + 12);
        SeekBar seekbar = (SeekBar) findViewById(R.id.seekbar);

        seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            int progressValue = 12;
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(progress < 2){
                    progressValue = 2;
                    seekBar.setProgress(2);
                }else{
                    progressValue = progress;
                }
                vh.setGridX(progressValue);
                vh.setGridY(progressValue);
                tv.setText("" + getResources().getText(R.string.seekbar_value) + progressValue);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                vh.setGridX(progressValue);
                vh.setGridY(progressValue);
                tv.setText("" + getResources().getText(R.string.seekbar_value) + progressValue);
            }
        });
        reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(MainActivity.this)
                        .setMessage("Do you really want to reset?")
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int whichButton) {
                                vh.resetBoard();
                            }})
                        .setNegativeButton(android.R.string.no, null).show();
            }
        });

        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                vh.generateNextGen();
            }
        });
    }
}


text:
package com.objectiva.englishmagnet.persistence.collectionOperate;

import java.util.ArrayList;
import java.util.List;
import com.objectiva.englishmagnet.general.General;
import com.objectiva.englishmagnet.persistence.collectionInfro.*;

public class CollectionSentence {

	public void saveCollection(int save_user_id, int save_move_id,
			String save_startTime, String save_word) {
		CollectionDAO cDAO = new CollectionDAO();
		Collection c = new Collection(save_user_id, save_move_id,
				save_startTime, save_word);
		cDAO.save(c);

		Wordbook wbWordbook = new Wordbook();
		wbWordbook.checkWord(save_user_id, save_word);

	}

	public void cancelCollection(int cancel_user_id, int cancel_move_id,
			String cancel_startTime, String cancel_word) {
		CollectionDAO cDAO = new CollectionDAO();
		Collection a = null;

		List<Collection> collection = cDAO.findByUserId(cancel_user_id);
		for (int i = 0; i < collection.size(); i++) {
			if ((collection.get(i).getMoveId() == cancel_move_id)
					&& (collection.get(i).getStart().equals(cancel_startTime))) {
				a = collection.get(i);
				cDAO.delete(a);
			}
		}

	}

	public void collectSen() {
		int userID = Integer.getInteger(General.USERID);
	}

	public String checkCollection(int movie_id, String start, String word) {

		String uid = General.getUserId();
		int user_id = Integer.parseInt(uid);
		try {
			CollectionDAO cdao = new CollectionDAO();
			Collection c = new Collection();

			@SuppressWarnings("rawtypes")
			List clist = new ArrayList();
			clist = cdao.findByMoveId(movie_id);

			if (clist.size() > 0) {

				for (int i = 0; i < clist.size(); i++) {

					c = (Collection) clist.get(i);
					Integer movieId = (Integer) movie_id;

					if ((c.getMoveId().equals(movieId))
							&& (c.getStart().matches(start))) {

					} else {
						if (i == clist.size() - 1) {
							saveCollection(user_id, movie_id, start, word);
						}
					}
				}
			} else {
				saveCollection(user_id, movie_id, start, word);
			}
		} catch (RuntimeException re) {
			re.printStackTrace();
		}
		return word;
	}

}


text:
package com.java110.common.bmo.sysDocument;
import com.java110.po.sysDocument.SysDocumentPo;
import org.springframework.http.ResponseEntity;

public interface IDeleteSysDocumentBMO {

    /**
     * 修改系统文档
     * add by wuxw
     * @param sysDocumentPo
     * @return
     */
    ResponseEntity<String> delete(SysDocumentPo sysDocumentPo);

}


text:
/**
 * An ELAD FMD-Duo radio.
 *  This object implements the standard API shared by all instruments
 * objects
 *
 * @author Edouard Lafargue, ed@lafargue.name
 */

define(function(require) {
    'use strict';

    return  function() {
        // Helper function: get driver capabilites.
        // returns a simple array of capabilities
        this.getCaps = function() {
            return ['LiveDisplay', 'NumDisplay', 'DiagDisplay', 'WizkersSettings'];
        };

        // Return the type of data reading that this instrument generates. Can be used
        // by output plugins to accept data from this instrument or not.
        this.getDataType = function() {
                    return [ 'transceiver' ];
        }

        // This is a Backbone view
        this.getLiveDisplay = function(arg, callback) {
            require(['app/instruments/fdm_duo/display_live'], function(view) {
                callback(new view(arg));
            });
        };

        // This is a Backbone view
        this.getNumDisplay = function(arg, callback) {
            require(['app/instruments/fdm_duo/display_numeric'], function(view) {
                callback( new view(arg));
            });
        };

        // A diagnostics/device setup screen
        this.getDiagDisplay = function(arg, callback) {
            require(['app/instruments/fdm_duo/display_diag'], function(view) {
                callback(new view(arg));
            });
        };

        // This is the front-end driver
        this.getDriver = function(callback) {
             require(['app/instruments/fdm_duo/driver_frontend'], function(d) {
                callback(new d());
             });
        };

        // This is a browser implementation of the backend driver, when we
        // run the app fully in-browser on as a Cordova native app.
        this.getBackendDriver = function(arg, callback) {
            require(['app/instruments/fdm_duo/driver_backend'], function(driver) {
                callback(new driver(arg));
            });
        };

        // The screen for the "Settings" top level menu. This covers settings
        // for the Wizkers app, not the instrument itself (those are done on the DiagDisplay
        // screen).
        this.getWizkersSettings = function(arg, callback) {
            require(['app/instruments/fdm_duo/settings_wizkers'], function(view) {
                callback(new view(arg));
            });
        };

        // Return a Backbone view which is a mini graph
        this.getMiniLogview = function(arg) {
            return null;
        };

        // Render a log (or list of logs) for the device.
        this.getLogView = function(arg) {
            return null;
        }
    };

});


text:
using DromundKaasII.Engine;

namespace DromundKaasII.Interfaces
{
    /// <summary>
    /// Exposes the options of the engine.
    /// </summary>
    public interface IEngineOptions
    {
        /// <summary>
        /// The speed at which the engine state updates.
        /// </summary>
        GameSpeedOptions GameSpeed { get; set; }

        /// <summary>
        /// The difficulty of the gameplay.
        /// </summary>
        GameDifficultyOptions GameDifficulty { get; set; }
    }
}


text:
var mixin_         = require('typedef').mixin;
var Eventable      = require('./Eventable.js');

module.exports = ChangeNotifier;
mixin_(ChangeNotifier, Eventable);

/**
 * An object that has functions that can be used to inform a listener it has
 * changed.
 * @mixin
 * @extends Eventable
 */
function ChangeNotifier()
{

}

/**
 * Fired when this object has changed.
 * @event
 */
ChangeNotifier.CHANGE = 'change';

/**
 * A specific property has changed on this object.
 * @param {String} prop Name of the property that has changed.
 * @event
 */
ChangeNotifier.PROPERTY_CHANGE = function(prop)
{
  return ChangeNotifier.CHANGE + ':' + prop;
};

/**
 * Fire a property change notification. Always use this function to manually
 * trigger a property change.
 * @param {String} prop Name of the property that changed.
 */
ChangeNotifier.prototype.triggerPropertyChange = function(prop)
{
  this.trigger(ChangeNotifier.PROPERTY_CHANGE(prop));
  this.trigger(ChangeNotifier.CHANGE);
};

/**
 * Listen for when a property on this object changes. All callbacks are bound
 * to this object.
 * @param {String} prop Property name we want to listen for changes on.
 * @param {function()} f Handler for when the property changes.
 */
ChangeNotifier.prototype.onPropertyChange = function(prop, f)
{
  if (f)
    this.on(ChangeNotifier.PROPERTY_CHANGE(prop), f);
  else
    for (var key in prop)
      this.on(ChangeNotifier.PROPERTY_CHANGE(key), prop[key]);
};


text:
{
  babelHelpers.inherits(Test, _Foo);

  function Test() {
    var _this;

    babelHelpers.classCallCheck(this, Test);
    _this = babelHelpers.possibleConstructorReturn(
      this,
      (Test.__proto__ || Object.getPrototypeOf(Test)).call(this)
    );
    babelHelpers
      .get(
        Test.prototype.__proto__ || Object.getPrototypeOf(Test.prototype),
        "test",
        _this
      )
      .whatever();
    babelHelpers
      .get(
        Test.prototype.__proto__ || Object.getPrototypeOf(Test.prototype),
        "test",
        _this
      )
      .call(_this);
    return _this;
  }

  babelHelpers.createClass(Test, null, [
    {
      key: "test",
      value: function test() {
        return babelHelpers
          .get(Test.__proto__ || Object.getPrototypeOf(Test), "wow", this)
          .call(this);
      }
    }
  ]);
  return Test;
}