text:
var Q = require('q'),
    cordova = require('../cordova');

describe('callback wrapper', function() {
    var calls = ['prepare', 'build', 'create', 'emulate', 'plugin', 'platform', 'compile', 'run'];
    for (var i = 0; i < calls.length; i++) {
        var call = calls[i];

        describe('`' + call + '`', function() {
            var raw;
            beforeEach(function() {
                raw = spyOn(cordova.raw, call);
            });

            it('should work with no callback and success', function() {
                raw.andReturn(Q());
                cordova[call]();
                expect(raw).toHaveBeenCalled();
            });

            it('should call the callback on success', function(done) {
                raw.andReturn(Q());
                cordova[call](function(err) {
                    expect(err).toBeUndefined();
                    done();
                });
            });

            it('should call the callback with the error on failure', function(done) {
                raw.andReturn(Q.reject(new Error('junk')));
                cordova[call](function(err) {
                    expect(err).toEqual(new Error('junk'));
                    done();
                });
            });
        });
    }
});


text:
import json
import nflgame.schedule
import io
import os
import sys
import re
import ols
from numpy.random import randn
import numpy

class defensive_stats:
	def __init__(self):
		self.fields = ["tkl","sk","ast","int","ffum","rushing_yds","rushing_tds","passing_yds","passing_tds","kicking_fgm","kickret_tds","puntret_tds"]
		self.opposing_fields = ["rushing_tds","passing_tds","kicking_fgm","kickret_tds","puntret_tds"]
		self.variables = ["tkl","sk","ast","int","ffum","rushing_yds","passing_yds"]
		self.results = {}
		self.y = []
		self.x = []
		self.totals = {}

	def process_week(self,year,week):
		games = nflgame._search_schedule(year,week=week)
		for g in games:
			eid = g["eid"]
			f = open('data/' + eid + ".json","r")
			j = json.loads(f.read())
			f.close()
			team_array = ["home","away"]
			for idx,t in enumerate(team_array):
				team  = j[eid][t]["abbr"]
				team_string = team + "_" + str(year) + "_" + str(week)
				if team_string not in self.results:
					self.results[team_string] = {}
					for f in self.fields:
						self.results[team_string][f] = 0
				defense = j[eid][t]["stats"]["defense"]
				for p in defense.keys():
					for stat in defense[p].keys():
						if stat in self.fields:
							self.results[team_string][stat] += defense[p][stat]
				opposing = j[eid][team_array[idx-1]]["stats"]
				for cat in ["passing","rushing","kicking","kickret","puntret"]:
					try:
						for p in opposing[cat].keys():
							for stat in opposing[cat][p].keys():
								if cat +  "_" + stat in self.fields:
									self.results[team_string][cat + "_" + stat] += opposing[cat][p][stat]
					except KeyError as e:
						pass

	def create_arrays(self):
		for t in self.results.keys():
			temp = []
			for v in self.variables:
				temp.append(self.results[t][v])
			self.x.append(temp)
			self.y.append(6*self.results[t]["passing_tds"] + 6*self.results[t]["rushing_tds"] + 6*self.results[t]["kickret_tds"] + 6*self.results[t]["puntret_tds"] + 3*self.results[t]["kicking_fgm"])
		self.y = numpy.array(self.y)
		self.x = numpy.array(self.x)
		print self.x
		print self.y

	def run_results(self):
		mymodel = ols.ols(self.y,self.x,'Points allowed',self.variables)
		mymodel.summary()
		self.variables.append("const")
		correlations =  dict(zip(mymodel.x_varnm,mymodel.b))
		for t in self.results.keys():
			self.results[t]["const"] = 1
			total = 0
			for stat in self.variables:
				total += (self.results[t][stat]*correlations[stat])
			team = t.split("_")[0]
			if team not in self.totals:
				self.totals[team] = []
			self.totals[team].append(total)
			del self.results[t]["const"]
		self.variables.remove("const")

	def return_results(self):
		print self.totals
		output = {}
		for team in self.totals.keys():
			print team
			print sum(self.totals[team])/len(self.totals[team])
			output[team] = sum(self.totals[team])/len(self.totals[team])
		output_teams = sorted(output,key=max)
		for k in output_teams:
			print k + ":" + str(output[k])

d = defensive_stats()
years = ['2009','2010','2011']
weeks = range(1,18)
for y in years:
	for w in weeks:
		d.process_week(int(y),w)
d.create_arrays()
d.run_results()
d.return_results()

redpajama_set_name: RedPajamaGithub


text:
#ifndef _CONN_BLE_GAP_SEC_KEYS_H
#define _CONN_BLE_GAP_SEC_KEYS_H

/**
 * @addtogroup ser_codecs Serialization codecs
 * @ingroup ble_sdk_lib_serialization
 */

/**
 * @addtogroup ser_conn_s130_codecs Connectivity S132 codecs
 * @ingroup ser_codecs
 */

/**@file
 *
 * @defgroup conn_ble_gap_sec_keys GAP Functions for managing memory for security keys on connectivity device
 * @{
 * @ingroup  ser_conn_s130_codecs
 *
 * @brief    GAP Connectivity auxiliary functions for providing static memory required by the SoftDevice. This memory is used to store GAP security keys.
 */

#include "ble_gap.h"
#include <stdint.h>

#ifdef __cplusplus
extern "C" {
#endif

#ifndef SER_MAX_CONNECTIONS
#define SER_MAX_CONNECTIONS 2
#endif

/**@brief GAP connection - keyset mapping structure.
 *
 * @note  This structure is used to map keysets to connection instances, and will be stored in a static table.
 */
typedef struct
{
  uint16_t                conn_handle;     /**< Connection handle. */
  uint8_t                 conn_active;     /**< Indication that keys for this connection are used by the SoftDevice. 0: keys used; 1: keys not used. */
  ble_gap_sec_keyset_t    keyset;          /**< Keyset structure, see @ref ble_gap_sec_keyset_t. */
  ble_gap_enc_key_t       enc_key_own;     /**< Own Encryption Key, see @ref ble_gap_enc_key_t. */
  ble_gap_id_key_t        id_key_own;      /**< Own Identity Key, see @ref ble_gap_id_key_t. */
  ble_gap_sign_info_t     sign_key_own;    /**< Own Signing Information, see @ref ble_gap_sign_info_t. */
  ble_gap_lesc_p256_pk_t  pk_own;          /**< Own Public key, see @ref ble_gap_lesc_p256_pk_t. */
  ble_gap_enc_key_t       enc_key_peer;    /**< Peer Encryption Key, see @ref ble_gap_enc_key_t. */
  ble_gap_id_key_t        id_key_peer;     /**< Peer Identity Key, see @ref ble_gap_id_key_t. */
  ble_gap_sign_info_t     sign_key_peer;   /**< Peer Signing Information, see @ref ble_gap_sign_info_t. */
  ble_gap_lesc_p256_pk_t  pk_peer;         /**< Peer Public key, see @ref ble_gap_lesc_p256_pk_t. */
} ser_ble_gap_conn_keyset_t;

/**@brief Allocates instance in m_conn_keys_table[] for storage of encryption keys.
 *
 * @param[out]    p_index             Pointer to the index of allocated instance.
 *
 * @retval NRF_SUCCESS                Success.
 * @retval NRF_ERROR_NO_MEM           No free instance available.
 */
uint32_t conn_ble_gap_sec_context_create(uint32_t *p_index);

/**@brief Releases the instance identified by a connection handle.
 *
 * @param[in]     conn_handle         conn_handle
 *
 * @retval NRF_SUCCESS                Context released.
 * @retval NRF_ERROR_NOT_FOUND        Instance with conn_handle not found.
 */
uint32_t conn_ble_gap_sec_context_destroy(uint16_t conn_handle);

/**@brief Finds index of the instance identified by a connection handle in m_conn_keys_table[].
 *
 * @param[in]     conn_handle         conn_handle
 *
 * @param[out]    p_index             Pointer to the index of entry in the context table corresponding to the given conn_handle.
 *
 * @retval NRF_SUCCESS                Context table entry found.
 * @retval NRF_ERROR_NOT_FOUND        Instance with the conn_handle not found.
 */
uint32_t conn_ble_gap_sec_context_find(uint16_t conn_handle, uint32_t *p_index);
/** @} */

#ifdef __cplusplus
}
#endif

#endif //_CONN_BLE_GAP_SEC_KEYS_H


text:
import '../../configuration/whitelisted.js';
import '../../lib/platform/loglevel-web.js';
import {SlotObserver} from '../../lib/xen-renderer.js';

const renderer = new SlotObserver(document.body);

window.renderer = renderer;
window.render = content => renderer.render(content);


text:
package client

const (
	ADD_REMOVE_SERVICE_LINK_INPUT_TYPE = "addRemoveServiceLinkInput"
)

type AddRemoveServiceLinkInput struct {
	Resource

    ServiceId string `json:"serviceId,omitempty"`

}

type AddRemoveServiceLinkInputCollection struct {
	Collection
	Data []AddRemoveServiceLinkInput `json:"data,omitempty"`
}

type AddRemoveServiceLinkInputClient struct {
	rancherClient *RancherClient
}

type AddRemoveServiceLinkInputOperations interface {
	List(opts *ListOpts) (*AddRemoveServiceLinkInputCollection, error)
	Create(opts *AddRemoveServiceLinkInput) (*AddRemoveServiceLinkInput, error)
	Update(existing *AddRemoveServiceLinkInput, updates interface{}) (*AddRemoveServiceLinkInput, error)
	ById(id string) (*AddRemoveServiceLinkInput, error)
	Delete(container *AddRemoveServiceLinkInput) error
}

