text:
package internal

import (
	. "github.com/kahing/goofys/api/common"

	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"
	"strings"
	"syscall"
	"time"

	uuid "github.com/gofrs/uuid"
	"github.com/jacobsa/fuse"
	"github.com/sirupsen/logrus"

	adl "github.com/Azure/azure-sdk-for-go/services/datalake/store/2016-11-01/filesystem"
	"github.com/Azure/go-autorest/autorest"
)

type ADLv1 struct {
	cap Capabilities

	flags  *FlagStorage
	config *ADLv1Config

	client  *adl.Client
	account string
	// ADLv1 doesn't actually have the concept of buckets (defined
	// by me as a top level container that can be created with
	// existing credentials). We could create new adl filesystems
	// but that seems more involved. This bucket is more like a
	// backend level prefix mostly to ease testing
	bucket string
}

type ADLv1Err struct {
	RemoteException struct {
		Exception     string
		Message       string
		JavaClassName string
	}
	resp *http.Response
}

func (err ADLv1Err) Error() string {
	return fmt.Sprintf("%v %v", err.resp.Status, err.RemoteException)
}

const ADL1_REQUEST_ID = "X-Ms-Request-Id"

var adls1Log = GetLogger("adlv1")

type ADLv1MultipartBlobCommitInput struct {
	Size uint64
}

func IsADLv1Endpoint(endpoint string) bool {
	return strings.HasPrefix(endpoint, "adl://")
	//return strings.HasSuffix(endpoint, ".azuredatalakestore.net")
}

func adlLogResp(level logrus.Level, r *http.Response) {
	if adls1Log.IsLevelEnabled(level) {
		op := r.Request.URL.Query().Get("op")
		requestId := r.Request.Header.Get(ADL1_REQUEST_ID)
		respId := r.Header.Get(ADL1_REQUEST_ID)
		adls1Log.Logf(level, "%v %v %v %v %v", op, r.Request.URL.String(),
			requestId, r.Status, respId)
	}
}

func NewADLv1(bucket string, flags *FlagStorage, config *ADLv1Config) (*ADLv1, error) {
	parts := strings.SplitN(config.Endpoint, ".", 2)
	if len(parts) != 2 {
		return nil, fmt.Errorf("Invalid endpoint: %v", config.Endpoint)
	}

	LogRequest := func(p autorest.Preparer) autorest.Preparer {
		return autorest.PreparerFunc(func(r *http.Request) (*http.Request, error) {
			// the autogenerated permission bits are
			// incorrect, it should be a string in base 8
			// instead of base 10
			q := r.URL.Query()
			if perm := q.Get("permission"); perm != "" {
				perm, err := strconv.ParseInt(perm, 10, 32)
				if err == nil {
					q.Set("permission",
						fmt.Sprintf("0%o", perm))
					r.URL.RawQuery = q.Encode()
				}
			}

			u, _ := uuid.NewV4()
			r.Header.Add(ADL1_REQUEST_ID, u.String())

			if adls1Log.IsLevelEnabled(logrus.DebugLevel) {
				op := r.URL.Query().Get("op")
				requestId := r.Header.Get(ADL1_REQUEST_ID)
				adls1Log.Debugf("%v %v %v", op, r.URL.String(), requestId)
			}

			r, err := p.Prepare(r)
			if err != nil {
				log.Error(err)
			}
			return r, err
		})
	}

	LogResponse := func(p autorest.Responder) autorest.Responder {
		return autorest.ResponderFunc(func(r *http.Response) error {
			adlLogResp(logrus.DebugLevel, r)
			err := p.Respond(r)
			if err != nil {
				log.Error(err)
			}
			return err
		})
	}

	adlClient := adl.NewClient()
	adlClient.BaseClient.Client.Authorizer = config.Authorizer
	adlClient.BaseClient.Client.RequestInspector = LogRequest
	adlClient.BaseClient.Client.ResponseInspector = LogResponse
	adlClient.BaseClient.AdlsFileSystemDNSSuffix = parts[1]
	adlClient.BaseClient.Sender.(*http.Client).Transport = GetHTTPTransport()

	b := &ADLv1{
		flags:   flags,
		config:  config,
		client:  &adlClient,
		account: parts[0],
		bucket:  bucket,
		cap: Capabilities{
			NoParallelMultipart: true,
			DirBlob:             true,
			Name:                "adl",
			// ADLv1 fails with 404 if we upload data
			// larger than 30000000 bytes (28.6MB) (28MB
			// also failed in at one point, but as of
			// 2019-11-07 seems to work)
			MaxMultipartSize: 20 * 1024 * 1024,
		},
	}

	return b, nil
}

func (b *ADLv1) Bucket() string {
	return b.bucket
}

func (b *ADLv1) Delegate() interface{} {
	return b
}

func mapADLv1Error(resp *http.Response, err error, rawError bool) error {
	// TODO(dotslash/khc): Figure out a way to surface these errors before reducing
	// them to syscall.E<SOMETHING>. The detailed errors can aid in better debugging
	// without the need to explicitly enabling debug_s3 flag and trying to reproduce
	// issues.
	if resp == nil {
		if err != nil {
			return syscall.EAGAIN
		} else {
			return err
		}
	}

	if resp.StatusCode < 200 || resp.StatusCode >= 300 {
		defer resp.Body.Close()
		if rawError {
			decoder := json.NewDecoder(resp.Body)
			var adlErr ADLv1Err

			var err error
			if err = decoder.Decode(&adlErr); err == nil {
				adlErr.resp = resp
				return adlErr
			} else {
				adls1Log.Errorf("cannot parse error: %v", err)
				return syscall.EAGAIN
			}
		} else {
			err = mapHttpError(resp.StatusCode)
			if err != nil {
				return err
			} else {
				adlLogResp(logrus.ErrorLevel, resp)
				return syscall.EINVAL
			}
		}
	}
	return nil
}

func (b *ADLv1) path(key string) string {
	key = strings.TrimLeft(key, "/")
	if b.bucket != "" {
		if key != "" {
			key = b.bucket + "/" + key
		} else {
			key = b.bucket
		}
	}
	return key
}

func (b *ADLv1) Init(key string) error {
	res, err := b.client.GetFileStatus(context.TODO(), b.account, b.path(key), nil)
	err = mapADLv1Error(res.Response.Response, err, true)
	if adlErr, ok := err.(ADLv1Err); ok {
		if adlErr.RemoteException.Exception == "FileNotFoundException" {
			return nil
		}
	}
	return err
}

func (b *ADLv1) Capabilities() *Capabilities {
	return &b.cap
}

func adlv1LastModified(t int64) time.Time {
	return time.Unix(t/1000, t%1000000)
}

func adlv1FileStatus2BlobItem(f *adl.FileStatusProperties, key *string) BlobItemOutput {
	return BlobItemOutput{
		Key:          key,
		LastModified: PTime(adlv1LastModified(*f.ModificationTime)),
		Size:         uint64(*f.Length),
	}
}

func (b *ADLv1) HeadBlob(param *HeadBlobInput) (*HeadBlobOutput, error) {
	res, err := b.client.GetFileStatus(context.TODO(), b.account, b.path(param.Key), nil)
	err = mapADLv1Error(res.Response.Response, err, false)
	if err != nil {
		return nil, err
	}

	return &HeadBlobOutput{
		BlobItemOutput: adlv1FileStatus2BlobItem(res.FileStatus, &param.Key),
		IsDirBlob:      res.FileStatus.Type == "DIRECTORY",
	}, nil

}

func (b *ADLv1) appendToListResults(path string, recursive bool, startAfter string,
	maxKeys *uint32, prefixes []BlobPrefixOutput, items []BlobItemOutput) (adl.FileStatusesResult, []BlobPrefixOutput, []BlobItemOutput, error) {

	res, err := b.client.ListFileStatus(context.TODO(), b.account, b.path(path),
		nil, "", "", nil)
	err = mapADLv1Error(res.Response.Response, err, false)
	if err != nil {
		return adl.FileStatusesResult{}, nil, nil, err
	}

	if path != "" {
		if len(*res.FileStatuses.FileStatus) == 1 &&
			*(*res.FileStatuses.FileStatus)[0].PathSuffix == "" {
			// path is actually a file
			if !strings.HasSuffix(path, "/") {
				items = append(items,
					adlv1FileStatus2BlobItem(&(*res.FileStatuses.FileStatus)[0], &path))
			}
			return res, prefixes, items, nil
		}

		if !recursive {
			if strings.HasSuffix(path, "/") {
				// we listed for the dir object itself
				items = append(items, BlobItemOutput{
					Key: PString(path),
				})
			} else {
				prefixes = append(prefixes, BlobPrefixOutput{
					PString(path + "/"),
				})
			}
		}
	}

	path = strings.TrimRight(path, "/")

	if maxKeys != nil {
		*maxKeys -= uint32(len(*res.FileStatuses.FileStatus))
	}

	for _, i := range *res.FileStatuses.FileStatus {
		key := *i.PathSuffix
		if path != "" {
			key = path + "/" + key
		}

		if i.Type == "DIRECTORY" {
			if recursive {
				// we shouldn't generate prefixes if
				// it's a recursive listing
				items = append(items,
					adlv1FileStatus2BlobItem(&i, PString(key+"/")))

				_, prefixes, items, err = b.appendToListResults(key,
					recursive, "", maxKeys, prefixes, items)
			} else {
				prefixes = append(prefixes, BlobPrefixOutput{
					Prefix: PString(key + "/"),
				})
			}
		} else {
			items = append(items, adlv1FileStatus2BlobItem(&i, &key))
		}
	}

	return res, prefixes, items, nil
}

func (b *ADLv1) ListBlobs(param *ListBlobsInput) (*ListBlobsOutput, error) {
	var recursive bool
	if param.Delimiter == nil {
		// used by tests to cleanup (and also slurping, but
		// that's only enabled on S3 right now)
		recursive = true
		// cannot emulate these
		if param.ContinuationToken != nil || param.StartAfter != nil {
			return nil, syscall.ENOTSUP
		}
	} else if *param.Delimiter != "/" {
		return nil, syscall.ENOTSUP
	}
	continuationToken := param.ContinuationToken
	if param.StartAfter != nil {
		continuationToken = param.StartAfter
	}

	_, prefixes, items, err := b.appendToListResults(NilStr(param.Prefix),
		recursive, NilStr(continuationToken), param.MaxKeys, nil, nil)
	if err == fuse.ENOENT {
		err = nil
	} else if err != nil {
		return nil, err
	}

	return &ListBlobsOutput{
		Prefixes:    prefixes,
		Items:       items,
		IsTruncated: false,
	}, nil
}