func newAddRemoveServiceLinkInputClient(rancherClient *RancherClient) *AddRemoveServiceLinkInputClient {
	return &AddRemoveServiceLinkInputClient{
		rancherClient: rancherClient,
	}
}

func (c *AddRemoveServiceLinkInputClient) Create(container *AddRemoveServiceLinkInput) (*AddRemoveServiceLinkInput, error) {
	resp := &AddRemoveServiceLinkInput{}
	err := c.rancherClient.doCreate(ADD_REMOVE_SERVICE_LINK_INPUT_TYPE, container, resp)
	return resp, err
}

func (c *AddRemoveServiceLinkInputClient) Update(existing *AddRemoveServiceLinkInput, updates interface{}) (*AddRemoveServiceLinkInput, error) {
	resp := &AddRemoveServiceLinkInput{}
	err := c.rancherClient.doUpdate(ADD_REMOVE_SERVICE_LINK_INPUT_TYPE, &existing.Resource, updates, resp)
	return resp, err
}

func (c *AddRemoveServiceLinkInputClient) List(opts *ListOpts) (*AddRemoveServiceLinkInputCollection, error) {
	resp := &AddRemoveServiceLinkInputCollection{}
	err := c.rancherClient.doList(ADD_REMOVE_SERVICE_LINK_INPUT_TYPE, opts, resp)
	return resp, err
}

func (c *AddRemoveServiceLinkInputClient) ById(id string) (*AddRemoveServiceLinkInput, error) {
	resp := &AddRemoveServiceLinkInput{}
	err := c.rancherClient.doById(ADD_REMOVE_SERVICE_LINK_INPUT_TYPE, id, resp)
	return resp, err
}

func (c *AddRemoveServiceLinkInputClient) Delete(container *AddRemoveServiceLinkInput) error {
	return c.rancherClient.doResourceDelete(ADD_REMOVE_SERVICE_LINK_INPUT_TYPE, &container.Resource)
}


text:
package org.elasticsearch.action.admin.indices.shards;

import com.carrotsearch.hppc.cursors.IntObjectCursor;
import com.carrotsearch.hppc.cursors.ObjectObjectCursor;

import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.Version;
import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.action.ShardOperationFailedException;
import org.elasticsearch.action.support.DefaultShardOperationFailedException;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.collect.ImmutableOpenIntMap;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Streamable;
import org.elasticsearch.common.xcontent.ToXContentFragment;
import org.elasticsearch.common.xcontent.XContentBuilder;

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

import static org.elasticsearch.action.admin.indices.shards.IndicesShardStoresResponse.StoreStatus.readStoreStatus;

/**
 * Response for {@link IndicesShardStoresAction}
 *
 * Consists of {@link StoreStatus}s for requested indices grouped by
 * indices and shard ids and a list of encountered node {@link Failure}s
 */
public class IndicesShardStoresResponse extends ActionResponse implements ToXContentFragment {

    /**
     * Shard store information from a node
     */
    public static class StoreStatus implements Streamable, ToXContentFragment, Comparable<StoreStatus> {
        private DiscoveryNode node;
        private String allocationId;
        private Exception storeException;
        private AllocationStatus allocationStatus;

        /**
         * The status of the shard store with respect to the cluster
         */
        public enum AllocationStatus {

            /**
             * Allocated as primary
             */
            PRIMARY((byte) 0),

            /**
             * Allocated as a replica
             */
            REPLICA((byte) 1),

            /**
             * Not allocated
             */
            UNUSED((byte) 2);

            private final byte id;

            AllocationStatus(byte id) {
                this.id = id;
            }

            private static AllocationStatus fromId(byte id) {
                switch (id) {
                    case 0: return PRIMARY;
                    case 1: return REPLICA;
                    case 2: return UNUSED;
                    default: throw new IllegalArgumentException("unknown id for allocation status [" + id + "]");
                }
            }

            public String value() {
                switch (id) {
                    case 0: return "primary";
                    case 1: return "replica";
                    case 2: return "unused";
                    default: throw new IllegalArgumentException("unknown id for allocation status [" + id + "]");
                }
            }

            private static AllocationStatus readFrom(StreamInput in) throws IOException {
                return fromId(in.readByte());
            }

            private void writeTo(StreamOutput out) throws IOException {
                out.writeByte(id);
            }
        }

        private StoreStatus() {
        }

        public StoreStatus(DiscoveryNode node, String allocationId, AllocationStatus allocationStatus, Exception storeException) {
            this.node = node;
            this.allocationId = allocationId;
            this.allocationStatus = allocationStatus;
            this.storeException = storeException;
        }

        /**
         * Node the store belongs to
         */
        public DiscoveryNode getNode() {
            return node;
        }

        /**
         * AllocationStatus id of the store, used to select the store that will be
         * used as a primary.
         */
        public String getAllocationId() {
            return allocationId;
        }

        /**
         * Exception while trying to open the
         * shard index or from when the shard failed
         */
        public Exception getStoreException() {
            return storeException;
        }

        /**
         * The allocationStatus status of the store.
         * {@link AllocationStatus#PRIMARY} indicates a primary shard copy
         * {@link AllocationStatus#REPLICA} indicates a replica shard copy
         * {@link AllocationStatus#UNUSED} indicates an unused shard copy
         */
        public AllocationStatus getAllocationStatus() {
            return allocationStatus;
        }

        public static StoreStatus readStoreStatus(StreamInput in) throws IOException {
            StoreStatus storeStatus = new StoreStatus();
            storeStatus.readFrom(in);
            return storeStatus;
        }

        @Override
        public void readFrom(StreamInput in) throws IOException {
            node = new DiscoveryNode(in);
            if (in.getVersion().before(Version.V_6_0_0_alpha1)) {
                // legacy version
                in.readLong();
            }
            allocationId = in.readOptionalString();
            allocationStatus = AllocationStatus.readFrom(in);
            if (in.readBoolean()) {
                storeException = in.readException();
            }
        }

        @Override
        public void writeTo(StreamOutput out) throws IOException {
            node.writeTo(out);
            if (out.getVersion().before(Version.V_6_0_0_alpha1)) {
                // legacy version
                out.writeLong(-1L);
            }
            out.writeOptionalString(allocationId);
            allocationStatus.writeTo(out);
            if (storeException != null) {
                out.writeBoolean(true);
                out.writeException(storeException);
            } else {
                out.writeBoolean(false);
            }
        }

        @Override
        public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
            node.toXContent(builder, params);
            if (allocationId != null) {
                builder.field(Fields.ALLOCATION_ID, allocationId);
            }
            builder.field(Fields.ALLOCATED, allocationStatus.value());
            if (storeException != null) {
                builder.startObject(Fields.STORE_EXCEPTION);
                ElasticsearchException.generateThrowableXContent(builder, params, storeException);
                builder.endObject();
            }
            return builder;
        }

        @Override
        public int compareTo(StoreStatus other) {
            if (storeException != null && other.storeException == null) {
                return 1;
            } else if (other.storeException != null && storeException == null) {
                return -1;
            }
            if (allocationId != null && other.allocationId == null) {
                return -1;
            } else if (allocationId == null && other.allocationId != null) {
                return 1;
            } else if (allocationId == null && other.allocationId == null) {
                return Integer.compare(allocationStatus.id, other.allocationStatus.id);
            } else {
                int compare = Integer.compare(allocationStatus.id, other.allocationStatus.id);
                if (compare == 0) {
                    return allocationId.compareTo(other.allocationId);
                }
                return compare;
            }
        }
    }

    /**
     * Single node failure while retrieving shard store information
     */
    public static class Failure extends DefaultShardOperationFailedException {
        private String nodeId;

        public Failure(String nodeId, String index, int shardId, Throwable reason) {
            super(index, shardId, reason);
            this.nodeId = nodeId;
        }

        private Failure() {
        }

        public String nodeId() {
            return nodeId;
        }

        public static Failure readFailure(StreamInput in) throws IOException {
            Failure failure = new Failure();
            failure.readFrom(in);
            return failure;
        }

        @Override
        public void readFrom(StreamInput in) throws IOException {
            nodeId = in.readString();
            super.readFrom(in);
        }

        @Override
        public void writeTo(StreamOutput out) throws IOException {
            out.writeString(nodeId);
            super.writeTo(out);
        }

        @Override
        public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
            builder.field("node", nodeId());
            super.toXContent(builder, params);
            return builder;
        }
    }

    private ImmutableOpenMap<String, ImmutableOpenIntMap<List<StoreStatus>>> storeStatuses;
    private List<Failure> failures;

    public IndicesShardStoresResponse(ImmutableOpenMap<String, ImmutableOpenIntMap<List<StoreStatus>>> storeStatuses, List<Failure> failures) {
        this.storeStatuses = storeStatuses;
        this.failures = failures;
    }

    IndicesShardStoresResponse() {
        this(ImmutableOpenMap.<String, ImmutableOpenIntMap<List<StoreStatus>>>of(), Collections.<Failure>emptyList());
    }

    /**
     * Returns {@link StoreStatus}s
     * grouped by their index names and shard ids.
     */
    public ImmutableOpenMap<String, ImmutableOpenIntMap<List<StoreStatus>>> getStoreStatuses() {
        return storeStatuses;
    }

    /**
     * Returns node {@link Failure}s encountered
     * while executing the request
     */
    public List<Failure> getFailures() {
        return failures;
    }

    @Override
    public void readFrom(StreamInput in) throws IOException {
        super.readFrom(in);
        int numResponse = in.readVInt();
        ImmutableOpenMap.Builder<String, ImmutableOpenIntMap<List<StoreStatus>>> storeStatusesBuilder = ImmutableOpenMap.builder();
        for (int i = 0; i < numResponse; i++) {
            String index = in.readString();
            int indexEntries = in.readVInt();
            ImmutableOpenIntMap.Builder<List<StoreStatus>> shardEntries = ImmutableOpenIntMap.builder();
            for (int shardCount = 0; shardCount < indexEntries; shardCount++) {
                int shardID = in.readInt();
                int nodeEntries = in.readVInt();
                List<StoreStatus> storeStatuses = new ArrayList<>(nodeEntries);
                for (int nodeCount = 0; nodeCount < nodeEntries; nodeCount++) {
                    storeStatuses.add(readStoreStatus(in));
                }
                shardEntries.put(shardID, storeStatuses);
            }
            storeStatusesBuilder.put(index, shardEntries.build());
        }
        int numFailure = in.readVInt();
        List<Failure> failureBuilder = new ArrayList<>();
        for (int i = 0; i < numFailure; i++) {
            failureBuilder.add(Failure.readFailure(in));
        }
        storeStatuses = storeStatusesBuilder.build();
        failures = Collections.unmodifiableList(failureBuilder);
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        super.writeTo(out);
        out.writeVInt(storeStatuses.size());
        for (ObjectObjectCursor<String, ImmutableOpenIntMap<List<StoreStatus>>> indexShards : storeStatuses) {
            out.writeString(indexShards.key);
            out.writeVInt(indexShards.value.size());
            for (IntObjectCursor<List<StoreStatus>> shardStatusesEntry : indexShards.value) {
                out.writeInt(shardStatusesEntry.key);
                out.writeVInt(shardStatusesEntry.value.size());
                for (StoreStatus storeStatus : shardStatusesEntry.value) {
                    storeStatus.writeTo(out);
                }
            }
        }
        out.writeVInt(failures.size());
        for (ShardOperationFailedException failure : failures) {
            failure.writeTo(out);
        }
    }

    @Override
    public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
        if (failures.size() > 0) {
            builder.startArray(Fields.FAILURES);
            for (ShardOperationFailedException failure : failures) {
                builder.startObject();
                failure.toXContent(builder, params);
                builder.endObject();
            }
            builder.endArray();
        }

        builder.startObject(Fields.INDICES);
        for (ObjectObjectCursor<String, ImmutableOpenIntMap<List<StoreStatus>>> indexShards : storeStatuses) {
            builder.startObject(indexShards.key);

            builder.startObject(Fields.SHARDS);
            for (IntObjectCursor<List<StoreStatus>> shardStatusesEntry : indexShards.value) {
                builder.startObject(String.valueOf(shardStatusesEntry.key));
                builder.startArray(Fields.STORES);
                for (StoreStatus storeStatus : shardStatusesEntry.value) {
                    builder.startObject();
                    storeStatus.toXContent(builder, params);
                    builder.endObject();
                }
                builder.endArray();

                builder.endObject();
            }
            builder.endObject();

            builder.endObject();
        }
        builder.endObject();
        return builder;
    }

    static final class Fields {
        static final String INDICES = "indices";
        static final String SHARDS = "shards";
        static final String FAILURES = "failures";
        static final String STORES = "stores";
        // StoreStatus fields
        static final String ALLOCATION_ID = "allocation_id";
        static final String STORE_EXCEPTION = "store_exception";
        static final String ALLOCATED = "allocation";
    }
}


text:
# -*- coding: utf-8 -*-
"""
    flask.testsuite.blueprints
    ~~~~~~~~~~~~~~~~~~~~~~~~~~

    Blueprints (and currently modules)

    :copyright: (c) 2011 by Armin Ronacher.
    :license: BSD, see LICENSE for more details.
"""

from __future__ import with_statement

import flask
import unittest
import warnings
from flask.testsuite import FlaskTestCase, emits_module_deprecation_warning
from werkzeug.exceptions import NotFound
from werkzeug.http import parse_cache_control_header
from jinja2 import TemplateNotFound

# import moduleapp here because it uses deprecated features and we don't
# want to see the warnings
warnings.simplefilter('ignore', DeprecationWarning)
from moduleapp import app as moduleapp
warnings.simplefilter('default', DeprecationWarning)

class ModuleTestCase(FlaskTestCase):

    @emits_module_deprecation_warning
    def test_basic_module(self):
        app = flask.Flask(__name__)
        admin = flask.Module(__name__, 'admin', url_prefix='/admin')
        @admin.route('/')
        def admin_index():
            return 'admin index'
        @admin.route('/login')
        def admin_login():
            return 'admin login'
        @admin.route('/logout')
        def admin_logout():
            return 'admin logout'
        @app.route('/')
        def index():
            return 'the index'
        app.register_module(admin)
        c = app.test_client()
        self.assert_equal(c.get('/').data, 'the index')
        self.assert_equal(c.get('/admin/').data, 'admin index')
        self.assert_equal(c.get('/admin/login').data, 'admin login')
        self.assert_equal(c.get('/admin/logout').data, 'admin logout')

    @emits_module_deprecation_warning
    def test_default_endpoint_name(self):
        app = flask.Flask(__name__)
        mod = flask.Module(__name__, 'frontend')
        def index():
            return 'Awesome'
        mod.add_url_rule('/', view_func=index)
        app.register_module(mod)
        rv = app.test_client().get('/')
        self.assert_equal(rv.data, 'Awesome')
        with app.test_request_context():
            self.assert_equal(flask.url_for('frontend.index'), '/')

    @emits_module_deprecation_warning
    def test_request_processing(self):
        catched = []
        app = flask.Flask(__name__)
        admin = flask.Module(__name__, 'admin', url_prefix='/admin')
        @admin.before_request
        def before_admin_request():
            catched.append('before-admin')
        @admin.after_request
        def after_admin_request(response):
            catched.append('after-admin')
            return response
        @admin.route('/')
        def admin_index():
            return 'the admin'
        @app.before_request
        def before_request():
            catched.append('before-app')
        @app.after_request
        def after_request(response):
            catched.append('after-app')
            return response
        @app.route('/')
        def index():
            return 'the index'
        app.register_module(admin)
        c = app.test_client()

        self.assert_equal(c.get('/').data, 'the index')
        self.assert_equal(catched, ['before-app', 'after-app'])
        del catched[:]

        self.assert_equal(c.get('/admin/').data, 'the admin')
        self.assert_equal(catched, ['before-app', 'before-admin',
                           'after-admin', 'after-app'])

    @emits_module_deprecation_warning
    def test_context_processors(self):
        app = flask.Flask(__name__)
        admin = flask.Module(__name__, 'admin', url_prefix='/admin')
        @app.context_processor
        def inject_all_regualr():
            return {'a': 1}
        @admin.context_processor
        def inject_admin():
            return {'b': 2}
        @admin.app_context_processor
        def inject_all_module():
            return {'c': 3}
        @app.route('/')
        def index():
            return flask.render_template_string('{{ a }}{{ b }}{{ c }}')
        @admin.route('/')
        def admin_index():
            return flask.render_template_string('{{ a }}{{ b }}{{ c }}')
        app.register_module(admin)
        c = app.test_client()
        self.assert_equal(c.get('/').data, '13')
        self.assert_equal(c.get('/admin/').data, '123')

    @emits_module_deprecation_warning
    def test_late_binding(self):
        app = flask.Flask(__name__)
        admin = flask.Module(__name__, 'admin')
        @admin.route('/')
        def index():
            return '42'
        app.register_module(admin, url_prefix='/admin')
        self.assert_equal(app.test_client().get('/admin/').data, '42')

    @emits_module_deprecation_warning
    def test_error_handling(self):
        app = flask.Flask(__name__)
        admin = flask.Module(__name__, 'admin')
        @admin.app_errorhandler(404)
        def not_found(e):
            return 'not found', 404
        @admin.app_errorhandler(500)
        def internal_server_error(e):
            return 'internal server error', 500
        @admin.route('/')
        def index():
            flask.abort(404)
        @admin.route('/error')
        def error():
            1 // 0
        app.register_module(admin)
        c = app.test_client()
        rv = c.get('/')
        self.assert_equal(rv.status_code, 404)
        self.assert_equal(rv.data, 'not found')
        rv = c.get('/error')
        self.assert_equal(rv.status_code, 500)
        self.assert_equal('internal server error', rv.data)

    def test_templates_and_static(self):
        app = moduleapp
        app.testing = True
        c = app.test_client()

        rv = c.get('/')
        self.assert_equal(rv.data, 'Hello from the Frontend')
        rv = c.get('/admin/')
        self.assert_equal(rv.data, 'Hello from the Admin')
        rv = c.get('/admin/index2')
        self.assert_equal(rv.data, 'Hello from the Admin')
        rv = c.get('/admin/static/test.txt')
        self.assert_equal(rv.data.strip(), 'Admin File')
        rv = c.get('/admin/static/css/test.css')
        self.assert_equal(rv.data.strip(), '/* nested file */')

        with app.test_request_context():
            self.assert_equal(flask.url_for('admin.static', filename='test.txt'),
                              '/admin/static/test.txt')

        with app.test_request_context():
            try:
                flask.render_template('missing.html')
            except TemplateNotFound, e:
                self.assert_equal(e.name, 'missing.html')
            else:
                self.assert_(0, 'expected exception')

        with flask.Flask(__name__).test_request_context():
            self.assert_equal(flask.render_template('nested/nested.txt'), 'I\'m nested')

    def test_safe_access(self):
        app = moduleapp

        with app.test_request_context():
            f = app.view_functions['admin.static']

            try:
                f('/etc/passwd')
            except NotFound:
                pass
            else:
                self.assert_(0, 'expected exception')
            try:
                f('../__init__.py')
            except NotFound:
                pass
            else:
                self.assert_(0, 'expected exception')

            # testcase for a security issue that may exist on windows systems
            import os
            import ntpath
            old_path = os.path
            os.path = ntpath
            try:
                try:
                    f('..\\__init__.py')
                except NotFound:
                    pass
                else:
                    self.assert_(0, 'expected exception')
            finally:
                os.path = old_path

    @emits_module_deprecation_warning
    def test_endpoint_decorator(self):
        from werkzeug.routing import Submount, Rule
        from flask import Module

        app = flask.Flask(__name__)
        app.testing = True
        app.url_map.add(Submount('/foo', [
            Rule('/bar', endpoint='bar'),
            Rule('/', endpoint='index')
        ]))
        module = Module(__name__, __name__)

        @module.endpoint('bar')
        def bar():
            return 'bar'

        @module.endpoint('index')
        def index():
            return 'index'

        app.register_module(module)

        c = app.test_client()
        self.assert_equal(c.get('/foo/').data, 'index')
        self.assert_equal(c.get('/foo/bar').data, 'bar')