func (b *ADLv1) DeleteBlob(param *DeleteBlobInput) (*DeleteBlobOutput, error) {
	res, err := b.client.Delete(context.TODO(), b.account, b.path(strings.TrimRight(param.Key, "/")), PBool(false))
	err = mapADLv1Error(res.Response.Response, err, false)
	if err != nil {
		return nil, err
	}
	if !*res.OperationResult {
		return nil, fuse.ENOENT
	}
	return &DeleteBlobOutput{}, nil
}

func (b *ADLv1) DeleteBlobs(param *DeleteBlobsInput) (*DeleteBlobsOutput, error) {
	return nil, syscall.ENOTSUP
}

func (b *ADLv1) RenameBlob(param *RenameBlobInput) (*RenameBlobOutput, error) {
	r, err := b.client.RenamePreparer(context.TODO(), b.account, b.path(param.Source),
		b.path(param.Destination))
	err = mapADLv1Error(nil, err, false)
	if err != nil {
		return nil, err
	}

	params := r.URL.Query()
	params.Add("renameoptions", "OVERWRITE")
	r.URL.RawQuery = params.Encode()

	resp, err := b.client.RenameSender(r)
	err = mapADLv1Error(resp, err, false)
	if err != nil {
		return nil, err
	}

	res, err := b.client.RenameResponder(resp)
	err = mapADLv1Error(resp, err, false)
	if err != nil {
		return nil, err
	}

	if !*res.OperationResult {
		// ADLv1 returns false if we try to rename a dir to a
		// file, or if the rename source doesn't exist. We
		// should have prevented renaming a dir to a file at
		// upper layer so this is probably the former

		// (the reverse, renaming a file to a directory works
		// in ADLv1 and is the same as moving the file into
		// the directory)
		return nil, fuse.ENOENT
	}

	return &RenameBlobOutput{}, nil
}

func (b *ADLv1) CopyBlob(param *CopyBlobInput) (*CopyBlobOutput, error) {
	return nil, syscall.ENOTSUP
}

func (b *ADLv1) GetBlob(param *GetBlobInput) (*GetBlobOutput, error) {
	var length *int64
	var offset *int64

	if param.Count != 0 {
		length = PInt64(int64(param.Count))
	}
	if param.Start != 0 {
		offset = PInt64(int64(param.Start))
	}

	var filesessionid *uuid.UUID
	if param.IfMatch != nil {
		b := make([]byte, 16)
		copy(b, []byte(*param.IfMatch))
		u, err := uuid.FromBytes(b)
		if err != nil {
			return nil, err
		}
		filesessionid = &u
	}

	resp, err := b.client.Open(context.TODO(), b.account, b.path(param.Key), length, offset,
		filesessionid)
	err = mapADLv1Error(resp.Response.Response, err, false)
	if err != nil {
		return nil, err
	}
	if resp.Value != nil {
		defer func() {
			if resp.Value != nil {
				(*resp.Value).Close()
			}
		}()
	}
	// WebHDFS specifies that Content-Length is returned but ADLv1
	// doesn't return it. Thankfully we never actually use it in
	// the context of GetBlobOutput

	var contentType *string
	// not very useful since ADLv1 always return application/octet-stream
	if val, ok := resp.Header["Content-Type"]; ok && len(val) != 0 {
		contentType = &val[len(val)-1]
	}

	res := GetBlobOutput{
		HeadBlobOutput: HeadBlobOutput{
			BlobItemOutput: BlobItemOutput{
				Key: &param.Key,
			},
			ContentType: contentType,
			IsDirBlob:   false,
		},
		Body: *resp.Value,
	}
	resp.Value = nil

	return &res, nil
}

func (b *ADLv1) PutBlob(param *PutBlobInput) (*PutBlobOutput, error) {
	if param.DirBlob {
		err := b.mkdir(param.Key)
		if err != nil {
			return nil, err
		}
	} else {
		res, err := b.client.Create(context.TODO(), b.account, b.path(param.Key),
			&ReadSeekerCloser{param.Body}, PBool(true), adl.CLOSE, nil,
			PInt32(int32(b.flags.FileMode)))
		err = mapADLv1Error(res.Response, err, false)
		if err != nil {
			return nil, err
		}
	}

	return &PutBlobOutput{}, nil
}

func (b *ADLv1) MultipartBlobBegin(param *MultipartBlobBeginInput) (*MultipartBlobCommitInput, error) {
	// ADLv1 doesn't have the concept of atomic replacement which
	// means that when we replace an object, readers may see
	// intermediate results. Here we implement MPU by first
	// sending a CREATE with 0 bytes and acquire a lease at the
	// same time.  much of these is not documented anywhere except
	// in the SDKs:
	// https://github.com/Azure/azure-data-lake-store-java/blob/f5c270b8cb2ac68536b2cb123d355a874cade34c/src/main/java/com/microsoft/azure/datalake/store/Core.java#L84
	leaseId, err := uuid.NewV4()
	if err != nil {
		return nil, err
	}

	res, err := b.client.Create(context.TODO(), b.account, b.path(param.Key),
		&ReadSeekerCloser{bytes.NewReader([]byte(""))}, PBool(true), adl.DATA, &leaseId,
		PInt32(int32(b.flags.FileMode)))
	err = mapADLv1Error(res.Response, err, false)
	if err != nil {
		return nil, err
	}

	return &MultipartBlobCommitInput{
		Key:         PString(b.path(param.Key)),
		UploadId:    PString(leaseId.String()),
		backendData: &ADLv1MultipartBlobCommitInput{},
	}, nil
}

func (b *ADLv1) uploadPart(param *MultipartBlobAddInput, offset uint64) error {
	leaseId, err := uuid.FromString(*param.Commit.UploadId)
	if err != nil {
		return err
	}

	res, err := b.client.Append(context.TODO(), b.account, *param.Commit.Key,
		&ReadSeekerCloser{param.Body}, PInt64(int64(offset-param.Size)), adl.DATA,
		&leaseId, &leaseId)
	err = mapADLv1Error(res.Response, err, true)
	if err != nil {
		if adlErr, ok := err.(ADLv1Err); ok {
			if adlErr.resp.StatusCode == 404 {
				// ADLv1 APPEND returns 404 if either:
				// the request payload is too large:
				// https://social.msdn.microsoft.com/Forums/azure/en-US/48e86ce8-79f8-4412-838f-8e2a60b5f387/notfound-error-on-call-to-data-lake-store-create?forum=AzureDataLake

				// or if a second concurrent stream is
				// created. The behavior is odd: seems
				// like the first stream will error
				// but the latter stream works fine
				err = fuse.EINVAL
				return err
			} else if adlErr.resp.StatusCode == 400 &&
				adlErr.RemoteException.Exception == "BadOffsetException" {
				appendErr := b.detectTransientError(param, offset)
				if appendErr == nil {
					return nil
				}
			}
			err = mapADLv1Error(adlErr.resp, err, false)
		}
	}
	return err
}

func (b *ADLv1) detectTransientError(param *MultipartBlobAddInput, offset uint64) error {
	leaseId, err := uuid.FromString(*param.Commit.UploadId)
	if err != nil {
		return err
	}
	res, err := b.client.Append(context.TODO(), b.account, *param.Commit.Key,
		&ReadSeekerCloser{bytes.NewReader([]byte(""))},
		PInt64(int64(offset)), adl.CLOSE, &leaseId, &leaseId)
	err = mapADLv1Error(res.Response, err, false)
	return err
}

func (b *ADLv1) MultipartBlobAdd(param *MultipartBlobAddInput) (*MultipartBlobAddOutput, error) {
	// APPEND with the expected offsets (so we can detect
	// concurrent updates to the same file and fail, in case lease
	// is for some reason broken on the server side

	var commitData *ADLv1MultipartBlobCommitInput
	var ok bool
	if commitData, ok = param.Commit.backendData.(*ADLv1MultipartBlobCommitInput); !ok {
		panic("Incorrect commit data type")
	}

	commitData.Size += param.Size
	err := b.uploadPart(param, commitData.Size)
	if err != nil {
		return nil, err
	}

	return &MultipartBlobAddOutput{}, nil
}

func (b *ADLv1) MultipartBlobAbort(param *MultipartBlobCommitInput) (*MultipartBlobAbortOutput, error) {
	// there's no such thing as abort, but at least we should release the lease
	// which technically is more like a commit than abort
	leaseId, err := uuid.FromString(*param.UploadId)
	if err != nil {
		return nil, err
	}
	res, err := b.client.Append(context.TODO(), b.account, *param.Key,
		&ReadSeekerCloser{bytes.NewReader([]byte(""))}, nil, adl.CLOSE, &leaseId, &leaseId)
	err = mapADLv1Error(res.Response, err, false)
	if err != nil {
		return nil, err
	}

	return &MultipartBlobAbortOutput{}, err
}

func (b *ADLv1) MultipartBlobCommit(param *MultipartBlobCommitInput) (*MultipartBlobCommitOutput, error) {
	var commitData *ADLv1MultipartBlobCommitInput
	var ok bool
	if commitData, ok = param.backendData.(*ADLv1MultipartBlobCommitInput); !ok {
		panic("Incorrect commit data type")
	}

	leaseId, err := uuid.FromString(*param.UploadId)
	if err != nil {
		return nil, err
	}
	res, err := b.client.Append(context.TODO(), b.account, *param.Key,
		&ReadSeekerCloser{bytes.NewReader([]byte(""))}, PInt64(int64(commitData.Size)),
		adl.CLOSE, &leaseId, &leaseId)
	err = mapADLv1Error(res.Response, err, false)
	if err == fuse.ENOENT {
		// either the blob was concurrently deleted or we got
		// another CREATE which broke our lease. Either way
		// technically we did finish uploading data so swallow
		// the error
		err = nil
	}
	if err != nil {
		return nil, err
	}

	return &MultipartBlobCommitOutput{}, nil
}

func (b *ADLv1) MultipartExpire(param *MultipartExpireInput) (*MultipartExpireOutput, error) {
	return nil, syscall.ENOTSUP
}

func (b *ADLv1) RemoveBucket(param *RemoveBucketInput) (*RemoveBucketOutput, error) {
	if b.bucket == "" {
		return nil, fuse.EINVAL
	}

	res, err := b.client.Delete(context.TODO(), b.account, b.path(""), PBool(false))
	err = mapADLv1Error(res.Response.Response, err, false)
	if err != nil {
		return nil, err
	}
	if !*res.OperationResult {
		return nil, fuse.ENOENT
	}

	return &RemoveBucketOutput{}, nil
}