class BlueprintTestCase(FlaskTestCase):

    def test_blueprint_specific_error_handling(self):
        frontend = flask.Blueprint('frontend', __name__)
        backend = flask.Blueprint('backend', __name__)
        sideend = flask.Blueprint('sideend', __name__)

        @frontend.errorhandler(403)
        def frontend_forbidden(e):
            return 'frontend says no', 403

        @frontend.route('/frontend-no')
        def frontend_no():
            flask.abort(403)

        @backend.errorhandler(403)
        def backend_forbidden(e):
            return 'backend says no', 403

        @backend.route('/backend-no')
        def backend_no():
            flask.abort(403)

        @sideend.route('/what-is-a-sideend')
        def sideend_no():
            flask.abort(403)

        app = flask.Flask(__name__)
        app.register_blueprint(frontend)
        app.register_blueprint(backend)
        app.register_blueprint(sideend)

        @app.errorhandler(403)
        def app_forbidden(e):
            return 'application itself says no', 403

        c = app.test_client()

        self.assert_equal(c.get('/frontend-no').data, 'frontend says no')
        self.assert_equal(c.get('/backend-no').data, 'backend says no')
        self.assert_equal(c.get('/what-is-a-sideend').data, 'application itself says no')

    def test_blueprint_url_definitions(self):
        bp = flask.Blueprint('test', __name__)

        @bp.route('/foo', defaults={'baz': 42})
        def foo(bar, baz):
            return '%s/%d' % (bar, baz)

        @bp.route('/bar')
        def bar(bar):
            return unicode(bar)

        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/1', url_defaults={'bar': 23})
        app.register_blueprint(bp, url_prefix='/2', url_defaults={'bar': 19})

        c = app.test_client()
        self.assert_equal(c.get('/1/foo').data, u'23/42')
        self.assert_equal(c.get('/2/foo').data, u'19/42')
        self.assert_equal(c.get('/1/bar').data, u'23')
        self.assert_equal(c.get('/2/bar').data, u'19')

    def test_blueprint_url_processors(self):
        bp = flask.Blueprint('frontend', __name__, url_prefix='/<lang_code>')

        @bp.url_defaults
        def add_language_code(endpoint, values):
            values.setdefault('lang_code', flask.g.lang_code)

        @bp.url_value_preprocessor
        def pull_lang_code(endpoint, values):
            flask.g.lang_code = values.pop('lang_code')

        @bp.route('/')
        def index():
            return flask.url_for('.about')

        @bp.route('/about')
        def about():
            return flask.url_for('.index')

        app = flask.Flask(__name__)
        app.register_blueprint(bp)

        c = app.test_client()

        self.assert_equal(c.get('/de/').data, '/de/about')
        self.assert_equal(c.get('/de/about').data, '/de/')

    def test_templates_and_static(self):
        from blueprintapp import app
        c = app.test_client()

        rv = c.get('/')
        self.assert_equal(rv.data, 'Hello from the Frontend')
        rv = c.get('/admin/')
        self.assert_equal(rv.data, 'Hello from the Admin')
        rv = c.get('/admin/index2')
        self.assert_equal(rv.data, 'Hello from the Admin')
        rv = c.get('/admin/static/test.txt')
        self.assert_equal(rv.data.strip(), 'Admin File')
        rv = c.get('/admin/static/css/test.css')
        self.assert_equal(rv.data.strip(), '/* nested file */')

        # try/finally, in case other tests use this app for Blueprint tests.
        max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT']
        try:
            expected_max_age = 3600
            if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == expected_max_age:
                expected_max_age = 7200
            app.config['SEND_FILE_MAX_AGE_DEFAULT'] = expected_max_age
            rv = c.get('/admin/static/css/test.css')
            cc = parse_cache_control_header(rv.headers['Cache-Control'])
            self.assert_equal(cc.max_age, expected_max_age)
        finally:
            app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default

        with app.test_request_context():
            self.assert_equal(flask.url_for('admin.static', filename='test.txt'),
                              '/admin/static/test.txt')

        with app.test_request_context():
            try:
                flask.render_template('missing.html')
            except TemplateNotFound, e:
                self.assert_equal(e.name, 'missing.html')
            else:
                self.assert_(0, 'expected exception')

        with flask.Flask(__name__).test_request_context():
            self.assert_equal(flask.render_template('nested/nested.txt'), 'I\'m nested')

    def test_default_static_cache_timeout(self):
        app = flask.Flask(__name__)
        class MyBlueprint(flask.Blueprint):
            def get_send_file_max_age(self, filename):
                return 100

        blueprint = MyBlueprint('blueprint', __name__, static_folder='static')
        app.register_blueprint(blueprint)

        # try/finally, in case other tests use this app for Blueprint tests.
        max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT']
        try:
            with app.test_request_context():
                unexpected_max_age = 3600
                if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == unexpected_max_age:
                    unexpected_max_age = 7200
                app.config['SEND_FILE_MAX_AGE_DEFAULT'] = unexpected_max_age
                rv = blueprint.send_static_file('index.html')
                cc = parse_cache_control_header(rv.headers['Cache-Control'])
                self.assert_equal(cc.max_age, 100)
        finally:
            app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default

    def test_templates_list(self):
        from blueprintapp import app
        templates = sorted(app.jinja_env.list_templates())
        self.assert_equal(templates, ['admin/index.html',
                                     'frontend/index.html'])

    def test_dotted_names(self):
        frontend = flask.Blueprint('myapp.frontend', __name__)
        backend = flask.Blueprint('myapp.backend', __name__)

        @frontend.route('/fe')
        def frontend_index():
            return flask.url_for('myapp.backend.backend_index')

        @frontend.route('/fe2')
        def frontend_page2():
            return flask.url_for('.frontend_index')

        @backend.route('/be')
        def backend_index():
            return flask.url_for('myapp.frontend.frontend_index')

        app = flask.Flask(__name__)
        app.register_blueprint(frontend)
        app.register_blueprint(backend)

        c = app.test_client()
        self.assert_equal(c.get('/fe').data.strip(), '/be')
        self.assert_equal(c.get('/fe2').data.strip(), '/fe')
        self.assert_equal(c.get('/be').data.strip(), '/fe')

    def test_empty_url_defaults(self):
        bp = flask.Blueprint('bp', __name__)

        @bp.route('/', defaults={'page': 1})
        @bp.route('/page/<int:page>')
        def something(page):
            return str(page)

        app = flask.Flask(__name__)
        app.register_blueprint(bp)

        c = app.test_client()
        self.assert_equal(c.get('/').data, '1')
        self.assert_equal(c.get('/page/2').data, '2')

    def test_route_decorator_custom_endpoint(self):

        bp = flask.Blueprint('bp', __name__)

        @bp.route('/foo')
        def foo():
            return flask.request.endpoint

        @bp.route('/bar', endpoint='bar')
        def foo_bar():
            return flask.request.endpoint

        @bp.route('/bar/123', endpoint='123')
        def foo_bar_foo():
            return flask.request.endpoint

        @bp.route('/bar/foo')
        def bar_foo():
            return flask.request.endpoint

        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/py')

        @app.route('/')
        def index():
            return flask.request.endpoint

        c = app.test_client()
        self.assertEqual(c.get('/').data, 'index')
        self.assertEqual(c.get('/py/foo').data, 'bp.foo')
        self.assertEqual(c.get('/py/bar').data, 'bp.bar')
        self.assertEqual(c.get('/py/bar/123').data, 'bp.123')
        self.assertEqual(c.get('/py/bar/foo').data, 'bp.bar_foo')

    def test_route_decorator_custom_endpoint_with_dots(self):
        bp = flask.Blueprint('bp', __name__)

        @bp.route('/foo')
        def foo():
            return flask.request.endpoint

        try:
            @bp.route('/bar', endpoint='bar.bar')
            def foo_bar():
                return flask.request.endpoint
        except AssertionError:
            pass
        else:
            raise AssertionError('expected AssertionError not raised')

        try:
            @bp.route('/bar/123', endpoint='bar.123')
            def foo_bar_foo():
                return flask.request.endpoint
        except AssertionError:
            pass
        else:
            raise AssertionError('expected AssertionError not raised')

        def foo_foo_foo():
            pass

        self.assertRaises(
            AssertionError,
            lambda: bp.add_url_rule(
                '/bar/123', endpoint='bar.123', view_func=foo_foo_foo
            )
        )

        self.assertRaises(
            AssertionError,
            bp.route('/bar/123', endpoint='bar.123'),
            lambda: None
        )

        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/py')

        c = app.test_client()
        self.assertEqual(c.get('/py/foo').data, 'bp.foo')
        # The rule's din't actually made it through
        rv = c.get('/py/bar')
        assert rv.status_code == 404
        rv = c.get('/py/bar/123')
        assert rv.status_code == 404

    def test_template_filter(self):
        bp = flask.Blueprint('bp', __name__)
        @bp.app_template_filter()
        def my_reverse(s):
            return s[::-1]
        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/py')
        self.assert_('my_reverse' in  app.jinja_env.filters.keys())
        self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse)
        self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba')

    def test_add_template_filter(self):
        bp = flask.Blueprint('bp', __name__)
        def my_reverse(s):
            return s[::-1]
        bp.add_app_template_filter(my_reverse)
        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/py')
        self.assert_('my_reverse' in  app.jinja_env.filters.keys())
        self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse)
        self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba')

    def test_template_filter_with_name(self):
        bp = flask.Blueprint('bp', __name__)
        @bp.app_template_filter('strrev')
        def my_reverse(s):
            return s[::-1]
        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/py')
        self.assert_('strrev' in  app.jinja_env.filters.keys())
        self.assert_equal(app.jinja_env.filters['strrev'], my_reverse)
        self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba')

    def test_add_template_filter_with_name(self):
        bp = flask.Blueprint('bp', __name__)
        def my_reverse(s):
            return s[::-1]
        bp.add_app_template_filter(my_reverse, 'strrev')
        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/py')
        self.assert_('strrev' in  app.jinja_env.filters.keys())
        self.assert_equal(app.jinja_env.filters['strrev'], my_reverse)
        self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba')

    def test_template_filter_with_template(self):
        bp = flask.Blueprint('bp', __name__)
        @bp.app_template_filter()
        def super_reverse(s):
            return s[::-1]
        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/py')
        @app.route('/')
        def index():
            return flask.render_template('template_filter.html', value='abcd')
        rv = app.test_client().get('/')
        self.assert_equal(rv.data, 'dcba')

    def test_template_filter_after_route_with_template(self):
        app = flask.Flask(__name__)
        @app.route('/')
        def index():
            return flask.render_template('template_filter.html', value='abcd')
        bp = flask.Blueprint('bp', __name__)
        @bp.app_template_filter()
        def super_reverse(s):
            return s[::-1]
        app.register_blueprint(bp, url_prefix='/py')
        rv = app.test_client().get('/')
        self.assert_equal(rv.data, 'dcba')

    def test_add_template_filter_with_template(self):
        bp = flask.Blueprint('bp', __name__)
        def super_reverse(s):
            return s[::-1]
        bp.add_app_template_filter(super_reverse)
        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/py')
        @app.route('/')
        def index():
            return flask.render_template('template_filter.html', value='abcd')
        rv = app.test_client().get('/')
        self.assert_equal(rv.data, 'dcba')

    def test_template_filter_with_name_and_template(self):
        bp = flask.Blueprint('bp', __name__)
        @bp.app_template_filter('super_reverse')
        def my_reverse(s):
            return s[::-1]
        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/py')
        @app.route('/')
        def index():
            return flask.render_template('template_filter.html', value='abcd')
        rv = app.test_client().get('/')
        self.assert_equal(rv.data, 'dcba')

    def test_add_template_filter_with_name_and_template(self):
        bp = flask.Blueprint('bp', __name__)
        def my_reverse(s):
            return s[::-1]
        bp.add_app_template_filter(my_reverse, 'super_reverse')
        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/py')
        @app.route('/')
        def index():
            return flask.render_template('template_filter.html', value='abcd')
        rv = app.test_client().get('/')
        self.assert_equal(rv.data, 'dcba')

def suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(BlueprintTestCase))
    suite.addTest(unittest.makeSuite(ModuleTestCase))
    return suite


text:
package io.github.ihongs.serv.centra;

import io.github.ihongs.combat.CombatHelper;
import io.github.ihongs.combat.anno.Combat;
import java.io.IOException;
import java.io.InputStream;
import java.io.File;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * 资源释放
 * @author Hongs
 */
@Combat("resources")
public class Resources {

    @Combat("save")
    public static void save(String[] args)
           throws IOException {
        if (args.length <= 1 || args[0].isEmpty()) {
            CombatHelper.println(
                "Usage: resources.save save/path " +
                "resource/path1 resource/path2/* resource/path3/**");
            return;
        }

        saveResources(args[0], args, 1);
    }

    @Combat("list")
    public static void list(String[] args)
           throws IOException {
        if (args.length <= 0) {
        CombatHelper.println(
                "Usage: resources.list " +
                "resource/path1 resource/path2/* resource/path3/**");
            return;
        }

        saveResources(null, args, 0);
    }

    @Combat("find")
    public static void find(String[] args)
           throws IOException {
        if (args.length <= 0) {
        CombatHelper.println(
                "Usage: resources.find " +
                "resource/path1 resource/path2/* resource/path3/**");
            return;
        }

        saveResources( "" , args, 0);
    }

    private static void saveResources(String dist, String[] args, int b)
            throws IOException {
        Set ress = new HashSet();
        for (int i = b; i < args.length; i ++) {
            String path = args[i];

            if (path.endsWith("/**")) {
                saveResources(ress, dist, path.substring(0, path.length() - 3), true );
            } else
            if (path.endsWith("/*" )) {
                saveResources(ress, dist, path.substring(0, path.length() - 2), false);
            } else
            {
                saveResource (ress, dist, path);
            }
        }
    }

    private static void saveResources(Set ress, String dist, String path, boolean recu)
            throws IOException {
        Enumeration <URL> links = Thread
                .currentThread (  /**/  )
                .getContextClassLoader( )
                .getResources  (  path  );

        while (links.hasMoreElements()) {
            URL    link = links.nextElement();
            String prot = link .getProtocol();
            String root = link .getPath  (  );

            /**
             * jar 格式 file:/xxxx/xxxx.jar!/zzzz/zzzz
             * dir 格式 /xxxx/xxxx/zzzz/zzzz
             * [1] 需要去掉后面类库包名路径
             * [2] jar 还要去掉 file: 和 !/
             */
            switch (prot) {
                case "jar" :
                    root = root.substring(5, root.length() - path.length() - 2); // [2]
                    saveResourcesInJar(ress, dist, root, path, recu);
                    break;
                case "file":
                    root = root.substring(0, root.length() - path.length() - 0); // [1]
                    saveResourcesInDir(ress, dist, root, path, recu);
                    break;
                default:
                    throw new IOException("Can not get resrouces in "+ link.toString());
            }
        }
    }

    private static void saveResourcesInJar(Set ress, String dist, String root, String path, boolean recu)
            throws IOException {
        try(JarFile file = new JarFile(root)) {
            Enumeration<JarEntry> items = file.entries();
                path = path +  "/"  ;
            int leng = path.length();

            while ( items.hasMoreElements( )) {
                JarEntry item = items.nextElement();
                String   name = item . getName(   );
                if ( name.endsWith(   "/"   )
                ||   name.endsWith(".class")) {
                    continue;
                }
                if (!name.startsWith( path )) {
                    continue;
                }
                if (!recu && name.indexOf("/",leng) > 0) {
                    continue;
                }

                if (dist == null) {
                    CombatHelper.paintln(name);
                } else
                if (dist.isEmpty()) {
                    name = name +" in "+ root ;
                    CombatHelper.paintln(name);
                } else
                {
                    saveFile(ress, dist, name, file, item);
                    CombatHelper.paintln(name);
                }
            }
        }
    }

    private static void saveResourcesInDir(Set ress, String dist, String root, String path, boolean recu)
            throws IOException {
        File[] files = new File (root + path).listFiles();
        for (File file : files) {
            if (! file.isDirectory()) {
                String name = path + "/" + file.getName();
                if (name.endsWith(".class")) {
                    continue;
                }

                if (dist == null) {
                    CombatHelper.paintln(name);
                } else
                if (dist.isEmpty()) {
                    name = name +" in "+ root ;
                    CombatHelper.paintln(name);
                } else
                {
                    saveFile(ress, dist, name, file);
                    CombatHelper.paintln(name);
                }
            } else if (recu) {
                String name = path + "/" + file.getName( );
                saveResourcesInDir(ress, dist, root, name, recu);
            }
        }
    }

    private static void saveResource(Set ress, String dist, String path)
            throws IOException {
        Enumeration <URL> links = Thread
                .currentThread (  /**/  )
                .getContextClassLoader( )
                .getResources  (  path  );

        while (links.hasMoreElements()) {
            URL    link = links.nextElement();
            String prot = link .getProtocol();
            String root = link .getPath  (  );

            /**
             * jar 格式 file:/xxxx/xxxx.jar!/zzzz/zzzz
             * dir 格式 /xxxx/xxxx/zzzz/zzzz
             * [1] 需要去掉后面类库包名路径
             * [2] jar 还要去掉 file: 和 !/
             */
            switch (prot) {
                case "jar" :
                    root = root.substring(5, root.length() - path.length() - 2); // [2]
                    saveResourceInJar (ress, dist, root, path);
                    break;
                case "file":
                    root = root.substring(0, root.length() - path.length() - 0); // [1]
                    saveResourceInDir (ress, dist, root, path);
                    break;
                default:
                    throw new IOException("Can not get resrouce in " + link.toString());
            }
        }
    }