func (b *ADLv1) MakeBucket(param *MakeBucketInput) (*MakeBucketOutput, error) {
	if b.bucket == "" {
		return nil, fuse.EINVAL
	}

	err := b.mkdir("")
	if err != nil {
		return nil, err
	}

	return &MakeBucketOutput{}, nil
}

func (b *ADLv1) mkdir(dir string) error {
	res, err := b.client.Mkdirs(context.TODO(), b.account, b.path(dir),
		PInt32(int32(b.flags.DirMode)))
	err = mapADLv1Error(res.Response.Response, err, true)
	if err != nil {
		return err
	}
	if !*res.OperationResult {
		return fuse.EEXIST
	}
	return nil
}


text:
int main(int argc, char * argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([JCAppDelegate class]));
    }
}

redpajama_set_name: RedPajamaGithub


text:
package Feature::CosineSimilarity;

use strict;
use warnings;

use Moose;
use namespace::autoclean;

# TODO : how can we reduce redundancy with Feature::ModalitySimilarity ?

# To be removed once I've confirmed that this feature is indeed properly covered here
### # (Non-Native) Target frequency
### push @edge_features, new WordGraph::EdgeFeature::NodeFrequency( id => $Web::Summarizer::Graph2::Definitions::FEATURE_FREQUENCY , modalities => $this->modalities_fluent );

# id
has 'id' => ( is => 'ro' , isa => 'Str' , init_arg => undef , lazy => 1 , builder => '_id_builder' );
sub _id_builder {
    my $this = shift;
    return 'cosine-similarity';
}

with 'Feature::ReferenceTargetFeature' => { type => 'Web::Summarizer::Sentence' };

# compute
# TODO: how can we define required abstract methods uing Moose ? ==> parent class
# TODO: add triggers on objects to recompute only when needed
sub compute {

    my $this = shift;
    my $sequence1 = shift;
    my $sequence2 = shift;

    # TODO : turn this into an attribute
    my $order = 1;

    # 1 - get vector for object 1
    my $vector_1 = $sequence1->get_ngrams( $order , 1 );

    # 2 - get vector for object 2
    my $vector_2 = $sequence2->get_ngrams( $order , 1 );

    # 3 - compute similarity
    # TODO: make similarity function a parameterizable attribute
    my $similarity = Vector::cosine( $vector_1 , $vector_2 );

    my $feature_key = $this->id ;

    return { $feature_key => $similarity };

}

__PACKAGE__->meta->make_immutable;

1;


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vista;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.view.JasperViewer;
import util.Globales;

/**
 *
 * @author PabloAntonio
 */