    private static void saveResourceInJar(Set ress, String dist, String root, String name)
            throws IOException {
        try(JarFile  file = new JarFile(root)) {
            JarEntry item = file.getJarEntry(name);
            if (item.isDirectory()) {
                throw new IOException("Can not save resrouce for dir "+ name);
            }

            if (dist == null) {
                CombatHelper.paintln(name);
            } else
            if (dist.isEmpty()) {
                name = name +" in "+ root ;
                CombatHelper.paintln(name);
            } else
            {
                saveFile(ress, dist, name, file, item);
                CombatHelper.paintln(name);
            }
        }
    }

    private static void saveResourceInDir(Set ress, String dist, String root, String name)
            throws IOException {
        File file = new File (root + name);
        if ( file.isDirectory() ) {
            throw new IOException("Can not save resrouce for dir "+ name);
        }

        if (dist == null) {
            CombatHelper.paintln(name);
        } else
        if (dist.isEmpty()) {
            name = name +" in "+ root ;
            CombatHelper.paintln(name);
        } else
        {
            saveFile(ress, dist, name, file);
            CombatHelper.paintln(name);
        }
    }

    private static void saveFile(Set ress, String dist, String name, File file)
            throws IOException {
        if (ress.contains(name) == false) {
            ress.add(name);
        } else {
            return;
        }

        File disf = new File (dist +"/"+ name);
        File dirf = disf.getParentFile();
        Path disp = disf.toPath();
        Path filp = file.toPath();
        if (!dirf.exists()) {
             dirf.mkdirs();
        }

        if (Files.isSameFile(disp, filp) == false) {
            Files.copy(filp, disp, StandardCopyOption.REPLACE_EXISTING);
        }
    }

    private static void saveFile(Set ress, String dist, String name, JarFile file, JarEntry item)
            throws IOException {
        if (ress.contains(name) == false) {
            ress.add(name);
        } else {
            return;
        }

        File disf = new File(dist +"/"+ name);
        File dirf = disf.getParentFile();
        Path disp = disf.toPath();
        if (!dirf.exists()) {
             dirf.mkdirs();
        }

        try (
            InputStream inps = file.getInputStream(item);
        ) {
            Files.copy(inps, disp, StandardCopyOption.REPLACE_EXISTING);
        }
    }

}


text:
package com.amazonaws.services.cloud9.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListEnvironmentsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * If there are more than 25 items in the list, only the first 25 items are returned, along with a unique string
     * called a next token. To get the next batch of items in the list, call this operation again, adding the
     * next token to the call.
     *

     */
    private String nextToken;
    /**
     *

     * The list of environment identifiers.
     *

     */
    private java.util.List<String> environmentIds;

    /**
     *

     * If there are more than 25 items in the list, only the first 25 items are returned, along with a unique string
     * called a next token. To get the next batch of items in the list, call this operation again, adding the
     * next token to the call.
     *

     *
     * @param nextToken
     *        If there are more than 25 items in the list, only the first 25 items are returned, along with a unique
     *        string called a next token. To get the next batch of items in the list, call this operation again,
     *        adding the next token to the call.
     */

    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     *

     * If there are more than 25 items in the list, only the first 25 items are returned, along with a unique string
     * called a next token. To get the next batch of items in the list, call this operation again, adding the
     * next token to the call.
     *

     *
     * @return If there are more than 25 items in the list, only the first 25 items are returned, along with a unique
     *         string called a next token. To get the next batch of items in the list, call this operation again,
     *         adding the next token to the call.
     */

    public String getNextToken() {
        return this.nextToken;
    }

    /**
     *

     * If there are more than 25 items in the list, only the first 25 items are returned, along with a unique string
     * called a next token. To get the next batch of items in the list, call this operation again, adding the
     * next token to the call.
     *

     *
     * @param nextToken
     *        If there are more than 25 items in the list, only the first 25 items are returned, along with a unique
     *        string called a next token. To get the next batch of items in the list, call this operation again,
     *        adding the next token to the call.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListEnvironmentsResult withNextToken(String nextToken) {
        setNextToken(nextToken);
        return this;
    }

    /**
     *

     * The list of environment identifiers.
     *

     *
     * @return The list of environment identifiers.
     */

    public java.util.List<String> getEnvironmentIds() {
        return environmentIds;
    }

    /**
     *

     * The list of environment identifiers.
     *

     *
     * @param environmentIds
     *        The list of environment identifiers.
     */

    public void setEnvironmentIds(java.util.Collection<String> environmentIds) {
        if (environmentIds == null) {
            this.environmentIds = null;
            return;
        }

        this.environmentIds = new java.util.ArrayList<String>(environmentIds);
    }

    /**
     *

     * The list of environment identifiers.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setEnvironmentIds(java.util.Collection)} or {@link #withEnvironmentIds(java.util.Collection)} if you want
     * to override the existing values.
     *

     *
     * @param environmentIds
     *        The list of environment identifiers.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListEnvironmentsResult withEnvironmentIds(String... environmentIds) {
        if (this.environmentIds == null) {
            setEnvironmentIds(new java.util.ArrayList<String>(environmentIds.length));
        }
        for (String ele : environmentIds) {
            this.environmentIds.add(ele);
        }
        return this;
    }

    /**
     *

     * The list of environment identifiers.
     *

     *
     * @param environmentIds
     *        The list of environment identifiers.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListEnvironmentsResult withEnvironmentIds(java.util.Collection<String> environmentIds) {
        setEnvironmentIds(environmentIds);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getNextToken() != null)
            sb.append("NextToken: ").append(getNextToken()).append(",");
        if (getEnvironmentIds() != null)
            sb.append("EnvironmentIds: ").append(getEnvironmentIds());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof ListEnvironmentsResult == false)
            return false;
        ListEnvironmentsResult other = (ListEnvironmentsResult) obj;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        if (other.getEnvironmentIds() == null ^ this.getEnvironmentIds() == null)
            return false;
        if (other.getEnvironmentIds() != null && other.getEnvironmentIds().equals(this.getEnvironmentIds()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        hashCode = prime * hashCode + ((getEnvironmentIds() == null) ? 0 : getEnvironmentIds().hashCode());
        return hashCode;
    }

    @Override
    public ListEnvironmentsResult clone() {
        try {
            return (ListEnvironmentsResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
"""Django page CMS test suite module"""
import unittest
from pages.tests.test_functionnal import FunctionnalTestCase
from pages.tests.test_unit import UnitTestCase
from pages.tests.test_regression import RegressionTestCase
#from pages.tests.test_pages_link import LinkTestCase
#from pages.tests.test_auto_render import AutoRenderTestCase

def suite():
    suite = unittest.TestSuite()
    from pages import settings
    if not settings.PAGE_ENABLE_TESTS:
        return suite
    suite.addTest(unittest.makeSuite(UnitTestCase))
    suite.addTest(unittest.makeSuite(RegressionTestCase))
    #try:
    #    from pages.tests.test_selenium import SeleniumTestCase
    #    suite.addTest(unittest.makeSuite(SeleniumTestCase))
    #except ImportError:
    #    print("You need to install selenium and PhantomJS to run browsers tests")
    # suite.addTest(unittest.makeSuite(LinkTestCase))
    # suite.addTest(unittest.makeSuite(AutoRenderTestCase))
    # being the slower test I run it at the end
    suite.addTest(unittest.makeSuite(FunctionnalTestCase))
    return suite


text:
package scsp

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// HangupThirdCall invokes the scsp.HangupThirdCall API synchronously
func (client *Client) HangupThirdCall(request *HangupThirdCallRequest) (response *HangupThirdCallResponse, err error) {
	response = CreateHangupThirdCallResponse()
	err = client.DoAction(request, response)
	return
}

// HangupThirdCallWithChan invokes the scsp.HangupThirdCall API asynchronously
func (client *Client) HangupThirdCallWithChan(request *HangupThirdCallRequest) (<-chan *HangupThirdCallResponse, <-chan error) {
	responseChan := make(chan *HangupThirdCallResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.HangupThirdCall(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// HangupThirdCallWithCallback invokes the scsp.HangupThirdCall API asynchronously
func (client *Client) HangupThirdCallWithCallback(request *HangupThirdCallRequest, callback func(response *HangupThirdCallResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *HangupThirdCallResponse
		var err error
		defer close(result)
		response, err = client.HangupThirdCall(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// HangupThirdCallRequest is the request struct for api HangupThirdCall
type HangupThirdCallRequest struct {
	*requests.RpcRequest
	ClientToken  string `position:"Body"`
	InstanceId   string `position:"Body"`
	AccountName  string `position:"Body"`
	CallId       string `position:"Body"`
	JobId        string `position:"Body"`
	ConnectionId string `position:"Body"`
}

// HangupThirdCallResponse is the response struct for api HangupThirdCall
type HangupThirdCallResponse struct {
	*responses.BaseResponse
	Message   string `json:"Message" xml:"Message"`
	RequestId string `json:"RequestId" xml:"RequestId"`
	Code      string `json:"Code" xml:"Code"`
	Success   bool   `json:"Success" xml:"Success"`
}

// CreateHangupThirdCallRequest creates a request to invoke HangupThirdCall API
func CreateHangupThirdCallRequest() (request *HangupThirdCallRequest) {
	request = &HangupThirdCallRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("scsp", "2020-07-02", "HangupThirdCall", "", "")
	request.Method = requests.POST
	return
}

// CreateHangupThirdCallResponse creates a response to parse from HangupThirdCall response
func CreateHangupThirdCallResponse() (response *HangupThirdCallResponse) {
	response = &HangupThirdCallResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
package org.apache.usergrid.corepersistence.index;

import com.google.inject.Inject;
import net.jcip.annotations.NotThreadSafe;
import org.apache.usergrid.corepersistence.TestIndexModule;
import org.apache.usergrid.corepersistence.util.CpNamingUtils;
import org.apache.usergrid.persistence.core.CassandraFig;
import org.apache.usergrid.persistence.core.guicyfig.ClusterFig;
import org.apache.usergrid.persistence.core.scope.ApplicationScope;
import org.apache.usergrid.persistence.core.scope.ApplicationScopeImpl;
import org.apache.usergrid.persistence.core.test.UseModules;
import org.apache.usergrid.persistence.index.IndexFig;
import org.apache.usergrid.persistence.index.IndexLocationStrategy;
import org.apache.usergrid.persistence.index.impl.EsRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;

/**
 * Classy class class.
 */
@RunWith( EsRunner.class )
@UseModules( { TestIndexModule.class } )
@NotThreadSafe
public class IndexNamingTest {
    @Inject
    public CassandraFig cassandraFig;

    @Inject
    public IndexFig indexFig;

    @Inject
    public ClusterFig clusterFig;

    @Inject
    public CoreIndexFig indexProcessorFig;

    @Inject
    public IndexLocationStrategyFactory indexLocationStrategyFactory;

    @Inject
    public ApplicationIndexBucketLocator bucketLocator;

    private ApplicationScope applicationScope;
    private ApplicationScope managementApplicationScope;
    private ApplicationIndexLocationStrategy applicationLocationStrategy;
    private ManagementIndexLocationStrategy managementLocationStrategy;
    private String keyspaceName;
    private String clusterName;

    @Before
    public void setup(){
        keyspaceName = cassandraFig.getApplicationKeyspace().toLowerCase();
        clusterName = clusterFig.getClusterName().toLowerCase();
        this.applicationScope = CpNamingUtils.getApplicationScope(UUID.randomUUID());
        this.managementApplicationScope = CpNamingUtils.getApplicationScope(CpNamingUtils.getManagementApplicationId().getUuid());
        this.managementLocationStrategy = new ManagementIndexLocationStrategy(clusterFig,cassandraFig,indexFig, indexProcessorFig);
        this.applicationLocationStrategy = new ApplicationIndexLocationStrategy(clusterFig, cassandraFig,indexFig,applicationScope,bucketLocator);
    }

    @Test
    public void managementNaming(){
        IndexLocationStrategy indexLocationStrategy = indexLocationStrategyFactory.getIndexLocationStrategy(managementApplicationScope);
        //check that factory works
        assertEquals(indexLocationStrategy.getIndexRootName(),managementLocationStrategy.getIndexRootName());
        //check that root name is as expected
        assertEquals(indexLocationStrategy.getIndexRootName(),clusterName + "_" + keyspaceName + "_" + indexProcessorFig.getManagementAppIndexName());
        //check bucket name is as expected
        assertEquals(indexLocationStrategy.getIndexRootName(), indexLocationStrategy.getIndexInitialName());
        assertEquals(indexLocationStrategy.getIndexInitialName(),clusterName + "_" + keyspaceName + "_" +indexProcessorFig.getManagementAppIndexName());

    }

    @Test
    public void managementAliasName(){
        IndexLocationStrategy indexLocationStrategy = indexLocationStrategyFactory.getIndexLocationStrategy(managementApplicationScope);

        String managementAppIndexName = indexProcessorFig.getManagementAppIndexName();
        assertEquals(
            indexLocationStrategy.getAlias().getReadAlias(),
            clusterName + "_" + keyspaceName + "_" + managementAppIndexName + "_read_" + indexFig.getAliasPostfix()
        );
        assertEquals(
            indexLocationStrategy.getAlias().getWriteAlias(),
            clusterName + "_" + keyspaceName + "_" + managementAppIndexName + "_write_" + indexFig.getAliasPostfix()
        );
    }

    @Test
    public void applicationRootNaming(){
        IndexLocationStrategy indexLocationStrategy = indexLocationStrategyFactory.getIndexLocationStrategy(applicationScope);

        assertEquals(
            indexLocationStrategy.getIndexRootName(),
            applicationLocationStrategy.getIndexRootName()
        );

        assertEquals(
            indexLocationStrategy.getIndexRootName(),
            clusterName
        );

    }

    @Test
    public void applicationAliasName(){
        IndexLocationStrategy indexLocationStrategy = indexLocationStrategyFactory.getIndexLocationStrategy(applicationScope);
        String applicationId = applicationScope.getApplication().getUuid().toString().toLowerCase();
        assertEquals(
            indexLocationStrategy.getAlias().getReadAlias(),
            clusterName +"_"+ applicationId + "_read_" + indexFig.getAliasPostfix()
        );
        assertEquals(
            indexLocationStrategy.getAlias().getWriteAlias(),
            clusterName +"_"+ applicationId + "_write_" + indexFig.getAliasPostfix()
        );
    }

    @Test
    public void applicationBucketNaming(){
        Set<String> names = new HashSet<>();
        for(int i=0;i<10;i++){
            IndexLocationStrategy indexLocationStrategyBucket =
                new ApplicationIndexLocationStrategy(
                    clusterFig, cassandraFig, indexFig,applicationScope,
                    new ApplicationIndexBucketLocator(indexProcessorFig)
                );
            names.add(indexLocationStrategyBucket.getIndexInitialName());
        }
        Pattern regex = Pattern.compile(clusterName+"_applications_\\d+");
        //always hashes to same bucket
        assertTrue(names.size() == 1);
        names = new HashSet<>();
        //get 100 names you should get 5 unique values in the set since app id is the same
        for(int i=0;i<100;i++){
            IndexLocationStrategy indexLocationStrategyBucket =
                new ApplicationIndexLocationStrategy(
                    clusterFig,
                    cassandraFig,
                    indexFig,
                    new ApplicationScopeImpl(CpNamingUtils.generateApplicationId(UUID.randomUUID())),
                    new ApplicationIndexBucketLocator(indexProcessorFig));
            String name = indexLocationStrategyBucket.getIndexInitialName();
            assertTrue("failed to match correct name",regex.matcher(name).matches());
            names.add(name);
        }
        //always hashes to diff't bucket
        assertTrue(names.size() == indexProcessorFig.getNumberOfIndexBuckets());
    }

    @Test
    public void testReplication(){
        IndexLocationStrategy indexLocationStrategy = indexLocationStrategyFactory.getIndexLocationStrategy(applicationScope);
        ReplicatedIndexLocationStrategy replicatedIndexLocationStrategy = new ReplicatedIndexLocationStrategy(indexLocationStrategy);
        assertEquals(replicatedIndexLocationStrategy.getApplicationScope(),indexLocationStrategy.getApplicationScope());
        assertEquals(replicatedIndexLocationStrategy.getIndexInitialName(),indexLocationStrategy.getIndexInitialName());
        assertEquals(replicatedIndexLocationStrategy.getIndexRootName(),indexLocationStrategy.getIndexRootName());
        assertEquals(replicatedIndexLocationStrategy.getNumberOfReplicas(), indexLocationStrategy.getNumberOfReplicas());
        assertEquals(replicatedIndexLocationStrategy.getNumberOfShards(),indexLocationStrategy.getNumberOfShards());
        assertEquals(replicatedIndexLocationStrategy.getAlias().getReadAlias(),indexLocationStrategy.getAlias().getReadAlias());
        assertEquals(replicatedIndexLocationStrategy.getAlias().getWriteAlias(),indexLocationStrategy.getAlias().getWriteAlias());

    }

}


text:
IF EXISTS ( SELECT  *
            FROM    sys.objects
            WHERE   object_id = OBJECT_ID(N'pa.GenPla_Genera_Fondo_Incapacidad')
                    AND type IN ( N'P', N'PC' ) )
/****** Object:  StoredProcedure [pa].[GenPla_Genera_Fondo_Incapacidad]    Script Date: 16-01-2017 4:00:02 PM ******/
DROP PROCEDURE [pa].[GenPla_Genera_Fondo_Incapacidad]
GO