public class RepEstudiantesIF extends javax.swing.JInternalFrame {
    public Connection conn;
    JasperReport reporte;
    JasperPrint jasperprint;
    JasperViewer visor;
    /**
     * Creates new form repEstudianteIF
     */
    public RepEstudiantesIF() {
        initComponents();
    }
public void reporteEstudianteDetalle() {
        try {
            Class.forName("org.sqlite.JDBC"); //driver a utilizar
            conn=DriverManager.getConnection("jdbc:sqlite:cnae.sqlite");

            Map<String,Object> parametros = new HashMap<String,Object>();
            parametros.put("idAsig", Globales.id);

            JOptionPane.showMessageDialog(null, "El valor de idasig: " + parametros);

            reporte = (JasperReport) JRLoader.loadObjectFromFile("src/reportes/repEstudianteDetalle.jasper");
            jasperprint = JasperFillManager.fillReport(reporte, parametros, conn);
            visor = new JasperViewer(jasperprint,false);
            visor.setTitle("Estudiante - CNAE");
            visor.setVisible(true);
        } catch (JRException | ClassNotFoundException | SQLException e) {
            JOptionPane.showMessageDialog(null, "Error en Reporte EstudianteDetalle: " + e.getMessage());
        } finally {
            try {
                conn.close();
            } catch (SQLException ex) {
                Logger.getLogger(RepEstudiantesIF.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void reporteEstudiante() {
        try {
            Class.forName("org.sqlite.JDBC"); //driver a utilizar
            conn=DriverManager.getConnection("jdbc:sqlite:cnae.sqlite");

            Map<String,Object> parametros = new HashMap<String,Object>();
            parametros.put("idAsig", Globales.id);
            JOptionPane.showMessageDialog(null, "El valor de idasig: " + parametros);

            reporte = (JasperReport) JRLoader.loadObjectFromFile("src/reportes/repEstudiante.jasper");
            jasperprint = JasperFillManager.fillReport(reporte, parametros, conn);
            visor = new JasperViewer(jasperprint,false);
            visor.setTitle("Estudiante - CNAE");
            visor.setVisible(true);
        } catch (JRException | ClassNotFoundException | SQLException e) {
            JOptionPane.showMessageDialog(null, "Error en Reporte EstudianteLista: " + e.getMessage());
        } finally {
            try {
                conn.close();
            } catch (SQLException ex) {
                Logger.getLogger(RepEstudiantesIF.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jButton1 = new javax.swing.JButton();
        btnEjecutar = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        rbDetalle = new javax.swing.JRadioButton();
        rbListado = new javax.swing.JRadioButton();

        setTitle("Reporte de Estudiante"); // NOI18N

        jButton1.setText("Salir");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        btnEjecutar.setText("Ejecutar");
        btnEjecutar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEjecutarActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Estudiantes"));

        buttonGroup1.add(rbDetalle);
        rbDetalle.setText("Detalle");
        rbDetalle.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rbDetalleActionPerformed(evt);
            }
        });

        buttonGroup1.add(rbListado);
        rbListado.setText("Listado");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(rbListado)
                .addGap(59, 59, 59)
                .addComponent(rbDetalle)
                .addGap(112, 112, 112))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(46, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(rbListado)
                    .addComponent(rbDetalle))
                .addGap(28, 28, 28))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(108, 108, 108)
                .addComponent(btnEjecutar, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(28, 28, 28)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(117, Short.MAX_VALUE))
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addComponent(btnEjecutar))
                .addContainerGap(17, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        int i = JOptionPane.showConfirmDialog(null, "Desea Salir del Informe?","Confirmar",
                JOptionPane.OK_CANCEL_OPTION,JOptionPane.ERROR_MESSAGE);
        if(i==JOptionPane.OK_OPTION){
            this.doDefaultCloseAction();
        }
}//GEN-LAST:event_jButton1ActionPerformed

    private void btnEjecutarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEjecutarActionPerformed

        if(rbDetalle.isSelected()==true){
            this.reporteEstudianteDetalle();

        } else if (rbListado.isSelected()==true){
            this.reporteEstudiante();
       }

}//GEN-LAST:event_btnEjecutarActionPerformed

    private void rbDetalleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbDetalleActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_rbDetalleActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnEjecutar;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JRadioButton rbDetalle;
    private javax.swing.JRadioButton rbListado;
    // End of variables declaration//GEN-END:variables
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.example"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="14" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />

    <application
        android:name="com.example.example.ExampleApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.example.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:theme="@android:style/Theme.Holo.NoActionBar"
            android:name="com.zhaojian.jolly.selectphotos.DisplyImageActivity" >
            <action android:name="android.intent.action.MEDIA_MOUNTED" />
            <action android:name="android.intent.action.MEDIA_EJECT" />
            <data android:scheme="file" />
        </activity>
        <activity
            android:theme="@android:style/Theme.Black.NoTitleBar"
            android:name="com.zhaojian.jolly.selectphotos.PhotoViewerActivity" >
            <action android:name="android.intent.action.MEDIA_MOUNTED" />
            <action android:name="android.intent.action.MEDIA_EJECT" />
            <data android:scheme="file" />
        </activity>
    </application>

</manifest>


text:
"""Module for supporting Google Vertex AI Custom Training Job Op."""

# Prior to release of kfp V2, we have to use a mix of kfp v1 and v2.
# TODO(chavoshi): switch to using V2 only once it is ready.
import copy
import json
import tempfile
from typing import Callable, Dict, Optional, Sequence

from google_cloud_pipeline_components.aiplatform import utils
from kfp import components
from kfp.components import structures
from kfp.dsl import dsl_utils
from kfp.v2.components.types import type_utils

_DEFAULT_CUSTOM_JOB_CONTAINER_IMAGE = utils.DEFAULT_CONTAINER_IMAGE
# Executor replacement is used as executor content needs to be jsonified before
# injection into the payload, since payload is already a Json serialized string.
_EXECUTOR_PLACE_HOLDER_REPLACEMENT = '{{$.json_escape[1]}}'

def create_custom_training_job_op_from_component(
    component_spec: Callable,  # pylint: disable=g-bare-generic
    display_name: Optional[str] = '',
    replica_count: Optional[int] = 1,
    machine_type: Optional[str] = 'n1-standard-4',
    accelerator_type: Optional[str] = '',
    accelerator_count: Optional[int] = 1,
    boot_disk_type: Optional[str] = 'pd-ssd',
    boot_disk_size_gb: Optional[int] = 100,
    timeout: Optional[str] = '',
    restart_job_on_worker_restart: Optional[bool] = False,
    service_account: Optional[str] = '',
    network: Optional[str] = '',
    encryption_spec_key_name: Optional[str] = '',
    tensorboard: Optional[str] = '',
    enable_web_access: Optional[bool] = False,
    reserved_ip_ranges: Optional[Sequence[str]] = [],
    base_output_directory: Optional[str] = '',
    labels: Optional[Dict[str, str]] = None,
) -> Callable:  # pylint: disable=g-bare-generic
  """Create a component spec that runs a custom training in Vertex AI.

  This utility converts a given component to a CustomTrainingJobOp that runs a
  custom training in Vertex AI. This simplifies the creation of custom training
  jobs. All Inputs and Outputs of the supplied component will be copied over to
  the constructed training job.

  Note that this utility constructs a ClusterSpec where the master and all the
  workers use the same spec, meaning all disk/machine spec related parameters
  will apply to all replicas. This is suitable for use cases such as training
  with MultiWorkerMirroredStrategy or Mirrored Strategy.

  This component does not support Vertex AI Python training application.

  For more details on Vertex AI Training service, please refer to
  https://cloud.google.com/vertex-ai/docs/training/create-custom-job

  Args:
    component_spec: The task (ContainerOp) object to run as Vertex AI custom
      job.
    display_name (Optional[str]): The name of the custom job. If not provided
      the component_spec.name will be used instead.
    replica_count (Optional[int]): The count of instances in the cluster. One
      replica always counts towards the master in worker_pool_spec[0] and the
      remaining replicas will be allocated in worker_pool_spec[1]. For more
      details see
      https://cloud.google.com/vertex-ai/docs/training/distributed-training#configure_a_distributed_training_job.
    machine_type (Optional[str]): The type of the machine to run the custom job.
      The default value is "n1-standard-4".  For more details about this input
      config, see
      https://cloud.google.com/vertex-ai/docs/training/configure-compute#machine-types.
    accelerator_type (Optional[str]): The type of accelerator(s) that may be
      attached to the machine as per accelerator_count.  For more details about
      this input config, see
      https://cloud.google.com/vertex-ai/docs/reference/rest/v1/MachineSpec#acceleratortype.
    accelerator_count (Optional[int]): The number of accelerators to attach to
      the machine. Defaults to 1 if accelerator_type is set.
    boot_disk_type (Optional[str]):
      Type of the boot disk (default is "pd-ssd"). Valid values: "pd-ssd"
        (Persistent Disk Solid State Drive) or "pd-standard" (Persistent Disk
        Hard Disk Drive).
    boot_disk_size_gb (Optional[int]): Size in GB of the boot disk (default is
      100GB).
    timeout (Optional[str]): The maximum job running time. The default is 7
      days. A duration in seconds with up to nine fractional digits, terminated
      by 's', for example: "3.5s".
    restart_job_on_worker_restart (Optional[bool]): Restarts the entire
      CustomJob if a worker gets restarted. This feature can be used by
      distributed training jobs that are not resilient to workers leaving and
      joining a job.
    service_account (Optional[str]): Sets the default service account for
      workload run-as account. The service account running the pipeline
        (https://cloud.google.com/vertex-ai/docs/pipelines/configure-project#service-account)
          submitting jobs must have act-as permission on this run-as account. If
          unspecified, the Vertex AI Custom Code Service
        Agent(https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents)
          for the CustomJob's project.
    network (Optional[str]): The full name of the Compute Engine network to
      which the job should be peered. For example,
      projects/12345/global/networks/myVPC. Format is of the form
      projects/{project}/global/networks/{network}. Where {project} is a project
      number, as in 12345, and {network} is a network name. Private services
      access must already be configured for the network. If left unspecified,
      the job is not peered with any network.
    reserved_ip_ranges (Optional[Sequence[str]]): A list of names for the
      reserved ip ranges under the VPC network that can be used for this job. If
      set, we will deploy the job within the provided ip ranges. Otherwise, the
      job will be deployed to any ip ranges under the provided VPC network.
    encryption_spec_key_name (Optional[str]): Customer-managed encryption key
      options for the CustomJob. If this is set, then all resources created by
      the CustomJob will be encrypted with the provided encryption key.
    tensorboard (Optional[str]): The name of a Vertex AI Tensorboard resource to
      which this CustomJob will upload Tensorboard logs.
    enable_web_access (Optional[bool]): Whether you want Vertex AI to enable
      [interactive shell access](https://cloud.google.com/vertex-ai/docs/training/monitor-debug-interactive-shell)
      to training containers.
      If set to `true`, you can access interactive shells at the URIs given
      by [CustomJob.web_access_uris][].
    base_output_directory (Optional[str]): The Cloud Storage location to store
      the output of this CustomJob or
      HyperparameterTuningJob. see below for more details:
      https://cloud.google.com/vertex-ai/docs/reference/rest/v1/GcsDestination
    labels (Optional[Dict[str, str]]): The labels with user-defined metadata to
      organize CustomJobs.
      See https://goo.gl/xmQnxf for more information.

  Returns:
    A Custom Job component operator corresponding to the input component
    operator.

  """
  job_spec = {}
  input_specs = []
  output_specs = []

  # pytype: disable=attribute-error

  if component_spec.component_spec.inputs:
    input_specs = component_spec.component_spec.inputs
  if component_spec.component_spec.outputs:
    output_specs = component_spec.component_spec.outputs

  def _is_output_parameter(output_key: str) -> bool:
    for output in component_spec.component_spec.outputs:
      if output.name == output_key:
        return type_utils.is_parameter_type(output.type)
    return False

  worker_pool_spec = {
      'machine_spec': {
          'machine_type': machine_type
      },
      'replica_count': 1,
      'container_spec': {
          'image_uri':
              component_spec.component_spec.implementation.container.image,
      }
  }
  if component_spec.component_spec.implementation.container.command:
    container_command_copy = component_spec.component_spec.implementation.container.command.copy(
    )
    dsl_utils.resolve_cmd_lines(container_command_copy, _is_output_parameter)
    # Replace executor place holder with the json escaped placeholder.
    for idx, val in enumerate(container_command_copy):
      if val == '{{{{$}}}}':
        container_command_copy[idx] = _EXECUTOR_PLACE_HOLDER_REPLACEMENT
    worker_pool_spec['container_spec']['command'] = container_command_copy

  if component_spec.component_spec.implementation.container.args:
    container_args_copy = component_spec.component_spec.implementation.container.args.copy(
    )
    dsl_utils.resolve_cmd_lines(container_args_copy, _is_output_parameter)
    # Replace executor place holder with the json escaped placeholder.
    for idx, val in enumerate(container_args_copy):
      if val == '{{{{$}}}}':
        container_args_copy[idx] = _EXECUTOR_PLACE_HOLDER_REPLACEMENT
    worker_pool_spec['container_spec']['args'] = container_args_copy
  if accelerator_type:
    worker_pool_spec['machine_spec']['accelerator_type'] = accelerator_type
    worker_pool_spec['machine_spec']['accelerator_count'] = accelerator_count
  if boot_disk_type:
    if 'disk_spec' not in worker_pool_spec:
      worker_pool_spec['disk_spec'] = {}
    worker_pool_spec['disk_spec']['boot_disk_type'] = boot_disk_type
    if 'disk_spec' not in worker_pool_spec:
      worker_pool_spec['disk_spec'] = {}
    worker_pool_spec['disk_spec']['boot_disk_size_gb'] = boot_disk_size_gb

  job_spec['worker_pool_specs'] = [worker_pool_spec]
  if int(replica_count) > 1:
    additional_worker_pool_spec = copy.deepcopy(worker_pool_spec)
    additional_worker_pool_spec['replica_count'] = str(replica_count - 1)
    job_spec['worker_pool_specs'].append(additional_worker_pool_spec)

  # TODO(chavoshi): Use input parameter instead of hard coded string label.
  # This requires Dictionary input type to be supported in V2.
  if labels is not None:
    job_spec['labels'] = labels

  if timeout:
    if 'scheduling' not in job_spec:
      job_spec['scheduling'] = {}
    job_spec['scheduling']['timeout'] = timeout
  if restart_job_on_worker_restart:
    if 'scheduling' not in job_spec:
      job_spec['scheduling'] = {}
    job_spec['scheduling'][
        'restart_job_on_worker_restart'] = restart_job_on_worker_restart
  if enable_web_access:
    job_spec['enable_web_access'] = enable_web_access
  if reserved_ip_ranges:
    job_spec['reserved_ip_ranges'] = reserved_ip_ranges
  if encryption_spec_key_name:
    job_spec['encryption_spec'] = {}
    job_spec['encryption_spec'][
        'kms_key_name'] = "{{$.inputs.parameters['encryption_spec_key_name']}}"
    input_specs.append(
        structures.InputSpec(
            name='encryption_spec_key_name',
            type='String',
            optional=True,
            default=encryption_spec_key_name),)

  # Remove any existing service_account from component input list.
  input_specs[:] = [
      input_spec for input_spec in input_specs
      if input_spec.name not in ('service_account', 'network', 'tensorboard',
                                 'base_output_directory')
  ]
  job_spec['service_account'] = "{{$.inputs.parameters['service_account']}}"
  job_spec['network'] = "{{$.inputs.parameters['network']}}"

  job_spec['tensorboard'] = "{{$.inputs.parameters['tensorboard']}}"
  job_spec['base_output_directory'] = {}
  job_spec['base_output_directory'][
      'output_uri_prefix'] = "{{$.inputs.parameters['base_output_directory']}}"
  custom_job_payload = {
      'display_name': display_name or component_spec.component_spec.name,
      'job_spec': job_spec
  }

  custom_job_component_spec = structures.ComponentSpec(
      name=component_spec.component_spec.name,
      inputs=input_specs + [
          structures.InputSpec(
              name='base_output_directory',
              type='String',
              optional=True,
              default=base_output_directory),
          structures.InputSpec(
              name='tensorboard',
              type='String',
              optional=True,
              default=tensorboard),
          structures.InputSpec(
              name='network', type='String', optional=True, default=network),
          structures.InputSpec(
              name='service_account',
              type='String',
              optional=True,
              default=service_account),
          structures.InputSpec(name='project', type='String'),
          structures.InputSpec(name='location', type='String')
      ],
      outputs=output_specs +
      [structures.OutputSpec(name='gcp_resources', type='String')],
      implementation=structures.ContainerImplementation(
          container=structures.ContainerSpec(
              image=_DEFAULT_CUSTOM_JOB_CONTAINER_IMAGE,
              command=[
                  'python3', '-u', '-m',
                  'google_cloud_pipeline_components.container.v1.custom_job.launcher'
              ],
              args=[
                  '--type',
                  'CustomJob',
                  '--payload',
                  json.dumps(custom_job_payload),
                  '--project',
                  structures.InputValuePlaceholder(input_name='project'),
                  '--location',
                  structures.InputValuePlaceholder(input_name='location'),
                  '--gcp_resources',
                  structures.OutputPathPlaceholder(output_name='gcp_resources'),
              ],
          )))

  # pytype: enable=attribute-error

  component_path = tempfile.mktemp()
  custom_job_component_spec.save(component_path)
  return components.load_component_from_file(component_path)


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>io.permazen.kv.xodus (Permazen 4.1.6 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package io.permazen.kv.xodus

KVDatabase implementation based on Xodus.

See: Description

Class Summary

Class
Description

XodusKVDatabase

KVDatabase view of an Xodus database.

XodusKVImplementation

XodusKVImplementation.Config

XodusKVStore

Straightforward KVStore view of a Xodus Store viewed within an open Transaction.

XodusKVTransaction

XodusKVDatabase transaction.

Enum Summary

Enum
Description

TransactionType

Xodus transaction types.

Package io.permazen.kv.xodus Description

KVDatabase implementation based on Xodus.

See Also:

XodusKVDatabase,
Xodus

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Copyright © 2020. All rights reserved.


text:
<?php
namespace paslandau\ArrayUtility\ArrayPath;

interface ArraySelectorInterface {

    /**
     * Gets the element specified by $path.
     * @param ArrayPathInterface $path
     * @return mixed
     */
    public function getElement(ArrayPathInterface $path);

    /**
     * Set $value at the position specified by $path.
     * @param ArrayPathInterface $path
     * @param mixed $value
     * @return void
     */
    public function setElement(ArrayPathInterface $path, $value);

    /**
     * Merges $value with the element specified by $path.
     * @param ArrayPathInterface $path
     * @param mixed $value
     * @param ArrayMergingStrategyInterface $mergingStrategy
     * @return void
     */
    public function merge(ArrayPathInterface $path, $value, ArrayMergingStrategyInterface $mergingStrategy);

    /**
     * Returns the array
     * @return array
     */
    public function getArray();
}


text:
class MonsterRival : public Rival
{
public:
	MonsterRival(Ogre::SceneNode* node, Ogre::Entity* ent, Ogre::String& combatSceneName, const MonsterInfo* pMonsterInfo, int posNum);
	~MonsterRival(void);
protected:
	virtual void KillRival();
private:
	int m_iPosNum;
	const MonsterInfo* m_pMonsterInfo;
};

#endif


text:
////////////////////////////////////////////////////////////////////////////////////
///
///  \file setglobalpose.h
///  \brief This file contains the implementation of a JAUS message.
///
///
Author(s): Bo Sun
///
Created: 3 December 2009
///
Copyright (c) 2009
///
Applied Cognition and Training in Immersive Virtual Environments
///
(ACTIVE) Laboratory
///
Institute for Simulation and Training (IST)
///
University of Central Florida (UCF)
///
All rights reserved.
///
Email: bsun@ist.ucf.edu
///
Web:  http://active.ist.ucf.edu
///
///  Redistribution and use in source and binary forms, with or without
///  modification, are permitted provided that the following conditions are met:
///      * Redistributions of source code must retain the above copyright
///        notice, this list of conditions and the following disclaimer.
///      * Redistributions in binary form must reproduce the above copyright
///        notice, this list of conditions and the following disclaimer in the
///        documentation and/or other materials provided with the distribution.
///      * Neither the name of the ACTIVE LAB, IST, UCF, nor the
///        names of its contributors may be used to endorse or promote products
///        derived from this software without specific prior written permission.
///
///  THIS SOFTWARE IS PROVIDED BY THE ACTIVE LAB''AS IS'' AND ANY
///  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
///  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
///  DISCLAIMED. IN NO EVENT SHALL UCF BE LIABLE FOR ANY
///  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
///  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
///  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
///  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
///  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
///  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
///
////////////////////////////////////////////////////////////////////////////////////
#ifndef __JAUS_MOBILITY_SET_GLOBAL_POSE__H
#define __JAUS_MOBILITY_SET_GLOBAL_POSE__H

#include <cxutils/math/coordinates.h>
#include "jaus/core/message.h"
#include "jaus/mobility/mobilitycodes.h"

namespace JAUS
{
    ////////////////////////////////////////////////////////////////////////////////////
    ///
    ///   \class SetGlobalPose
    ///   \brief This message is used to set the global pose values.
    ///
    ////////////////////////////////////////////////////////////////////////////////////
    class JAUS_MOBILITY_DLL SetGlobalPose : public Message
    {
    public:
        ////////////////////////////////////////////////////////////////////////////////////
        ///
        ///   \class PresenceVector
        ///   \brief This class contains bit masks for bitwise operations on the
        ///          presence vector for this message.
        ///
        ////////////////////////////////////////////////////////////////////////////////////
        class JAUS_MOBILITY_DLL PresenceVector : public JAUS::PresenceVector
        {
        public:
            const static UShort Latitude = 0x0001;      ///< Presence of the Lattitude field
            const static UShort Longitude = 0x0002;     ///< Presence of the Longitude field
            const static UShort Altitude = 0x0004;      ///< Presence of the Altitude field
            const static UShort PositionRMS = 0x0008;   ///< Presence of the PositionRMS field
            const static UShort Roll = 0x0010;          ///< Presence of the Roll field
            const static UShort Pitch = 0x0020;         ///< Presence of the Pitch field
            const static UShort Yaw = 0x0040;           ///< Presence of the Yaw field
            const static UShort AttitudeRMS = 0x0080;   ///< Presence of the AttitudeRMS field
            const static UShort TimeStamp = 0x0100;     ///< Presence of the Timestamp field
        };
        ////////////////////////////////////////////////////////////////////////////////////
        ///
        ///   \class Limits
        ///   \brief Contains constants for limit values of data members of class.
        ///
        ////////////////////////////////////////////////////////////////////////////////////
        class JAUS_MOBILITY_DLL Limits : public JAUS::Limits
        {
        public:
            const static double MinLatitude;            ///<  Minimum latitude. (-90)
            const static double MaxLatitude;            ///<  Maximum latitude. (90)
            const static double MinLongitude;           ///<  Minimum longitude. (-180)
            const static double MaxLongitude;           ///<  Maximum longitude. (180)
            const static double MinElevation;           ///<  Minimum altitude. (-10000)
            const static double MaxElevation;           ///<  Maximum altitude. (35000)
            const static double MinPositionRMS;         ///<  Minimum position RMS (0)
            const static double MaxPositionRMS;         ///<  Maximum position RMS (100)
            const static double MinAngle;               ///<  Minimum angle value in radians. (-PI)
            const static double MaxAngle;               ///<  Maximum angle value in radians. (PI)
            const static double MinAttitudeRMS;         ///<  Minimum attitude RMS in radians. (0)
            const static double MaxAttitudeRMS;         ///<  Maximum attitude RMS in radians. (PI)
        };
        SetGlobalPose(const Address& dest = Address(), const Address& src = Address());
        SetGlobalPose(const SetGlobalPose& message);
        ~SetGlobalPose();
        bool SetLatitude(const double degrees);
        bool SetLongitude(const double degrees);
        bool SetAltitude(const double value);
        bool SetPositionRMS(const double value);
        bool SetRoll(const double radians);
        bool SetPitch(const double radians);
        bool SetYaw(const double radians);
        bool SetAttitudeRMS(const double radians);
        bool SetTimeStamp(const Time& time);
        bool SetPose(const Wgs& position,
                     const Point3D& orientation,
                     const Time& time = Time(true));
        bool SetPosition(const Wgs& position, const Time& time = Time(true));
        bool SetOrientation(const Point3D& orientation, const Time& time = Time(true));
        inline double GetLatitude() const { return mLatitude; }
        inline double GetLongitude() const { return mLongitude; }
        inline double GetAltitude() const { return mAltitude; }
        inline double GetPositionRMS() const { return mPositionRMS; }
        inline double GetRoll() const { return mRoll; }
        inline double GetPitch() const { return mPitch; }
        inline double GetYaw() const { return mYaw; }
        inline double GetAttitudeRMS() const { return mAttitudeRMS; }
        inline Time GetTimeStamp() const { return mTimeStamp; }
        Wgs GetPosition() const;
        Point3D GetOrientation() const;
        virtual bool IsCommand() const { return true; }
        virtual int WriteMessageBody(Packet& packet) const;
        virtual int ReadMessageBody(const Packet& packet);
        virtual Message* Clone() const { return new SetGlobalPose(*this); }
        virtual UInt GetPresenceVector() const { return mPresenceVector; }
        virtual UInt GetPresenceVectorSize() const { return USHORT_SIZE; }
        virtual UInt GetPresenceVectorMask() const { return 0x01FF; }
        virtual UShort GetMessageCodeOfResponse() const { return 0; }
        virtual std::string GetMessageName() const { return "Set Global Pose"; }
        virtual void ClearMessageBody();
        virtual bool IsLargeDataSet(const unsigned int maxPayloadSize = 1437) const { return false; }
        virtual int RunTestCase() const;
        SetGlobalPose& operator=(const SetGlobalPose& message);
    protected:
        UShort mPresenceVector;                 ///<  Bit vector for fields present.
        double mLatitude;                       ///<  Latitude in degrees [-90, 90].
        double mLongitude;                      ///<  Longitude in degrees [-180, 180].
        double mAltitude;                       ///<  Altitude in meters [-10000, 35000].
        double mPositionRMS;                    ///<  Position RMS value in meters [0, 100].
        double mRoll;                           ///<  Roll in radians [-PI, PI].
        double mPitch;                          ///<  Pitch in radians [-PI, PI].
        double mYaw;                            ///<  Yaw in radians [-PI, PI].
        double mAttitudeRMS;                    ///<  Attitude RMS value in Radians [0, PI].
        Time mTimeStamp;                        ///<  TimeStamp, a tuple in (ms,sec,min,hour,day)

    };
}

#endif
/*  End of File */


text:
namespace syncer {

NonBlockingTypeProcessorCoreInterface::NonBlockingTypeProcessorCoreInterface() {
}

NonBlockingTypeProcessorCoreInterface::
    ~NonBlockingTypeProcessorCoreInterface() {
}

}  // namespace syncer


text:
"I'm a useful engine." -- Thomas the Tank Engine

This is a collection of little shell scripts that I've written over the years. I never attempted to make them portable to different shells, so many will only work in bash. If you like one, and make it work in a different shell, please don't break it in bash and submit a pull request. My initials are "wws"; hence the repository name.

All the script files named below are in the `bin` sub-directory of this one.

## delfasls

Useful to lispers. Deletes all fasl files in the current directory or any of its subdirectories, whether they're actually in this directory or they're in the sub-directory of ~/.cache into which ASDF will store them by default. This will force ASDF (or Quicklisp) to recompile the corresponding source files.

Does NOT delete fasls from any directory named `quicklisp`, since you rarely want to force those to recompile. If you DO want to do that, `cd` into the `quicklisp` directory first:

```
cd ~/quicklisp
delfasls
```

## ip

If you're behind multiple routers, or you want to be sure that you're connected through a VPN, it can be useful to ask a remote web server what your IP address looks like to it. This script queries `http://billstclair.com/cgi-bin/ip.sh` for that. The `ip.sh` script is in the `aux` sub-directory here, in case you want to put it on your own web site instead of using mine. There's also an alternative, `ip.php`, if that's easier for you.

The `ip` script echoes "expecting xx.xx.xx.xx". If you want to remind yourself of what your IP should be when you're connected through a VPN provider, you can change that to the actual IP you expect. Or just comment out the line.

## rsyncit

Before the advent of `git`, I used to keep directories on my local machine in sync with web servers using `rsync`. I still do for image files. The problem was that I had to remember the `username@hostname:/path/to/webserver/directory` for a bunch of different sites. `rsyncit` allows you to put a `.sshdir` script in each directory you want to mirror somewhere. That script is responsible for echoing `username@hostname:/path/to/webserver/directory`. `rsyncit` calls `./.sshdir` and puts it in the right place for `rsync`.

If you give no arguments to `rsyncit`, it will sync the entire directory:

```
cd /local/path/to/webserver/images/dir
rsyncit
```

If you give arguments to `rsyncit` it will pass them to `rsync` with the output of the `./.sshdir` script added to the end:

```
rsyncit -av sunset-151002.jpg
```

There's a sample `.sshdir` script in the `aux` directory. Copy it to directories you want to sync, and change what it echoes appropriately.

## scpit

Like `rsyncit`, but uses `scp` to do the copying, instead of `rsync`. Uses the same `.sshdir` file to specify the remote location.

```
cd /local/path/to/webserver/images/dir
scpit sunset-151002.jpg
```

## xfiles

```
xfiles <pattern> <command> <arg> ...
```

is the same as:

```
find . -name "<pattern>" -print0 | xargs -0 <command> <arg> ...
```

`erlfiles` passes `*.erl` as the pattern.
`elmfiles` passes `*.elm` as the pattern.
 Make your own.

## lispfiles

```
lispfiles <arg> ...
```

is the same as:

```
find . -not -regex "\./quicklisp/.*" -and -name "*.lisp" -print0 | xargs -0 <arg> ...
```

I usually use it to grep source code:

```
lispfiles fgrep defpackage
```

`lispfiles` will NOT descend into a sub-directory named `quicklisp`, since you usually want to search YOUR code, not other people's libraries. You can `cd quicklisp` to find code there (unless you want to find code in `quicklisp/quicklisp`, in which case you'll need ANOTHER `cd quicklisp`).

## git-x-files

Like `xfiles`, but uses `git ls-files` for the full list, then filters it
with the first parameter, then pipes it through `xargs` and adds the rest of the parameters

`git-elm-files` and `git-js-files` use it.

## git-x-files-wc

Same as `git-x-files "$1" wc-l`

Useful to count lines in files of a partilar type in a git repository.

`git-elm-files-wc` and `git-js-files-wc` use it.

## git-x-files-wc-total

Same as `git-x-files-wc`, but prints only the total line at the end, not the individual files:

```
git-x-files-wc "$1" wc -l | grep total
```

`git-elm-files-wc-total` and `git-js-files-wc-total` use it.

## kerl_activate

A quick way to interact with the `activate` and `kerl_deactivate` scripts created by `kerl`. Instead of:

```
. path/to/release/dir/<release-name>/activate
...
kerl_deactivate
```

You can do:

```
. kerl_activate <release-name>
...
kerl_deactivate
```

The `path/to/release/dir` is wired in to the `kerl_activate` script. You'll probably need to change it to match what you use.

`kerl_activate list` displays the names of the sub-directories in its wired-in release directory.

`. kerl_activate deactivate` is longhand for `kerl_deactivate`, there mostly for those of us who may have forgotten `kerl_deactivate`.

`kerl_activate` tells the kerl-generated `activate` script to enable the prompt that shows `(<build-name>)` at the beginning of your `PS1` shell prompt. Get rid of `KERL_ENABLE_PROMPT=y` if you don't like that.


text:
package com.vmware.antlr4c3;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.antlr.v4.runtime.Parser;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.TokenStream;
import org.antlr.v4.runtime.Vocabulary;
import org.antlr.v4.runtime.atn.ATN;
import org.antlr.v4.runtime.atn.ATNState;
import org.antlr.v4.runtime.atn.PredicateTransition;
import org.antlr.v4.runtime.atn.RuleStopState;
import org.antlr.v4.runtime.atn.RuleTransition;
import org.antlr.v4.runtime.atn.Transition;
import org.antlr.v4.runtime.misc.IntervalSet;

/**
 * Port of antlr-c3 javascript library to java
 * <p>
 * The c3 engine is able to provide code completion candidates useful for
 * editors with ANTLR generated parsers, independent of the actual
 * language/grammar used for the generation.
 */
public class CodeCompletionCore {

    public final static Logger logger = Logger.getLogger(CodeCompletionCore.class.getName());

    /**
     * JDO returning information about matching tokens and rules
     */
    public static class CandidatesCollection {
        /**
         * Collection of Token ID candidates, each with a follow-on List of
         * subsequent tokens
         */
        public Map<Integer, List<Integer>> tokens = new HashMap<>();
        /**
         * Collection of Rule candidates, each with the callstack of rules to
         * reach the candidate
         */
        public Map<Integer, List<Integer>> rules = new HashMap<>();
        /**
         * Collection of matched Preferred Rules each with their start and end
         * offsets
         */
        public Map<Integer, List<Integer>> rulePositions = new HashMap<>();

        @Override
        public String toString() {
            return "CandidatesCollection{" + "tokens=" + tokens + ", rules=" + rules + ", ruleStrings=" + rulePositions + '}';
        }
    }

    public static class FollowSetWithPath {
        public IntervalSet intervals;
        public List<Integer> path;
        public List<Integer> following;
    }

    public static class FollowSetsHolder {
        public List<FollowSetWithPath> sets;
        public IntervalSet combined;
    }

    public static class PipelineEntry {

        public PipelineEntry(ATNState state, Integer tokenIndex) {
            this.state = state;
            this.tokenIndex = tokenIndex;
        }

        ATNState state;
        Integer tokenIndex;
    }

    private boolean showResult = true;
    private boolean showDebugOutput = true;
    private boolean debugOutputWithTransitions = true;
    private boolean showRuleStack = true;

    private Set<Integer> ignoredTokens = new HashSet<>();
    private Set<Integer> preferredRules = new HashSet<>();

    private Parser parser;
    private ATN atn;
    private Vocabulary vocabulary;
    private String[] ruleNames;
    private List<Token> tokens;

    private int tokenStartIndex = 0;
    private int statesProcessed = 0;

    // A mapping of rule index to token stream position to end token positions.
    // A rule which has been visited before with the same input position will always produce the same output positions.
    private final Map<Integer, Map<Integer, Set<Integer>>> shortcutMap = new HashMap<>();
    private final CandidatesCollection candidates = new CandidatesCollection(); // The collected candidates (rules and tokens).

    private final static Map<String, Map<Integer, FollowSetsHolder>> followSetsByATN = new HashMap<>();

    public CodeCompletionCore(Parser parser, Set<Integer> preferredRules, Set<Integer> ignoredTokens) {
        this.parser = parser;
        this.atn = parser.getATN();
        this.vocabulary = parser.getVocabulary();
        this.ruleNames = parser.getRuleNames();
        if (preferredRules != null) {
            this.preferredRules = preferredRules;
        }
        if (ignoredTokens != null) {
            this.ignoredTokens = ignoredTokens;
        }
    }

    public Set<Integer> getPreferredRules() {
        return Collections.unmodifiableSet(preferredRules);
    }

    public void setPreferredRules(Set<Integer> preferredRules) {
        this.preferredRules = new HashSet<>(preferredRules);
    }

    /**
     * This is the main entry point. The caret token index specifies the token stream index for the token which currently
     * covers the caret (or any other position you want to get code completion candidates for).
     * Optionally you can pass in a parser rule context which limits the ATN walk to only that or called rules. This can significantly
     * speed up the retrieval process but might miss some candidates (if they are outside of the given context).
     */
    public CandidatesCollection collectCandidates(int caretTokenIndex, ParserRuleContext context) {
        this.shortcutMap.clear();
        this.candidates.rules.clear();
        this.candidates.tokens.clear();
        this.statesProcessed = 0;

        this.tokenStartIndex = context != null ? context.start.getTokenIndex() : 0;
        TokenStream tokenStream  = this.parser.getInputStream();

        int currentIndex = tokenStream.index();
        tokenStream.seek(this.tokenStartIndex);
        this.tokens = new LinkedList<>();
        int offset = 1;
        while (true) {
            Token token = tokenStream.LT(offset++);
            this.tokens.add(token);
            if (token.getTokenIndex() >= caretTokenIndex || token.getType() == Token.EOF) {
                break;
            }
        }
        tokenStream.seek(currentIndex);

        LinkedList<Integer> callStack = new LinkedList<>();
        int startRule = context != null ? context.getRuleIndex() : 0;
        this.processRule(this.atn.ruleToStartState[startRule], 0, callStack, "\n");

        tokenStream.seek(currentIndex);

        // now post-process the rule candidates and find the last occurrences
        // of each preferred rule and extract its start and end in the input stream
        for (int ruleId : preferredRules) {
            final Map<Integer, Set<Integer>> shortcut = shortcutMap.get(ruleId);
            if (shortcut == null || shortcut.isEmpty()) {
                continue;
            }
            // select the right-most occurrence
            final int startToken = Collections.max(shortcut.keySet());
            final Set<Integer> endSet = shortcut.get(startToken);
            final int endToken;
            if (endSet.isEmpty()) {
                endToken = tokens.size() - 1;
            } else {
                endToken = Collections.max(shortcut.get(startToken));
            }
            final int startOffset = tokens.get(startToken).getStartIndex();
            final int endOffset;
            if (tokens.get(endToken).getType() == Token.EOF) {
                // if last token is EOF, include trailing whitespace
                endOffset = tokens.get(endToken).getStartIndex();
            } else {
                // if last token is not EOF, limit to matching tokens which excludes trailing whitespace
                endOffset = tokens.get(endToken - 1).getStopIndex() + 1;
            }

            final List<Integer> ruleStartStop = Arrays.asList(startOffset, endOffset);
            candidates.rulePositions.put(ruleId, ruleStartStop);
        }

        if (this.showResult && logger.isLoggable(Level.FINE)) {
            StringBuilder logMessage = new StringBuilder();

            logMessage.append("States processed: ").append(this.statesProcessed).append("\n");

            logMessage.append("Collected rules:\n");

            for (Map.Entry<Integer, List<Integer>> entry : this.candidates.rules.entrySet()) {

                logMessage.append("  ").append(entry.getKey()).append(", path: ");
                for (Integer token : entry.getValue()) {
                    logMessage.append(this.ruleNames[token]).append(" ");
                }
                logMessage.append("\n");
            }

            logMessage.append("Collected Tokens:\n");
            for (Map.Entry<Integer, List<Integer>> entry : this.candidates.tokens.entrySet()) {
                logMessage.append("  ").append(this.vocabulary.getDisplayName(entry.getKey()));
                for (Integer following : entry.getValue()) {
                    logMessage.append(" ").append(this.vocabulary.getDisplayName(following));
                }
                logMessage.append("\n");
            }
            logger.log(Level.FINE, logMessage.toString());
        }

        return this.candidates;
    }

    /**
     * Check if the predicate associated with the given transition evaluates to true.
     */
    private boolean checkPredicate(PredicateTransition transition) {
        return transition.getPredicate().eval(this.parser, ParserRuleContext.EMPTY);
    }

    /**
     * Walks the rule chain upwards to see if that matches any of the preferred rules.
     * If found, that rule is added to the collection candidates and true is returned.
     */
    private boolean translateToRuleIndex(List<Integer> ruleStack) {
        if (this.preferredRules.isEmpty())
            return false;

        // Loop over the rule stack from highest to lowest rule level. This way we properly handle the higher rule
        // if it contains a lower one that is also a preferred rule.
        for (int i = 0; i < ruleStack.size(); ++i) {
            if (this.preferredRules.contains(ruleStack.get(i))) {
                // Add the rule to our candidates list along with the current rule path,
                // but only if there isn't already an entry like that.
                List<Integer> path = new LinkedList<>(ruleStack.subList(0, i));
                boolean addNew = true;
                for (Map.Entry<Integer, List<Integer>> entry : this.candidates.rules.entrySet()) {
                    if (!entry.getKey().equals(ruleStack.get(i)) || entry.getValue().size() != path.size()) {
                        continue;
                    }
                    // Found an entry for this rule. Same path? If so don't add a new (duplicate) entry.
                    if (path.equals(entry.getValue())) {
                        addNew = false;
                        break;
                    }
                }

                if (addNew) {
                    this.candidates.rules.put(ruleStack.get(i), path);
                    if (showDebugOutput && logger.isLoggable(Level.FINE)) {
                        logger.fine("=====> collected: " + this.ruleNames[i]);
                    }
                }
                return true;
            }
        }

        return false;
    }

    /**
     * This method follows the given transition and collects all symbols within the same rule that directly follow it
     * without intermediate transitions to other rules and only if there is a single symbol for a transition.
     */
    private List<Integer> getFollowingTokens(Transition initialTransition) {
        LinkedList<Integer> result = new LinkedList<>();
        LinkedList<ATNState> seen = new LinkedList<>(); // unused but in orig
        LinkedList<ATNState> pipeline = new LinkedList<>();
        pipeline.add(initialTransition.target);

        while (!pipeline.isEmpty()) {
            ATNState state = pipeline.removeLast();

            for (Transition transition: state.getTransitions()) {
                if (transition.getSerializationType() == Transition.ATOM) {
                    if (!transition.isEpsilon()) {
                        List<Integer> list = transition.label().toList();
                        if (list.size() == 1 && !this.ignoredTokens.contains(list.get(0))) {
                            result.addLast(list.get(0));
                            pipeline.addLast(transition.target);
                        }
                    } else {
                        pipeline.addLast(transition.target);
                    }
                }
            }
        }

        return result;
    }

    /**
     * Entry point for the recursive follow set collection function.
     */
    private LinkedList<FollowSetWithPath> determineFollowSets(ATNState start, ATNState stop){
        LinkedList<FollowSetWithPath> result = new LinkedList<>();
        Set<ATNState> seen = new HashSet<>();
        LinkedList<Integer> ruleStack = new LinkedList<>();

        this.collectFollowSets(start, stop, result, seen, ruleStack);

        return result;
    }

    /**
     * Collects possible tokens which could be matched following the given ATN state. This is essentially the same
     * algorithm as used in the LL1Analyzer class, but here we consider predicates also and use no parser rule context.
     */
    private void collectFollowSets(ATNState s, ATNState stopState, LinkedList<FollowSetWithPath> followSets,
            Set<ATNState> seen, LinkedList<Integer> ruleStack) {

        if (seen.contains(s))
            return;

        seen.add(s);

        if (s.equals(stopState) || s.getStateType() == ATNState.RULE_STOP) {
            FollowSetWithPath set = new FollowSetWithPath();
            set.intervals = IntervalSet.of(Token.EPSILON);
            set.path = new LinkedList<Integer>(ruleStack);
            followSets.addLast(set);
            return;
        }

        for (Transition transition : s.getTransitions()) {
            if (transition.getSerializationType() == Transition.RULE) {
                RuleTransition ruleTransition = (RuleTransition) transition;
                if (ruleStack.indexOf(ruleTransition.target.ruleIndex) != -1) {
                    continue;
                }
                ruleStack.addLast(ruleTransition.target.ruleIndex);
                this.collectFollowSets(transition.target, stopState, followSets, seen, ruleStack);
                ruleStack.removeLast();

            } else if (transition.getSerializationType() == Transition.PREDICATE) {
                if (this.checkPredicate((PredicateTransition) transition)) {
                    this.collectFollowSets(transition.target, stopState, followSets, seen, ruleStack);
                }
            } else if (transition.isEpsilon()) {
                this.collectFollowSets(transition.target, stopState, followSets, seen, ruleStack);
            } else if (transition.getSerializationType() == Transition.WILDCARD) {
                FollowSetWithPath set = new FollowSetWithPath();
                set.intervals = IntervalSet.of(Token.MIN_USER_TOKEN_TYPE, this.atn.maxTokenType);
                set.path = new LinkedList<Integer>(ruleStack);
                followSets.addLast(set);
            } else {
                IntervalSet label = transition.label();
                if (label != null && label.size() > 0) {
                    if (transition.getSerializationType() == Transition.NOT_SET) {
                        label = label.complement(IntervalSet.of(Token.MIN_USER_TOKEN_TYPE, this.atn.maxTokenType));
                    }
                    FollowSetWithPath set = new FollowSetWithPath();
                    set.intervals = label;
                    set.path = new LinkedList<Integer>(ruleStack);
                    set.following = this.getFollowingTokens(transition);
                    followSets.addLast(set);
                }
            }
        }
    }

    /**
     * Walks the ATN for a single rule only. It returns the token stream position for each path that could be matched in this rule.
     * The result can be empty in case we hit only non-epsilon transitions that didn't match the current input or if we
     * hit the caret position.
     */
    private Set<Integer> processRule(ATNState startState, int tokenIndex, LinkedList<Integer> callStack, String indentation) {

        // Start with rule specific handling before going into the ATN walk.

        // Check first if we've taken this path with the same input before.
        Map<Integer,Set<Integer>> positionMap = this.shortcutMap.get(startState.ruleIndex);
        if (positionMap == null) {
            positionMap = new HashMap<>();
            this.shortcutMap.put(startState.ruleIndex, positionMap);
        } else {
            if (positionMap.containsKey(tokenIndex)) {
                if (showDebugOutput) {
                    logger.fine("=====> shortcut");
                }
                return positionMap.get(tokenIndex);
            }
        }

        Set<Integer> result = new HashSet<>();

        // For rule start states we determine and cache the follow set, which gives us 3 advantages:
        // 1) We can quickly check if a symbol would be matched when we follow that rule. We can so check in advance
        //    and can save us all the intermediate steps if there is no match.
        // 2) We'll have all symbols that are collectable already together when we are at the caret when entering a rule.
        // 3) We get this lookup for free with any 2nd or further visit of the same rule, which often happens
        //    in non trivial grammars, especially with (recursive) expressions and of course when invoking code completion
        //    multiple times.
        Map<Integer, FollowSetsHolder> setsPerState = followSetsByATN.get(this.parser.getClass().getName());
        if (setsPerState == null) {
            setsPerState = new HashMap<>();
            followSetsByATN.put(this.parser.getClass().getName(), setsPerState);
        }

        FollowSetsHolder followSets = setsPerState.get(startState.stateNumber);
        if (followSets == null) {
            followSets = new FollowSetsHolder();
            setsPerState.put(startState.stateNumber, followSets);
            RuleStopState stop = this.atn.ruleToStopState[startState.ruleIndex];
            followSets.sets = this.determineFollowSets(startState, stop);

            // Sets are split by path to allow translating them to preferred rules. But for quick hit tests
            // it is also useful to have a set with all symbols combined.
            IntervalSet combined = new IntervalSet();
            for (FollowSetWithPath set: followSets.sets) {
                combined.addAll(set.intervals);
            }
            followSets.combined = combined;
        }

        callStack.addLast(startState.ruleIndex);
        int currentSymbol = this.tokens.get(tokenIndex).getType();

        if (tokenIndex >= this.tokens.size() - 1) { // At caret?
            if (this.preferredRules.contains(startState.ruleIndex)) {
                // No need to go deeper when collecting entries and we reach a rule that we want to collect anyway.
                this.translateToRuleIndex(callStack);
            } else {
                // Convert all follow sets to either single symbols or their associated preferred rule and add
                // the result to our candidates list.
                for (FollowSetWithPath set: followSets.sets) {
                    LinkedList<Integer> fullPath = new LinkedList<>(callStack);
                    fullPath.addAll(set.path);
                    if (!this.translateToRuleIndex(fullPath)) {
                        for (int symbol : set.intervals.toList()) {
                            if (!this.ignoredTokens.contains(symbol)) {
                                if (showDebugOutput && logger.isLoggable(Level.FINE)) {
                                    logger.fine("=====> collected: " + this.vocabulary.getDisplayName(symbol));
                                }
                                if (!this.candidates.tokens.containsKey(symbol))
                                    this.candidates.tokens.put(symbol, set.following); // Following is empty if there is more than one entry in the set.
                                else {
                                    // More than one following list for the same symbol.
                                    if (!this.candidates.tokens.get(symbol).equals(set.following)) { // XXX js uses !=
                                        this.candidates.tokens.put(symbol, new LinkedList<Integer>());
                                    }
                                }
                            } else {
                                logger.fine("====> collection: Ignoring token: " + symbol);
                            }
                        }
                    }
                }
            }

            callStack.removeLast();
            return result;

        } else {
            // Process the rule if we either could pass it without consuming anything (epsilon transition)
            // or if the current input symbol will be matched somewhere after this entry point.
            // Otherwise stop here.
            if (!followSets.combined.contains(Token.EPSILON) && !followSets.combined.contains(currentSymbol)) {
                callStack.removeLast();
                return result;
            }
        }

        // The current state execution pipeline contains all yet-to-be-processed ATN states in this rule.
        // For each such state we store the token index + a list of rules that lead to it.
        LinkedList<PipelineEntry> statePipeline = new LinkedList<>();
        PipelineEntry currentEntry;

        // Bootstrap the pipeline.
        statePipeline.add(new PipelineEntry(startState, tokenIndex));

        while (!statePipeline.isEmpty()) {
            currentEntry = statePipeline.removeLast();
            ++this.statesProcessed;

            currentSymbol = this.tokens.get(currentEntry.tokenIndex).getType();

            boolean atCaret = currentEntry.tokenIndex >= this.tokens.size() - 1;
            if (logger.isLoggable(Level.FINE)) {
                printDescription(indentation, currentEntry.state, this.generateBaseDescription(currentEntry.state), currentEntry.tokenIndex);
                if (this.showRuleStack) {
                    printRuleState(callStack);
                }
            }

            switch (currentEntry.state.getStateType()) {
                case ATNState.RULE_START: // Happens only for the first state in this rule, not subrules.
                    indentation += "  ";
                    break;

                case ATNState.RULE_STOP: {
                    // Record the token index we are at, to report it to the caller.
                    result.add(currentEntry.tokenIndex);
                    continue;
                }

                default:
                    break;
            }

            Transition[] transitions = currentEntry.state.getTransitions();
            for (Transition transition : transitions) {
                switch (transition.getSerializationType()) {
                    case Transition.RULE: {
                        Set<Integer> endStatus = this.processRule(transition.target, currentEntry.tokenIndex, callStack, indentation);
                        for (Integer position : endStatus) {
                            statePipeline.addLast(new PipelineEntry(((RuleTransition) transition).followState, position));
                        }
                        break;
                    }

                    case Transition.PREDICATE: {
                        if (this.checkPredicate((PredicateTransition)transition)) {
                            statePipeline.addLast(new PipelineEntry(transition.target, currentEntry.tokenIndex));
                        }
                        break;
                    }

                    case Transition.WILDCARD: {
                        if (atCaret) {
                            if (!this.translateToRuleIndex(callStack)) {
                                for (Integer token : IntervalSet.of(Token.MIN_USER_TOKEN_TYPE, this.atn.maxTokenType).toList()) {
                                    if (!this.ignoredTokens.contains(token)) {
                                        this.candidates.tokens.put(token, new LinkedList<Integer>());
                                    }
                                }
                            }
                        } else {
                            statePipeline.addLast(new PipelineEntry(transition.target, currentEntry.tokenIndex + 1));
                        }
                        break;
                    }

                    default: {
                        if (transition.isEpsilon()) {
                            // Jump over simple states with a single outgoing epsilon transition.
                            statePipeline.addLast(new PipelineEntry(transition.target, currentEntry.tokenIndex));
                            continue;
                        }

                        IntervalSet set = transition.label();
                        if (set != null && set.size() > 0) {
                            if (transition.getSerializationType() == Transition.NOT_SET) {
                                set = set.complement(IntervalSet.of(Token.MIN_USER_TOKEN_TYPE, this.atn.maxTokenType));
                            }
                            if (atCaret) {
                                if (!this.translateToRuleIndex(callStack)) {
                                    List<Integer> list = set.toList();
                                    boolean addFollowing = list.size() == 1;
                                    for (Integer symbol: list) {
                                        if (!this.ignoredTokens.contains(symbol)) {
                                            if (showDebugOutput && logger.isLoggable(Level.FINE)) {
                                                logger.fine("=====> collected: " + this.vocabulary.getDisplayName(symbol));
                                            }
                                            if (addFollowing) {
                                                this.candidates.tokens.put(symbol, this.getFollowingTokens(transition));
                                            } else {
                                                this.candidates.tokens.put(symbol, new LinkedList<>());
                                            }
                                        } else {
                                            logger.fine("====> collected: Ignoring token: " + symbol);
                                        }
                                    }
                                }
                            } else {
                                if (set.contains(currentSymbol)) {
                                    if (showDebugOutput && logger.isLoggable(Level.FINE)) {
                                        logger.fine("=====> consumed: " + this.vocabulary.getDisplayName(currentSymbol));
                                    }
                                    statePipeline.addLast(new PipelineEntry(transition.target, currentEntry.tokenIndex + 1));
                                }
                            }
                        }
                    }
                }
            }
        }

        callStack.removeLast();

        // Cache the result, for later lookup to avoid duplicate walks.
        positionMap.put(tokenIndex, result);

        return result;
    }

    private String[] atnStateTypeMap = new String[] {
        "invalid",
        "basic",
        "rule start",
        "block start",
        "plus block start",
        "star block start",
        "token start",
        "rule stop",
        "block end",
        "star loop back",
        "star loop entry",
        "plus loop back",
        "loop end"
    };

    private String generateBaseDescription(ATNState state) {
        String stateValue = (state.stateNumber == ATNState.INVALID_STATE_NUMBER) ? "Invalid" : Integer.toString(state.stateNumber);
        return "[" + stateValue + " " + this.atnStateTypeMap[state.getStateType()] + "] in " + this.ruleNames[state.ruleIndex];
    }

    private void printDescription(String currentIndent, ATNState state, String baseDescription, int tokenIndex) {

        StringBuilder output = new StringBuilder(currentIndent);

        StringBuilder transitionDescription = new StringBuilder();
        if (this.debugOutputWithTransitions && logger.isLoggable(Level.FINER)) {
            for (Transition transition: state.getTransitions()) {
                StringBuilder labels = new StringBuilder();
                List<Integer> symbols = (transition.label() != null) ? transition.label().toList() : new LinkedList<>();
                if (symbols.size() > 2) {
                    // Only print start and end symbols to avoid large lists in debug output.
                    labels.append(this.vocabulary.getDisplayName(symbols.get(0)) + " .. " + this.vocabulary.getDisplayName(symbols.get(symbols.size() - 1)));
                } else {
                    for (Integer symbol: symbols) {
                        if (labels.length() > 0) {
                            labels.append(", ");
                        }
                        labels.append(this.vocabulary.getDisplayName(symbol));
                    }
                }
                if (labels.length() == 0) {
                    labels.append("ε");
                }
                transitionDescription.
                        append("\n").
                        append(currentIndent).
                        append("\t(").
                        append(labels).
                        append(") [").
                        append(transition.target.stateNumber).
                        append(" ").
                        append(this.atnStateTypeMap[transition.target.getStateType()]).
                        append("] in ").
                        append(this.ruleNames[transition.target.ruleIndex]);
            }

            if (tokenIndex >= this.tokens.size() - 1) {
                output.append("<<").append(this.tokenStartIndex + tokenIndex).append(">> ");
            } else {
                output.append("<").append(this.tokenStartIndex + tokenIndex).append("> ");
            }
            logger.finer(output + "Current state: " + baseDescription + transitionDescription);
        }
    }

    private void printRuleState(LinkedList<Integer> stack) {
        if (stack.isEmpty()) {
            logger.fine("<empty stack>");
            return;
        }

        if (logger.isLoggable(Level.FINER)) {
            StringBuilder sb = new StringBuilder();
            for (Integer rule : stack) {
                sb.append("  ").append(this.ruleNames[rule]).append("\n");
            }
            logger.log(Level.FINER, sb.toString());
        }
    }

}


text:
import re
import subprocess
from tempfile import NamedTemporaryFile
import os
import sys
from subprocess import Popen, PIPE

def to_sampa(phonemes):
    sampaphonemes = []
    #doesn't look like svox works well with this sound
    phonemes = [s.replace('ɔ', 'ɒ').replace('i', 'ɪ').replace('a', 'ɒ') for s in phonemes]
    for ph in phonemes:
        with Popen(['nodejs', 'src/speak/ipa-sampa.js', 'ipa2xsampa'], stdin=PIPE, stdout=PIPE) as ipa2xsampa:
            sampabytes = ipa2xsampa.communicate(input=ph.encode(encoding='UTF-8'))[0]
            sampaphonemes.append(sampabytes.decode(encoding='UTF-8'))
    return sampaphonemes

def speak_svox(sampaphonemes):
    #XML escape our sampa by doing something clever
    replace_dict = {
        "\\" : "\\\\",
        "\"" : "\\\""
    }

    regex = re.compile("(%s)" % "|".join(map(re.escape, replace_dict.keys())))
    sampa_escape = lambda s: \
                        regex.sub(lambda mo: replace_dict[mo.string[mo.start():mo.end()]], s)

    sampa_escaped_phonemes = [sampa_escape(s) for s in sampaphonemes]
    #And bundle it all up in xml tags
    sampa_xml_phonemes = ['<phoneme alphabet="xsampa" ph="{}" />'.format(s) for s in sampa_escaped_phonemes]

    xml_string = '<speed level="85">' + ''.join(sampa_xml_phonemes) + '</speed>'
    #Make a wave file with our xml tags
    tf = NamedTemporaryFile(suffix='.wav', delete=False)
    tf.close()
    #wave it up
    subprocess.call(['pico2wave', '-w', tf.name, xml_string], stdout=subprocess.DEVNULL)
    subprocess.call(['aplay', tf.name], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

    os.unlink(tf.name)

if __name__ == '__main__':
   speak_svox(to_sampa([sys.argv[1]]))


text: I am text.


text:
package Pavel.learn_java.addressbook.tests;

import Pavel.learn_java.addressbook.model.GroupData;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.util.List;

public class GroupDeletionTests extends TestBase {

  @Test
  public void testGroupDeletion() {
    app.getNavigationHelper().gotoGroupPage();
    if(! app.getGruopHelper().isThereAGroup()){
      app.getGruopHelper().createGroup(new GroupData("test1", null, "test3"));
    }
    List<GroupData> before = app.getGruopHelper().getGroupList();
    app.getGruopHelper().selectGroup(before.size() -1);
    app.getGruopHelper().deleteSelectedGroups();
    app.getGruopHelper().returnToGroupPage();
    List<GroupData> after = app.getGruopHelper().getGroupList();
    Assert.assertEquals(after.size(), before.size() - 1);
  }

}


text:
A face detection project made for CSH hackathon fall 2015. Used to detect faces on any computer running the script included here. The wave file that is generated will then be sent to the pi to be played over speakers.

## Usage
To use this, put your password and username in the getCSVDate.py file in the respective places.
Make sure to update the path to your path to your gallery of face in searchFaces.sh
Then type ./searchFaces.sh into your shell and run from this directory.
Run to the library.
Listen for your message!

## Requirements
you will need the following libraries to be installed to run this project

OpenCV 2.4.9 and above.
OpenBr
CSHLDAP python script from the wiki

you will also need to build the getFaces executable using CMake after OpenCV is installed.

### Building getFaces
To build getFaces on a linux machine using CMake, run the following in the project directory.

mkdir build && cd build
cmake ..
make
mv getFaces ..
cd ..

you can now run searchFaces.sh!