/****** Object:  StoredProcedure [pa].[GenPla_Genera_Fondo_Incapacidad]    Script Date: 16-01-2017 4:00:02 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [pa].[GenPla_Genera_Fondo_Incapacidad]
    @codppl INT,
    @usuario VARCHAR(50) = NULL

AS

set dateformat dmy

declare @codcia int,
        @ini datetime,
        @fin datetime,
        @anio int,
        @frec int,
        @maximodias float,
        @diasadjudicados float,
		@codrin int

select @codcia = tpl_codcia,
       @ini = ppl_fecha_ini,
       @fin = ppl_fecha_fin,
       @anio = ppl_anio,
       @frec = ppl_frecuencia
  from sal.ppl_periodos_planilla
  join sal.tpl_tipo_planilla
    on tpl_Codigo = ppl_Codtpl
 where ppl_codigo = @codppl

select @diasAdjudicados = gen.get_valor_parametro_int('FondoIncapacidadDias', cia_codpai, null, null, null),
       @maximodias = isnull(gen.get_valor_parametro_int('FondoIncapacidadMaximoDias', cia_codpai, null, null, null),0),
	   @codrin = isnull(gen.get_valor_parametro_int('CodigoRiesgoFondo', cia_codpai, null, null, null),0)
  from eor.cia_companias
 where cia_codigo = @codcia

set @diasAdjudicados = isnull(@diasAdjudicados, 0)
set @maximodias = isnull(@maximodias, 0)

-- ya que este proceso se corre por cada quincena es necesario saber cuanto gana el empleado por quincena.
select @diasAdjudicados = round(@diasAdjudicados/24.00,4)

-- primero inserto los periodos que no existan para empleados nuevos
insert into acc.fin_fondos_incapacidad
	(fin_Codemp, fin_periodo,fin_codrin, fin_Desde, fin_hasta, fin_dias_derecho, fin_dias_incapacitado, fin_horas_incapacitado ,
		fin_usuario_grabacion, fin_fecha_grabacion)
	select emp_codigo,
		'General',
		@codrin,
		emp_fecha_ingreso emp_fecha_ini,
		@fin emp_fecha_fin,
		0 fin_dias_derecho,
		0 fin_dias_incapacitado,
		0 fin_horas_incapacitado,
		isnull(@usuario, SYSTEM_USER), GETDATE()
	from exp.emp_empleos
	join eor.plz_plazas on plz_codigo = emp_codplz
	where plz_codcia = @codcia
	and emp_estado = 'A'
	and emp_fecha_ingreso <= @fin
	and NOT EXISTS (select 1 from acc.fin_fondos_incapacidad
						where fin_Codemp = emp_codigo
						and fin_periodo = 'General' )
	-- Omito los empleados que han tenido pago de vacaciones por Renuncia al Tiempo
	-- en el periodo de planilla para el cual se procesa el fondo de incapacidad
	and not exists (select 1 from acc.dva_dias_vacacion join acc.vac_vacaciones on vac_codigo = dva_codvac
					where dva_pagadas = 1 -- Renuncia al tiempo
					and dva_codppl = @codppl
					and vac_codemp = emp_codigo)

/* ACTUALIZA LOS DIAS DE INCAPACIDAD OTORGADOS */
UPDATE acc.fin_fondos_incapacidad
	SET fin_hasta = hasta,
		fin_dias_derecho =  CASE WHEN dias > @maximodias THEN @maximodias ELSE dias END ,
		fin_dias_incapacitado = fin_dias_incapacitado + ISNULL(dias_incapacitado,0)
	FROM (
		SELECT fin_codigo codfin,
				fin_Codemp codemp,
				fin_periodo periodo,
				fin_Codrin codrin,
				hasta = @fin,
				fin_dias_derecho +
				(CASE WHEN emp_fecha_ingreso > @ini THEN
						CASE WHEN DAY(emp_fecha_ingreso) <= 15 THEN
							CASE WHEN DAY(emp_fecha_ingreso) = 1 THEN
								1
							ELSE
								(gen.DateDiffComercial(emp_fecha_ingreso,CONVERT(DATETIME,'15/'+ CAST(MONTH(emp_fecha_ingreso) AS VARCHAR) + '/' + CAST(YEAR(emp_Fecha_ingreso) AS VARCHAR),103) + 1))/15.00
							END
						ELSE
							CASE WHEN DAY(emp_fecha_ingreso) = 16 THEN
								1
							ELSE
								(gen.DateDiffComercial(emp_fecha_ingreso,DATEADD(mm,1,CONVERT(DATETIME,'01/'+ CAST(MONTH(emp_fecha_ingreso) AS VARCHAR) + '/' + CAST(YEAR(emp_Fecha_ingreso) AS VARCHAR),103))- 1) + 1)/15.00
							END
						END * @diasAdjudicados
				ELSE
						@diasAdjudicados
				END
				)  dias, /*DIAS DERECHO*/
			ISNULL((SELECT --sum(isnull(ixe_dias_incapacitado,0) + isnull(ixe_horas_incapacitado,0)/ 8.0000)
			        SUM(pie_dias)
					FROM acc.ixe_incapacidades
					JOIN acc.rin_riesgos_incapacidades ON rin_codigo = ixe_codrin
					JOIN acc.pie_periodos_incapacidad ON pie_codixe = ixe_codigo
					WHERE ixe_estado  ='Autorizado'
					AND ixe_Codppl = @codppl
					AND ixe_codemp = fin_Codemp
					AND rin_utiliza_fondo = 1
					AND pie_codfin = fin_codigo
					AND pie_valor_a_pagar != 0
					) ,0) dias_incapacitado
			FROM acc.fin_fondos_incapacidad
			JOIN exp.emp_empleos ON emp_codigo = fin_codemp
			JOIN eor.plz_plazas ON plz_codigo = emp_codplz
			WHERE plz_codcia = @codcia
			AND fin_periodo = 'General'
			AND emp_estado = 'A'
			-- Omito los empleados que han tenido pago de vacaciones por Renuncia al Tiempo
			-- en el periodo de planilla para el cual se procesa el fondo de incapacidad
			AND NOT EXISTS (SELECT 1 FROM acc.dva_dias_vacacion JOIN acc.vac_vacaciones ON vac_codigo = dva_codvac
							WHERE dva_pagadas = 1 -- Renuncia al tiempo
							AND dva_codppl = @codppl
							AND vac_codemp = emp_codigo)
		)data
WHERE codfin = fin_Codigo
	AND fin_Codemp = codemp
	AND fin_periodo = periodo

GO


text:
<?xml version="1.0" encoding="UTF-8"?>
<project-private xmlns="http://www.netbeans.org/ns/project-private/1">
    <editor-bookmarks xmlns="http://www.netbeans.org/ns/editor-bookmarks/2" lastBookmarkId="0"/>
    <open-files xmlns="http://www.netbeans.org/ns/projectui-open-files/2">
        <group>
            <file>file:/C:/wamp/www/veilleTechnologique/app/config/config_prod.yml</file>
            <file>file:/C:/wamp/www/veilleTechnologique/app/config/security.yml</file>
            <file>file:/C:/wamp/www/veilleTechnologique/src/veilleTechnologique/veilleBundle/Resources/config/routing.yml</file>
            <file>file:/C:/wamp/www/veilleTechnologique/app/config/config_dev.yml</file>
            <file>file:/C:/wamp/www/veilleTechnologique/app/config/config.yml</file>
            <file>file:/C:/wamp/www/veilleTechnologique/app/AppKernel.php</file>
            <file>file:/C:/wamp/www/veilleTechnologique/src/veilleTechnologique/veilleBundle/Resources/views/menu.html.twig</file>
            <file>file:/C:/wamp/www/veilleTechnologique/app/config/routing.yml</file>
            <file>file:/C:/wamp/www/veilleTechnologique/src/veilleTechnologique/veilleBundle/Resources/views/layout.html.twig</file>
            <file>file:/C:/wamp/www/veilleTechnologique/src/veilleTechnologique/veilleBundle/Controller/UserController.php</file>
            <file>file:/C:/wamp/www/veilleTechnologique/src/veilleTechnologique/veilleBundle/Entity/User.php</file>
            <file>file:/C:/wamp/www/veilleTechnologique/src/veilleTechnologique/veilleBundle/Entity/Liste.php</file>
            <file>file:/C:/wamp/www/veilleTechnologique/src/veilleTechnologique/veilleBundle/Resources/views/Default/index.html.twig</file>
            <file>file:/C:/wamp/www/veilleTechnologique/src/veilleTechnologique/veilleBundle/Resources/views/Default/inscription.html.twig</file>
            <file>file:/C:/wamp/www/veilleTechnologique/.gitignore</file>
            <file>file:/C:/wamp/www/veilleTechnologique/app/config/routing_dev.yml</file>
            <file>file:/C:/wamp/www/veilleTechnologique/src/veilleTechnologique/veilleBundle/Resources/views/Default/interface.html.twig</file>
            <file>file:/C:/wamp/www/veilleTechnologique/src/veilleTechnologique/veilleBundle/Controller/DefaultController.php</file>
        </group>
    </open-files>
</project-private>


text:
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
{-# LANGUAGE PolyKinds, DataKinds, TypeFamilies, GADTs, MultiParamTypeClasses, KindSignatures,
             FunctionalDependencies, FlexibleInstances, UndecidableInstances, ExistentialQuantification #-}

module T6068 where

import Prelude hiding (Maybe, Nothing)
import Data.Kind (Type)

data Maybe :: Type -> Type where
  Nothing :: Maybe a

data family Sing (a :: k)

data instance Sing (a :: Maybe k) where
  SNothing :: Sing Nothing

data KProxy (a :: Type) = KProxy
data Existential (p :: KProxy k) =
  forall (a :: k). Exists (Sing a)

class HasSingleton a (kp :: KProxy k) | a -> kp where
  exists :: a -> Existential kp

class Floop a b | a -> b

instance Floop a (mp :: KProxy (Maybe ak)) => HasSingleton (Maybe a) mp where
  exists Nothing = Exists SNothing

-- instance forall (a ::Type) (mp :: KProxy (Maybe ak)).
--          HasSingleton (Maybe ak) (Maybe a) mp where
--   exists Nothing = Exists SNothing