text:
'use strict';

const blueprintHelpers = require('ember-cli-blueprint-test-helpers/helpers');
const setupTestHooks = blueprintHelpers.setupTestHooks;
const emberNew = blueprintHelpers.emberNew;
const emberGenerateDestroy = blueprintHelpers.emberGenerateDestroy;
const setupPodConfig = blueprintHelpers.setupPodConfig;

const chai = require('ember-cli-blueprint-test-helpers/chai');
const expect = chai.expect;

describe('Blueprint: controller', function() {
  setupTestHooks(this);

  describe('in app', function() {
    beforeEach(function() {
      return emberNew();
    });

    it('controller foo', function() {
      return emberGenerateDestroy(['controller', 'foo'], _file => {
        expect(_file('app/controllers/foo.js'))
          .to.contain("import Controller from '@ember/controller';")
          .to.contain("export default Controller.extend({\n});");

        expect(_file('tests/unit/controllers/foo-test.js'))
          .to.contain("import { moduleFor, test } from 'ember-qunit';")
          .to.contain("moduleFor('controller:foo'");
      });
    });

    it('controller foo/bar', function() {
      return emberGenerateDestroy(['controller', 'foo/bar'], _file => {
        expect(_file('app/controllers/foo/bar.js'))
          .to.contain("import Controller from '@ember/controller';")
          .to.contain("export default Controller.extend({\n});");

        expect(_file('tests/unit/controllers/foo/bar-test.js'))
          .to.contain("import { moduleFor, test } from 'ember-qunit';")
          .to.contain("moduleFor('controller:foo/bar'");
      });
    });

    it('controller foo --pod', function() {
      return emberGenerateDestroy(['controller', 'foo', '--pod'], _file => {
        expect(_file('app/foo/controller.js'))
          .to.contain("import Controller from '@ember/controller';")
          .to.contain("export default Controller.extend({\n});");

        expect(_file('tests/unit/foo/controller-test.js'))
          .to.contain("import { moduleFor, test } from 'ember-qunit';")
          .to.contain("moduleFor('controller:foo'");
      });
    });

    it('controller foo/bar --pod', function() {
      return emberGenerateDestroy(['controller', 'foo/bar', '--pod'], _file => {
        expect(_file('app/foo/bar/controller.js'))
          .to.contain("import Controller from '@ember/controller';")
          .to.contain("export default Controller.extend({\n});");

        expect(_file('tests/unit/foo/bar/controller-test.js'))
          .to.contain("import { moduleFor, test } from 'ember-qunit';")
          .to.contain("moduleFor('controller:foo/bar'");
      });
    });

    describe('with podModulePrefix', function() {
      beforeEach(function() {
        setupPodConfig({ podModulePrefix: true });
      });

      it('controller foo --pod podModulePrefix', function() {
        return emberGenerateDestroy(['controller', 'foo', '--pod'], _file => {
          expect(_file('app/pods/foo/controller.js'))
            .to.contain("import Controller from '@ember/controller';")
            .to.contain("export default Controller.extend({\n});");

          expect(_file('tests/unit/pods/foo/controller-test.js'))
            .to.contain("import { moduleFor, test } from 'ember-qunit';")
            .to.contain("moduleFor('controller:foo'");
        });
      });

      it('controller foo/bar --pod podModulePrefix', function() {
        return emberGenerateDestroy(['controller', 'foo/bar', '--pod'], _file => {
          expect(_file('app/pods/foo/bar/controller.js'))
            .to.contain("import Controller from '@ember/controller';")
            .to.contain("export default Controller.extend({\n});");

          expect(_file('tests/unit/pods/foo/bar/controller-test.js'))
            .to.contain("import { moduleFor, test } from 'ember-qunit';")
            .to.contain("moduleFor('controller:foo/bar'");
        });
      });
    });
  });

  describe('in addon', function() {
    beforeEach(function() {
      return emberNew({ target: 'addon' });
    });

    it('controller foo', function() {
      return emberGenerateDestroy(['controller', 'foo'], _file => {
        expect(_file('addon/controllers/foo.js'))
          .to.contain("import Controller from '@ember/controller';")
          .to.contain("export default Controller.extend({\n});");

        expect(_file('app/controllers/foo.js'))
          .to.contain("export { default } from 'my-addon/controllers/foo';");

        expect(_file('tests/unit/controllers/foo-test.js'))
          .to.contain("import { moduleFor, test } from 'ember-qunit';")
          .to.contain("moduleFor('controller:foo'");
      });
    });

    it('controller foo/bar', function() {
      return emberGenerateDestroy(['controller', 'foo/bar'], _file => {
        expect(_file('addon/controllers/foo/bar.js'))
          .to.contain("import Controller from '@ember/controller';")
          .to.contain("export default Controller.extend({\n});");

        expect(_file('app/controllers/foo/bar.js'))
          .to.contain("export { default } from 'my-addon/controllers/foo/bar';");

        expect(_file('tests/unit/controllers/foo/bar-test.js'))
          .to.contain("import { moduleFor, test } from 'ember-qunit';")
          .to.contain("moduleFor('controller:foo/bar'");
      });
    });

    it('controller foo --dummy', function() {
      return emberGenerateDestroy(['controller', 'foo', '--dummy'], _file => {
        expect(_file('tests/dummy/app/controllers/foo.js'))
          .to.contain("import Controller from '@ember/controller';")
          .to.contain("export default Controller.extend({\n});");

        expect(_file('app/controllers/foo-test.js'))
          .to.not.exist;

        expect(_file('tests/unit/controllers/foo-test.js'))
          .to.not.exist;
      });
    });

    it('controller foo/bar --dummy', function() {
      return emberGenerateDestroy(['controller', 'foo/bar', '--dummy'], _file => {
        expect(_file('tests/dummy/app/controllers/foo/bar.js'))
          .to.contain("import Controller from '@ember/controller';")
          .to.contain("export default Controller.extend({\n});");

        expect(_file('app/controllers/foo/bar.js'))
          .to.not.exist;

        expect(_file('tests/unit/controllers/foo/bar-test.js'))
          .to.not.exist;
      });
    });
  });

  describe('in in-repo-addon', function() {
    beforeEach(function() {
      return emberNew({ target: 'in-repo-addon' });
    });

    it('controller foo --in-repo-addon=my-addon', function() {
      return emberGenerateDestroy(['controller', 'foo', '--in-repo-addon=my-addon'], _file => {
        expect(_file('lib/my-addon/addon/controllers/foo.js'))
          .to.contain("import Controller from '@ember/controller';")
          .to.contain("export default Controller.extend({\n});");

        expect(_file('lib/my-addon/app/controllers/foo.js'))
          .to.contain("export { default } from 'my-addon/controllers/foo';");

        expect(_file('tests/unit/controllers/foo-test.js'))
          .to.contain("import { moduleFor, test } from 'ember-qunit';")
          .to.contain("moduleFor('controller:foo'");
      });
    });

    it('controller foo/bar --in-repo-addon=my-addon', function() {
      return emberGenerateDestroy(['controller', 'foo/bar', '--in-repo-addon=my-addon'], _file => {
        expect(_file('lib/my-addon/addon/controllers/foo/bar.js'))
          .to.contain("import Controller from '@ember/controller';")
          .to.contain("export default Controller.extend({\n});");

        expect(_file('lib/my-addon/app/controllers/foo/bar.js'))
          .to.contain("export { default } from 'my-addon/controllers/foo/bar';");

        expect(_file('tests/unit/controllers/foo/bar-test.js'))
          .to.contain("import { moduleFor, test } from 'ember-qunit';")
          .to.contain("moduleFor('controller:foo/bar'");
      });
    });
  });
});


text:
/**
 *
 */
package com.gemstone.gemfire.security;

/**
 * this class contains test methods that used to be in its superclass but
 * that test started taking too long and caused dunit runs to hang
 */
public class ClientAuthenticationPart2DUnitTest extends
    ClientAuthenticationDUnitTest {

  /** constructor */
  public ClientAuthenticationPart2DUnitTest(String name) {
    super(name);
  }

  // override inherited tests so they aren't executed again

  @Override
  public void testValidCredentials() {  }
  @Override
  public void testNoCredentials() {  }
  @Override
  public void testInvalidCredentials() {  }
  @Override
  public void testInvalidAuthInit() {  }
  @Override
  public void testNoAuthInitWithCredentials() {  }
  @Override
  public void testInvalidAuthenticator() {  }
  @Override
  public void testNoAuthenticatorWithCredentials() {  }
  @Override
  public void testCredentialsWithFailover() {  }
  @Override
  public void testCredentialsForNotifications() {  }
  //@Override
  public void testValidCredentialsForMultipleUsers() {  }

  public void DISABLED_Bug48433_testNoCredentialsForMultipleUsers() {
    itestNoCredentials(Boolean.TRUE);
  }
  public void testInvalidCredentialsForMultipleUsers() {
    itestInvalidCredentials(Boolean.TRUE);
  }
  public void testInvalidAuthInitForMultipleUsers() {
    itestInvalidAuthInit(Boolean.TRUE);
  }
  public void testNoAuthInitWithCredentialsForMultipleUsers() {
    itestNoAuthInitWithCredentials(Boolean.TRUE);
  }
  public void testInvalidAuthenitcatorForMultipleUsers() {
    itestInvalidAuthenticator(Boolean.TRUE);
  }
  public void testNoAuthenticatorWithCredentialsForMultipleUsers() {
    itestNoAuthenticatorWithCredentials(Boolean.TRUE);
  }
  public void testCredentialsWithFailoverForMultipleUsers() {
    itestCredentialsWithFailover(Boolean.TRUE);
  }
  public void __testCredentialsForNotificationsForMultipleUsers() {
    itestCredentialsForNotifications(Boolean.TRUE);
  }

}

redpajama_set_name: RedPajamaGithub


text:
package a;

public interface JFunction1<T> {
    void foo(T t);
}


text:
"use strict";

var gulp = require("gulp");
var plumber = require("gulp-plumber");
var postcss = require("gulp-postcss");
var autoprefixer = require("autoprefixer");

var mqpacker = require("css-mqpacker");
var minify = require("gulp-csso");
var rename = require("gulp-rename");
var imagemin = require("gulp-imagemin");

var copy = require('gulp-contrib-copy');
var clean = require('gulp-contrib-clean');

var server = require("browser-sync");

var uglify = require('gulp-uglify');

var uncss = require('gulp-uncss');
var concat = require('gulp-concat');

gulp.task("images", function() {
    return gulp.src("img/**/*.{png,jpg,gif,ico,svg}")
      .pipe(imagemin({
      optimizationLevel: 6,
      progressive: true
    }))
    .pipe(gulp.dest("build/img"));
});

gulp.task("style", function() {
  gulp.src("css/**/*.css")
    .pipe(plumber())
    .pipe(concat('main.css'))
    .pipe(uncss({
        html: ['index.html'],
        ignore: [/\w\.in/,
                  ".fade",
                  ".collapse",
                  ".collapsing",
                  /(#|\.)navbar(\-[a-zA-Z]+)?/,
                  /(#|\.)dropdown(\-[a-zA-Z]+)?/,
                  /(#|\.)(open)/,
                  ".modal",
                  ".modal-open",
                  ".modal-open .modal",
                  ".fade.in",
                  ".portfolio-modal", ".modal-content", ".close-modal",
                  ".modal-dialog",
                  ".modal-document",
                  ".modal-scrollbar-measure",
                  ".modal-backdrop.fade",
                  ".modal-backdrop.in",
                  ".modal.fade.modal-dialog",
                  ".modal.in.modal-dialog",
                  ".in",
                  ".modal-backdrop"]
    }))
    .pipe(postcss([
      autoprefixer({browsers: [
        "last 1 version",
        "last 2 Chrome versions",
        "last 2 Firefox versions",
        "last 2 Opera versions",
        "last 2 Edge versions"
      ]}),
      mqpacker({
        sort: true })
    ]))
    .pipe(gulp.dest("build/css"))
    .pipe(minify())
    .pipe(rename("main.min.css"))
    .pipe(gulp.dest("build/css"))

    .pipe(server.reload({stream: true}));
});

gulp.task('compress', function() {
  return gulp.src('js/*.js')
    .pipe(uglify())
    .pipe(gulp.dest('build/js'));
});

gulp.task("clean", function() {
  gulp.src('build', {read: false})
    .pipe(clean())
  });

gulp.task("copy", function() {
  gulp.src("*.html").pipe(gulp.dest("build"));
  gulp.src("font-awesome/*/**.*").pipe(gulp.dest("build/font-awesome"));
  gulp.src("fonts/**.*").pipe(gulp.dest("build/fonts"));
  gulp.src("mail/**.*").pipe(gulp.dest("build/mail"));
});

gulp.task("serve", function() {
  server.init({
    server: ".",
    notify: false,
    open: true,
    ui: false
  });

  gulp.watch("js/*.js").on("change", server.reload);
  gulp.watch("*.html").on("change", server.reload);
  gulp.watch("css/*.css").on("change", server.reload);
});

gulp.task("build", ["clean", "style", "images", "compress", "copy"], function() {
});


text:
class Page < Document
end


text:
package com.mcapatna.spring.ioc.app;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.mcapatna.spring.ioc.model.IndianGames;

/**
 *
 * @author mcapatna,The Power House
 * @Since 19 Jul 2016
 * @Details at www.mcapatna.wordpress.com
 */
public class SportsMinister {
	private static ApplicationContext context;

	public static void main(String[] args) {
		context = new ClassPathXmlApplicationContext("mcapatna-context.xml");
		IndianGames games = (IndianGames) context.getBean("indianGames");
		games.showDetails();
	}
}


text:
package com.bs.parser.tree;

import com.bs.interpreter.Interpreter;
import com.bs.parser.token.Token;

public class MessagesNode extends AbstractListNode<MessageNode> {

	public MessagesNode(Token token) {
		super(token);
	}

	@Override
	public String toTree() {
		return "Messages(messages=[" + super.toTree() + "])";
	}

	@Override
	public Object visit(Interpreter visitor) {
		return visitor.interpretMessages(this);
	}
}


text:
import { GirModulesGrouped } from './gir-modules-grouped'

export interface GirModulesGroupedMap {
    [id: string]: GirModulesGrouped
}


text:
require 'spec_helper'

describe ShouldClean::Simulator do

  let(:spec_file) { File.join(File.dirname(__FILE__), '..', 'fixtures', 'example_spec.txt') }
  let(:buffer) { StringIO.new }

  it "displays a diff of changes" do
    simulator = ShouldClean::Simulator.new(spec_file, buffer)
    simulator.run
    buffer.string.should == <<eos
- it "should create some (should another)" do
+ it "creates some (should another)" do
- it "should do something" do
+ it "does something" do
- it 'should do something' do
+ it 'does something' do
- it %{should do something} do
+ it %{does something} do
eos
  end

  it "does not raise exception when file has invalid encoding" do
    spec_file = File.join(File.dirname(__FILE__), '..', 'fixtures', 'broken_spec.txt')
    buffer = StringIO.new
    simulator = ShouldClean::Simulator.new(spec_file, buffer)
    lambda { simulator.run }.should_not raise_exception(ArgumentError)
  end
end


text:
__author__ = "Brian Lenihan <brian.lenihan@gmail.com"
__copyright__ = "Copyright (c) 2012 Python for Android Project"
__license__ = "Apache License, Version 2.0"

import logging
import android

from pyxmpp2.jid import JID
from pyxmpp2.client import Client
from pyxmpp2.settings import XMPPSettings
from pyxmpp2.interfaces import XMPPFeatureHandler
from pyxmpp2.interfaces import EventHandler, event_handler, QUIT
from pyxmpp2.interfaces import message_stanza_handler
from pyxmpp2.streamevents import DisconnectedEvent
from pyxmpp2.ext.version import VersionProvider

logging.basicConfig(level = logging.INFO)
xmpp_trace  = False

class SayChat(EventHandler, XMPPFeatureHandler):
  def __init__(self):
      self.droid = android.Android()
      settings = XMPPSettings({"software_name": "Say Chat"})
      settings["jid"] = self.droid.dialogGetInput("Google Talk Username").result
      settings["password"] = self.droid.dialogGetInput("Google Talk Password").result
      settings["server"] = "talk.google.com"
      settings["starttls"] = True
      self.client = Client(
        JID(settings["jid"]),
        [self, VersionProvider(settings)],
        settings)

  def connect(self):
    self.client.connect()
    self.client.run()

  def disconnect(self):
    self.client.disconnect()
    self.client.run(timeout = 2)

  @message_stanza_handler()
  def handle_message(self, stanza):
    self.droid.ttsSpeak(
      "{!s} says {!s}".format(stanza.from_jid.as_unicode(),
      stanza.body))
    return ""

  @event_handler(DisconnectedEvent)
  def handle_disconnected(self, event):
    return QUIT

  @event_handler()
  def handle_all(self, event):
    """If it's not logged, it didn't happen."""
    logging.info("-- {}".format(event))

  def run(self):
    try:
      self.connect()
    except KeyboardInterrupt:
      self.disconnect()

if xmpp_trace:
  handler = logging.StreamHandler()
  handler.setLevel(logging.DEBUG)
  for logger in ("pyxmpp2.IN", "pyxmpp2.OUT"):
    logger = logging.getLogger(logger)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(handler)
    logger.propagate = False

saychat = SayChat()
saychat.run()


text:
```cs
// 'this' could be a Context object (Android) or UIViewController, UIView, UIBarButtonItem (iOS)
var user = await auth0.LoginAsync(this);
/*
- get user email => user.Profile["email"].ToString()
- get facebook/google/twitter/etc access token => user.Profile["identities"][0]["access_token"]
- get Windows Azure AD groups => user.Profile["groups"]
- etc.
*/
```


text:
namespace AzureFunctions.Contracts
{
    public interface IUserSettings
    {
        string BearerToken { get; }
    }
}


text:
function convertSignDir_S(imagedir, dataname, str, templateDir, foldname, rename, filename, outdir)
fn = [imagedir dataname str];
if ~exist(fn)
    mkdir(fn);
end
oldfn = [imagedir dataname];
[Trainstr, TrainAlpha, datastruct, datastruct_test] = Readdata_Sign_S(...
    oldfn, fn, templateDir, foldname, rename, filename, outdir);
save([fn '\Trainstr.mat'], 'Trainstr', 'TrainAlpha', 'datastruct', 'datastruct_test');


text:
package org.springframework.boot.actuate.autoconfigure.metrics;

import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.binder.kafka.KafkaClientMetrics;
import io.micrometer.core.instrument.binder.kafka.KafkaStreamsMetrics;

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.kafka.DefaultKafkaConsumerFactoryCustomizer;
import org.springframework.boot.autoconfigure.kafka.DefaultKafkaProducerFactoryCustomizer;
import org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration;
import org.springframework.boot.autoconfigure.kafka.StreamsBuilderFactoryBeanCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.config.StreamsBuilderFactoryBean;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.MicrometerConsumerListener;
import org.springframework.kafka.core.MicrometerProducerListener;
import org.springframework.kafka.core.ProducerFactory;
import org.springframework.kafka.streams.KafkaStreamsMicrometerListener;

/**
 * Auto-configuration for Kafka metrics.
 *
 * @author Andy Wilkinson
 * @author Stephane Nicoll
 * @author Eddú Meléndez
 * @since 2.1.0
 */
@Configuration(proxyBeanMethods = false)
@AutoConfigureBefore(KafkaAutoConfiguration.class)
@AutoConfigureAfter({ MetricsAutoConfiguration.class, CompositeMeterRegistryAutoConfiguration.class })
@ConditionalOnClass({ KafkaClientMetrics.class, ProducerFactory.class })
@ConditionalOnBean(MeterRegistry.class)
public class KafkaMetricsAutoConfiguration {

	@Bean
	public DefaultKafkaProducerFactoryCustomizer kafkaProducerMetrics(MeterRegistry meterRegistry) {
		return (producerFactory) -> addListener(producerFactory, meterRegistry);
	}

	@Bean
	public DefaultKafkaConsumerFactoryCustomizer kafkaConsumerMetrics(MeterRegistry meterRegistry) {
		return (consumerFactory) -> addListener(consumerFactory, meterRegistry);
	}

	private <K, V> void addListener(DefaultKafkaConsumerFactory<K, V> factory, MeterRegistry meterRegistry) {
		factory.addListener(new MicrometerConsumerListener<>(meterRegistry));
	}

	private <K, V> void addListener(DefaultKafkaProducerFactory<K, V> factory, MeterRegistry meterRegistry) {
		factory.addListener(new MicrometerProducerListener<>(meterRegistry));
	}

	@Configuration(proxyBeanMethods = false)
	@ConditionalOnClass({ KafkaStreamsMetrics.class, StreamsBuilderFactoryBean.class })
	static class KafkaStreamsMetricsConfiguration {

		@Bean
		StreamsBuilderFactoryBeanCustomizer kafkaStreamsMetrics(MeterRegistry meterRegistry) {
			return (factoryBean) -> factoryBean.addListener(new KafkaStreamsMicrometerListener(meterRegistry));
		}

	}

}


text:
<?php

namespace Orion7\CoreBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class MensajeType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('texto', 'textarea');

    }

    public function getName()
    {
        return 'mensajetype';
    }
}


text:
@protocol MyProtocol <NSObject>
- (NSString *)getAnswer:(NSInteger)arg;
@end


text:
package org.jsoftware.dbpatch.config;

import java.util.Date;

/**
 * Single patch
 *
 * @see RollbackPatch
 */
public class Patch extends AbstractPatch {
    private DbState dbState;
    private Date dbDate;

    @Override
    public void setDbDate(Date dbDate) {
        this.dbDate = dbDate == null ? null : new Date(dbDate.getTime());
    }

    @Override
    public void setDbState(DbState dbState) {
        this.dbState = dbState;
    }

    @Override
    public Date getDbDate() {
        return dbDate == null ? null : new Date(dbDate.getTime());
    }

    @Override
    public DbState getDbState() {
        return dbState;
    }

    public boolean canApply() {
        return getStatementCount() > 0 && getDbState() == DbState.NOT_AVAILABLE;
    }
}


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

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

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

    /**
     *

     * An array of objects that summarize each monitor's properties.
     *

     */
    private java.util.List<MonitorSummary> monitors;
    /**
     *

     * If the response is truncated, Amazon Forecast returns this token. To retrieve the next set of results, use the
     * token in the next request.
     *

     */
    private String nextToken;

    /**
     *

     * An array of objects that summarize each monitor's properties.
     *

     *
     * @return An array of objects that summarize each monitor's properties.
     */

    public java.util.List<MonitorSummary> getMonitors() {
        return monitors;
    }

    /**
     *

     * An array of objects that summarize each monitor's properties.
     *

     *
     * @param monitors
     *        An array of objects that summarize each monitor's properties.
     */

    public void setMonitors(java.util.Collection<MonitorSummary> monitors) {
        if (monitors == null) {
            this.monitors = null;
            return;
        }

        this.monitors = new java.util.ArrayList<MonitorSummary>(monitors);
    }

    /**
     *

     * An array of objects that summarize each monitor's properties.
     *

     *

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

     *
     * @param monitors
     *        An array of objects that summarize each monitor's properties.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListMonitorsResult withMonitors(MonitorSummary... monitors) {
        if (this.monitors == null) {
            setMonitors(new java.util.ArrayList<MonitorSummary>(monitors.length));
        }
        for (MonitorSummary ele : monitors) {
            this.monitors.add(ele);
        }
        return this;
    }

    /**
     *

     * An array of objects that summarize each monitor's properties.
     *

     *
     * @param monitors
     *        An array of objects that summarize each monitor's properties.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListMonitorsResult withMonitors(java.util.Collection<MonitorSummary> monitors) {
        setMonitors(monitors);
        return this;
    }

    /**
     *

     * If the response is truncated, Amazon Forecast returns this token. To retrieve the next set of results, use the
     * token in the next request.
     *

     *
     * @param nextToken
     *        If the response is truncated, Amazon Forecast returns this token. To retrieve the next set of results, use
     *        the token in the next request.
     */

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

    /**
     *

     * If the response is truncated, Amazon Forecast returns this token. To retrieve the next set of results, use the
     * token in the next request.
     *

     *
     * @return If the response is truncated, Amazon Forecast returns this token. To retrieve the next set of results,
     *         use the token in the next request.
     */

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

    /**
     *

     * If the response is truncated, Amazon Forecast returns this token. To retrieve the next set of results, use the
     * token in the next request.
     *

     *
     * @param nextToken
     *        If the response is truncated, Amazon Forecast returns this token. To retrieve the next set of results, use
     *        the token in the next request.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

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

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

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

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

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

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

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

}


text:
package com.almasb.datavis;

import javafx.application.Application;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

import java.nio.file.Paths;

/**
 * @author Almas Baimagambetov (almaslvl@gmail.com)
 */
public class WordFrequencyApp extends Application {

    private DataExtractor extractor = new WordExtractor(Paths.get("chapter1.tex"));

    private Parent createContent() {
        StackPane root = new StackPane();
        root.setPrefSize(800, 600);

        BarChart<String, Number> chart = new BarChart<>(new CategoryAxis(), new NumberAxis());

        XYChart.Series<String, Number> series = new XYChart.Series<>();

        extractor.extract()
                .stream()
                .sorted((e1, e2) -> e2.getFrequency() - e1.getFrequency())
                .limit(10)
                .forEach(entry -> {
                    series.getData().add(new XYChart.Data<>(entry.getWord(), entry.getFrequency()));
                });

        chart.getData().add(series);

        root.getChildren().add(chart);

        return root;
    }

    @Override
    public void start(Stage stage) throws Exception {
        stage.setScene(new Scene(createContent()));
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}


text:
package com.intellij.refactoring.typeMigration.rules.guava;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTypesUtil;
import com.intellij.psi.util.RedundantCastUtil;
import com.intellij.refactoring.typeMigration.TypeConversionDescriptor;
import com.intellij.refactoring.typeMigration.TypeConversionDescriptorBase;
import com.intellij.refactoring.typeMigration.TypeEvaluator;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Set;

/**
 * @author Dmitry Batkovich
 */
public class GuavaPredicatesUtil {
  private static final Logger LOG = Logger.getInstance(GuavaPredicatesUtil.class);

  static final Set<String> PREDICATES_AND_OR = ContainerUtil.newHashSet("or", "and");
  static final String PREDICATES_NOT = "not";
  public static final Set<String> PREDICATES_METHOD_NAMES =
    ContainerUtil.newHashSet("alwaysTrue", "alwaysFalse", "isNull", "notNull", "equalTo", "not", "or", "and");

  @Nullable
  static TypeConversionDescriptorBase tryConvertIfPredicates(PsiMethod method, PsiExpression context) {
    final String name = method.getName();
    if (name.equals("alwaysTrue") || name.equals("alwaysFalse")) {
      return createConstantPredicate(name, name.contains("True"));
    }
    else if (name.equals("isNull") || name.equals("notNull")) {
      final String operation = name.equals("isNull") ? "==" : "!=";
      return new TypeConversionDescriptorWithLocalVariable(name, "$x$ -> $x$" + operation + " null");
    }
    else if (name.equals("equalTo")) {
      return new TypeConversionDescriptorWithLocalVariable("equalTo", "$x$ -> java.util.Objects.equals($x$, $v$)");
    }
    if (!isConvertablePredicatesMethod(method, (PsiMethodCallExpression)context)) return null;
    if (((PsiMethodCallExpression)context).getArgumentList().getExpressions().length == 0) {
      return createConstantPredicate(name, name.equals("and"));
    }
    if (PREDICATES_AND_OR.contains(name) && canMigrateAndOrOr((PsiMethodCallExpression)context)) {
      return new AndOrOrConversionDescriptor(GuavaConversionUtil.addTypeParameters(GuavaLambda.PREDICATE.getJavaAnalogueClassQName(), context.getType(), context));
    }
    else if (PREDICATES_NOT.equals(name)) {
      return new NotConversionDescriptor(GuavaConversionUtil.addTypeParameters(GuavaLambda.PREDICATE.getJavaAnalogueClassQName(), context.getType(), context));
    }
    return null;
  }

  @NotNull
  private static TypeConversionDescriptorWithLocalVariable createConstantPredicate(String methodName, boolean value) {
    return new TypeConversionDescriptorWithLocalVariable(methodName, "$x$ -> " + value + "");
  }

  private static class TypeConversionDescriptorWithLocalVariable extends TypeConversionDescriptor {
    private final String myReplaceByStringTemplate;

    TypeConversionDescriptorWithLocalVariable(String methodName, String replaceByString) {
      super("'Predicates*." + methodName + "(" + (methodName.equals("equalTo") ? "$v$" : "") + ")", null);
      myReplaceByStringTemplate = replaceByString;
    }

    @Override
    public PsiExpression replace(PsiExpression expression, TypeEvaluator evaluator) {
      final String chosenName = FluentIterableConversionUtil.chooseName(expression, getIntroducedVariableType(expression));
      setReplaceByString(StringUtil.replace(myReplaceByStringTemplate, "$x$", chosenName));
      return super.replace(expression, evaluator);
    }

    private static PsiType getIntroducedVariableType(PsiExpression expression) {
      final PsiType type = expression.getType();
      if (type instanceof PsiClassType) {
        final PsiType[] parameters = ((PsiClassType)type).getParameters();
        if (parameters.length == 1) {
          final PsiType parameter = parameters[0];
          if (parameter instanceof PsiClassType) {
            return parameter;
          }
        }
      }
      return null;
    }
  }

  public static boolean isConvertablePredicatesMethod(@NotNull PsiMethod method, PsiMethodCallExpression context) {
    if (method.getParameterList().getParametersCount() == 1) {
      final PsiParameter parameter = method.getParameterList().getParameters()[0];
      final PsiClass psiClass = PsiTypesUtil.getPsiClass(parameter.getType().getDeepComponentType());
      if (psiClass == null || CommonClassNames.JAVA_LANG_ITERABLE.equals(psiClass.getQualifiedName())) {
        return false;
      }
    }
    final PsiExpression[] expressions = context.getArgumentList().getExpressions();
    return !(expressions.length == 1 && expressions[0].getType() instanceof PsiArrayType);
  }

  private static boolean canMigrateAndOrOr(PsiMethodCallExpression expr) {
    final PsiMethod method = expr.resolveMethod();
    if (method == null) return false;
    final PsiParameterList parameters = method.getParameterList();
    if (parameters.getParametersCount() != 1) {
      return parameters.getParametersCount() != 0;
    }
    final PsiParameter parameter = parameters.getParameters()[0];
    final PsiType type = parameter.getType();
    return type instanceof PsiEllipsisType;
  }

  private static class NotConversionDescriptor extends TypeConversionDescriptorBase {
    private final PsiType myTargetType;

    public NotConversionDescriptor(PsiType targetType) {
      myTargetType = targetType;
    }

    @Override
    public PsiExpression replace(PsiExpression expression, @NotNull TypeEvaluator evaluator) throws IncorrectOperationException {
      String newExpressionString =
        GuavaConversionUtil.adjustLambdaContainingExpression(((PsiMethodCallExpression)expression).getArgumentList().getExpressions()[0], true, myTargetType, evaluator).getText() + ".negate()";

      final PsiElement parent = expression.getParent();
      if (parent instanceof PsiMethodReferenceExpression) {
        expression = replaceTypeCast(expression, parent);
      }
      else if (!GuavaConversionUtil.isJavaLambda(parent, evaluator)) {
        newExpressionString += "::test";
      }
      final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(expression.getProject());
      PsiExpression convertedExpression =
        (PsiExpression)expression.replace(elementFactory.createExpressionFromText(newExpressionString, expression));
      convertedExpression = convertedExpression.getParent() instanceof PsiMethodReferenceExpression
                            ? (PsiExpression)convertedExpression.getParent().replace(convertedExpression)
                            : convertedExpression;
      final PsiElement maybeTypeCast = convertedExpression.getParent();
      if (maybeTypeCast instanceof PsiTypeCastExpression && RedundantCastUtil.isCastRedundant((PsiTypeCastExpression)maybeTypeCast)) {
        convertedExpression = (PsiExpression)maybeTypeCast.replace(((PsiTypeCastExpression)maybeTypeCast).getOperand());
      }
      return convertedExpression;
    }
  }

  private static class AndOrOrConversionDescriptor extends TypeConversionDescriptorBase {
    private final PsiType myTargetType;

    public AndOrOrConversionDescriptor(PsiType targetType) {
      myTargetType = targetType;
    }

    @Override
    public PsiExpression replace(PsiExpression expression, @NotNull TypeEvaluator evaluator) throws IncorrectOperationException {
      final PsiMethodCallExpression methodCall = (PsiMethodCallExpression)expression;
      final String methodName = methodCall.getMethodExpression().getReferenceName();

      final PsiExpression[] arguments = methodCall.getArgumentList().getExpressions();
      final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(expression.getProject());
      if (arguments.length == 1) {
        return (PsiExpression)expression.replace(GuavaConversionUtil.adjustLambdaContainingExpression(arguments[0], true, myTargetType, evaluator));
      }
      LOG.assertTrue(arguments.length != 0);
      StringBuilder replaceBy = new StringBuilder();
      for (int i = 1; i < arguments.length; i++) {
        PsiExpression argument = arguments[i];
        replaceBy.append(".").append(methodName).append("(").append(GuavaConversionUtil.adjustLambdaContainingExpression(argument, false, myTargetType, evaluator).getText()).append(")");
      }
      replaceBy.insert(0, GuavaConversionUtil.adjustLambdaContainingExpression(arguments[0], true, myTargetType, evaluator).getText());
      final PsiElement parent = expression.getParent();
      if (parent instanceof PsiMethodReferenceExpression) {
        expression = replaceTypeCast(expression, parent);
      }
      else if (!GuavaConversionUtil.isJavaLambda(parent, evaluator)) {
        replaceBy.append("::test");
      }
      return (PsiExpression)expression.replace(elementFactory.createExpressionFromText(replaceBy.toString(), expression));
    }
  }

  private static PsiExpression replaceTypeCast(PsiExpression expression, PsiElement parent) {
    final PsiElement parParent = parent.getParent();
    if (parParent instanceof PsiTypeCastExpression) {
      final PsiTypeElement typeElement = ((PsiTypeCastExpression)parParent).getCastType();
      if (typeElement != null) {
        final PsiType type = typeElement.getType();
        final PsiClass aClass = PsiTypesUtil.getPsiClass(type);
        if (aClass != null && GuavaLambda.PREDICATE.getClassQName().equals(aClass.getQualifiedName())) {
          expression = (PsiExpression)parParent.replace(expression);
        }
      }
    }
    return expression;
  }
}


text:
import Component from '@ember/component';
import { inject as service } from '@ember/service';
import { and, not } from '@ember/object/computed';

export default Component.extend({
  tagName: '',

  animation: service(),
  auth: service(),
  multiVcs: service(),
  router: service(),

  isLinkToSignin: false,
  isOpen: false,

  isNotLinkToSignin: not('isLinkToSignin'),
  isNotSignedIn: not('auth.signedIn'),
  isOpenable: and('isNotLinkToSignin', 'multiVcs.enabled'),

  showVcsOptions: and('isOpenable', 'isOpen'),

  clickMainButton() {
    if (this.isLinkToSignin) {
      this.router.transitionTo('signin');
    } else if (this.multiVcs.disabled) {
      this.auth.signIn();
    }
  },
  close() {
    this.set('isOpen', false);
  },
  open() {
    this.set('isOpen', this.isOpenable);
  },
  signInWith(provider) {
    this.auth.signInWith(provider);
  },
});


text:
package jp.tf_web.radiolink.bluetooth;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import jp.tf_web.radiolink.HomeActivity;

/** MEDIA_BUTTON のイベントを受け取る
 *
 * Created by furukawanobuyuki on 2015/12/28.
 */
public class BluetoothControlReceiver extends BroadcastReceiver {
    private static String TAG = "BluetoothControlReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "onReceive()");
        String action = intent.getAction();
        if(action.equals(Intent.ACTION_MEDIA_BUTTON)){
            Log.d(TAG, " action:"+action);
            //Activityに通知するためにブロードキャスト等をする
            MediaButtonReceiver.onClickMediaButton(context.getApplicationContext());
      }
    }
}


text:
package com.jme3.material;

import com.jme3.asset.AssetKey;
import com.jme3.asset.AssetManager;
import com.jme3.asset.CloneableSmartAsset;
import com.jme3.export.*;
import com.jme3.light.*;
import com.jme3.material.RenderState.BlendMode;
import com.jme3.material.RenderState.FaceCullMode;
import com.jme3.material.TechniqueDef.LightMode;
import com.jme3.material.TechniqueDef.ShadowMode;
import com.jme3.math.*;
import com.jme3.renderer.Caps;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.Renderer;
import com.jme3.renderer.RendererException;
import com.jme3.renderer.queue.RenderQueue.Bucket;
import com.jme3.scene.Geometry;
import com.jme3.scene.Mesh;
import com.jme3.scene.instancing.InstancedGeometry;
import com.jme3.shader.Shader;
import com.jme3.shader.Uniform;
import com.jme3.shader.VarType;
import com.jme3.texture.Texture;
import com.jme3.texture.image.ColorSpace;
import com.jme3.util.ListMap;
import com.jme3.util.TempVars;
import java.io.IOException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Material describes the rendering style for a given
 * {@link Geometry}.
 *
A material is essentially a list of {@link MatParam parameters},
 * those parameters map to uniforms which are defined in a shader.
 * Setting the parameters can modify the behavior of a
 * shader.
 *

 *
 * @author Kirill Vainer
 */
public class Material implements CloneableSmartAsset, Cloneable, Savable {

    // Version #2: Fixed issue with RenderState.apply*** flags not getting exported
    public static final int SAVABLE_VERSION = 2;
    private static final Logger logger = Logger.getLogger(Material.class.getName());
    private static final RenderState additiveLight = new RenderState();
    private static final RenderState depthOnly = new RenderState();
    private static final Quaternion nullDirLight = new Quaternion(0, -1, 0, -1);

    static {
        depthOnly.setDepthTest(true);
        depthOnly.setDepthWrite(true);
        depthOnly.setFaceCullMode(RenderState.FaceCullMode.Back);
        depthOnly.setColorWrite(false);

        additiveLight.setBlendMode(RenderState.BlendMode.AlphaAdditive);
        additiveLight.setDepthWrite(false);
    }
    private AssetKey key;
    private String name;
    private MaterialDef def;
    private ListMap<String, MatParam> paramValues = new ListMap<String, MatParam>();
    private Technique technique;
    private HashMap<String, Technique> techniques = new HashMap<String, Technique>();
    private int nextTexUnit = 0;
    private RenderState additionalState = null;
    private RenderState mergedRenderState = new RenderState();
    private boolean transparent = false;
    private boolean receivesShadows = false;
    private int sortingId = -1;
    private transient ColorRGBA ambientLightColor = new ColorRGBA(0, 0, 0, 1);

    public Material(MaterialDef def) {
        if (def == null) {
            throw new NullPointerException("Material definition cannot be null");
        }
        this.def = def;

        // Load default values from definition (if any)
        for (MatParam param : def.getMaterialParams()) {
            if (param.getValue() != null) {
                setParam(param.getName(), param.getVarType(), param.getValue());
            }
        }
    }

    public Material(AssetManager contentMan, String defName) {
        this((MaterialDef) contentMan.loadAsset(new AssetKey(defName)));
    }

    /**
     * Do not use this constructor. Serialization purposes only.
     */
    public Material() {
    }

    /**
     * Returns the asset key name of the asset from which this material was loaded.
     *
     *
This value will be null unless this material was loaded
     * from a .j3m file.
     *
     * @return Asset key name of the j3m file
     */
    public String getAssetName() {
        return key != null ? key.getName() : null;
    }

    /**
     * @return the name of the material (not the same as the asset name), the returned value can be null
     */
    public String getName() {
        return name;
    }

    /**
     * This method sets the name of the material.
     * The name is not the same as the asset name.
     * It can be null and there is no guarantee of its uniqueness.
     * @param name the name of the material
     */
    public void setName(String name) {
        this.name = name;
    }

    public void setKey(AssetKey key) {
        this.key = key;
    }

    public AssetKey getKey() {
        return key;
    }

    /**
     * Returns the sorting ID or sorting index for this material.
     *
     *
The sorting ID is used internally by the system to sort rendering
     * of geometries. It sorted to reduce shader switches, if the shaders
     * are equal, then it is sorted by textures.
     *
     * @return The sorting ID used for sorting geometries for rendering.
     */
    public int getSortId() {
        Technique t = getActiveTechnique();
        if (sortingId == -1 && t != null && t.getShader() != null) {
            int texId = -1;
            for (int i = 0; i < paramValues.size(); i++) {
                MatParam param = paramValues.getValue(i);
                if (param instanceof MatParamTexture) {
                    MatParamTexture tex = (MatParamTexture) param;
                    if (tex.getTextureValue() != null && tex.getTextureValue().getImage() != null) {
                        if (texId == -1) {
                            texId = 0;
                        }
                        texId += tex.getTextureValue().getImage().getId() % 0xff;
                    }
                }
            }
            sortingId = texId + t.getShader().getId() * 1000;
        }
        return sortingId;
    }

    /**
     * Clones this material. The result is returned.
     */
    @Override
    public Material clone() {
        try {
            Material mat = (Material) super.clone();

            if (additionalState != null) {
                mat.additionalState = additionalState.clone();
            }
            mat.technique = null;
            mat.techniques = new HashMap<String, Technique>();

            mat.paramValues = new ListMap<String, MatParam>();
            for (int i = 0; i < paramValues.size(); i++) {
                Map.Entry<String, MatParam> entry = paramValues.getEntry(i);
                mat.paramValues.put(entry.getKey(), entry.getValue().clone());
            }

            return mat;
        } catch (CloneNotSupportedException ex) {
            throw new AssertionError(ex);
        }
    }

    /**
     * Compares two materials and returns true if they are equal.
     * This methods compare definition, parameters, additional render states.
     * Since materials are mutable objects, implementing equals() properly is not possible,
     * hence the name contentEquals().
     *
     * @param otherObj the material to compare to this material
     * @return true if the materials are equal.
     */
    public boolean contentEquals(Object otherObj) {
        if (!(otherObj instanceof Material)) {
            return false;
        }

        Material other = (Material) otherObj;

        // Early exit if the material are the same object
        if (this == other) {
            return true;
        }

        // Check material definition
        if (this.getMaterialDef() != other.getMaterialDef()) {
            return false;
        }

        // Early exit if the size of the params is different
        if (this.paramValues.size() != other.paramValues.size()) {
            return false;
        }

        // Checking technique
        if (this.technique != null || other.technique != null) {
            // Techniques are considered equal if their names are the same
            // E.g. if user chose custom technique for one material but
            // uses default technique for other material, the materials
            // are not equal.
            String thisDefName = this.technique != null ? this.technique.getDef().getName() : "Default";
            String otherDefName = other.technique != null ? other.technique.getDef().getName() : "Default";
            if (!thisDefName.equals(otherDefName)) {
                return false;
            }
        }

        // Comparing parameters
        for (String paramKey : paramValues.keySet()) {
            MatParam thisParam = this.getParam(paramKey);
            MatParam otherParam = other.getParam(paramKey);

            // This param does not exist in compared mat
            if (otherParam == null) {
                return false;
            }

            if (!otherParam.equals(thisParam)) {
                return false;
            }
        }

        // Comparing additional render states
        if (additionalState == null) {
            if (other.additionalState != null) {
                return false;
            }
        } else {
            if (!additionalState.equals(other.additionalState)) {
                return false;
            }
        }

        return true;
    }

    /**
     * Works like {@link Object#hashCode() } except it may change together with the material as the material is mutable by definition.
     */
    public int contentHashCode() {
        int hash = 7;
        hash = 29 * hash + (this.def != null ? this.def.hashCode() : 0);
        hash = 29 * hash + (this.paramValues != null ? this.paramValues.hashCode() : 0);
        hash = 29 * hash + (this.technique != null ? this.technique.getDef().getName().hashCode() : 0);
        hash = 29 * hash + (this.additionalState != null ? this.additionalState.contentHashCode() : 0);
        return hash;
    }

    /**
     * Returns the currently active technique.
     *

     * The technique is selected automatically by the {@link RenderManager}
     * based on system capabilities. Users may select their own
     * technique by using
     * {@link #selectTechnique(java.lang.String, com.jme3.renderer.RenderManager) }.
     *
     * @return the currently active technique.
     *
     * @see #selectTechnique(java.lang.String, com.jme3.renderer.RenderManager)
     */
    public Technique getActiveTechnique() {
        return technique;
    }

    /**
     * Check if the transparent value marker is set on this material.
     * @return True if the transparent value marker is set on this material.
     * @see #setTransparent(boolean)
     */
    public boolean isTransparent() {
        return transparent;
    }

    /**
     * Set the transparent value marker.
     *
     *
This value is merely a marker, by itself it does nothing.
     * Generally model loaders will use this marker to indicate further
     * up that the material is transparent and therefore any geometries
     * using it should be put into the {@link Bucket#Transparent transparent
     * bucket}.
     *
     * @param transparent the transparent value marker.
     */
    public void setTransparent(boolean transparent) {
        this.transparent = transparent;
    }

    /**
     * Check if the material should receive shadows or not.
     *
     * @return True if the material should receive shadows.
     *
     * @see Material#setReceivesShadows(boolean)
     */
    public boolean isReceivesShadows() {
        return receivesShadows;
    }

    /**
     * Set if the material should receive shadows or not.
     *
     *
This value is merely a marker, by itself it does nothing.
     * Generally model loaders will use this marker to indicate
     * the material should receive shadows and therefore any
     * geometries using it should have the {@link ShadowMode#Receive} set
     * on them.
     *
     * @param receivesShadows if the material should receive shadows or not.
     */
    public void setReceivesShadows(boolean receivesShadows) {
        this.receivesShadows = receivesShadows;
    }

    /**
     * Acquire the additional {@link RenderState render state} to apply
     * for this material.
     *
     *
The first call to this method will create an additional render
     * state which can be modified by the user to apply any render
     * states in addition to the ones used by the renderer. Only render
     * states which are modified in the additional render state will be applied.
     *
     * @return The additional render state.
     */
    public RenderState getAdditionalRenderState() {
        if (additionalState == null) {
            additionalState = RenderState.ADDITIONAL.clone();
        }
        return additionalState;
    }

    /**
     * Get the material definition (j3md file info) that this
     * material is implementing.
     *
     * @return the material definition this material implements.
     */
    public MaterialDef getMaterialDef() {
        return def;
    }

    /**
     * Returns the parameter set on this material with the given name,
     * returns null if the parameter is not set.
     *
     * @param name The parameter name to look up.
     * @return The MatParam if set, or null if not set.
     */
    public MatParam getParam(String name) {
        return paramValues.get(name);
    }

    /**
     * Returns the texture parameter set on this material with the given name,
     * returns null if the parameter is not set.
     *
     * @param name The parameter name to look up.
     * @return The MatParamTexture if set, or null if not set.
     */
    public MatParamTexture getTextureParam(String name) {
        MatParam param = paramValues.get(name);
        if (param instanceof MatParamTexture) {
            return (MatParamTexture) param;
        }
        return null;
    }

    /**
     * Returns a collection of all parameters set on this material.
     *
     * @return a collection of all parameters set on this material.
     *
     * @see #setParam(java.lang.String, com.jme3.shader.VarType, java.lang.Object)
     */
    public Collection<MatParam> getParams() {
        return paramValues.values();
    }

    /**
     * Returns the ListMap of all parameters set on this material.
     *
     * @return a ListMap of all parameters set on this material.
     *
     * @see #setParam(java.lang.String, com.jme3.shader.VarType, java.lang.Object)
     */
    public ListMap getParamsMap() {
        return paramValues;
    }

    /**
     * Check if setting the parameter given the type and name is allowed.
     * @param type The type that the "set" function is designed to set
     * @param name The name of the parameter
     */
    private void checkSetParam(VarType type, String name) {
        MatParam paramDef = def.getMaterialParam(name);
        if (paramDef == null) {
            throw new IllegalArgumentException("Material parameter is not defined: " + name);
        }
        if (type != null && paramDef.getVarType() != type) {
            logger.log(Level.WARNING, "Material parameter being set: {0} with "
                    + "type {1} doesn''t match definition types {2}", new Object[]{name, type.name(), paramDef.getVarType()});
        }
    }

    /**
     * Pass a parameter to the material shader.
     *
     * @param name the name of the parameter defined in the material definition (j3md)
     * @param type the type of the parameter {@link VarType}
     * @param value the value of the parameter
     */
    public void setParam(String name, VarType type, Object value) {
        checkSetParam(type, name);

        if (type.isTextureType()) {
            setTextureParam(name, type, (Texture)value);
        } else {
            MatParam val = getParam(name);
            if (val == null) {
                MatParam paramDef = def.getMaterialParam(name);
                paramValues.put(name, new MatParam(type, name, value));
            } else {
                val.setValue(value);
            }

            if (technique != null) {
                technique.notifyParamChanged(name, type, value);
            }
        }
    }

    /**
     * Clear a parameter from this material. The parameter must exist
     * @param name the name of the parameter to clear
     */
    public void clearParam(String name) {
        checkSetParam(null, name);
        MatParam matParam = getParam(name);
        if (matParam == null) {
            return;
        }

        paramValues.remove(name);
        if (matParam instanceof MatParamTexture) {
            int texUnit = ((MatParamTexture) matParam).getUnit();
            nextTexUnit--;
            for (MatParam param : paramValues.values()) {
                if (param instanceof MatParamTexture) {
                    MatParamTexture texParam = (MatParamTexture) param;
                    if (texParam.getUnit() > texUnit) {
                        texParam.setUnit(texParam.getUnit() - 1);
                    }
                }
            }
            sortingId = -1;
        }
        if (technique != null) {
            technique.notifyParamChanged(name, null, null);
        }
    }

    /**
     * Set a texture parameter.
     *
     * @param name The name of the parameter
     * @param type The variable type {@link VarType}
     * @param value The texture value of the parameter.
     *
     * @throws IllegalArgumentException is value is null
     */
    public void setTextureParam(String name, VarType type, Texture value) {
        if (value == null) {
            throw new IllegalArgumentException();
        }

        checkSetParam(type, name);
        MatParamTexture val = getTextureParam(name);
        if (val == null) {
            MatParamTexture paramDef = (MatParamTexture) def.getMaterialParam(name);
            if (paramDef.getColorSpace() != null && paramDef.getColorSpace() != value.getImage().getColorSpace()) {
                value.getImage().setColorSpace(paramDef.getColorSpace());
                logger.log(Level.FINE, "Material parameter {0} needs a {1} texture, "
                        + "texture {2} was switched to {3} color space.",
                        new Object[]{name, paramDef.getColorSpace().toString(),
                            value.getName(),
                            value.getImage().getColorSpace().name()});
            } else if (paramDef.getColorSpace() == null && value.getName() != null && value.getImage().getColorSpace() == ColorSpace.Linear) {
                logger.log(Level.WARNING,
                        "The texture {0} has linear color space, but the material "
                        + "parameter {2} specifies no color space requirement, this may "
                        + "lead to unexpected behavior.\nCheck if the image "
                        + "was not set to another material parameter with a linear "
                        + "color space, or that you did not set the ColorSpace to "
                        + "Linear using texture.getImage.setColorSpace().",
                        new Object[]{value.getName(), value.getImage().getColorSpace().name(), name});
            }
            paramValues.put(name, new MatParamTexture(type, name, value, nextTexUnit++, null));
        } else {
            val.setTextureValue(value);
        }

        if (technique != null) {
            technique.notifyParamChanged(name, type, nextTexUnit - 1);
        }

        // need to recompute sort ID
        sortingId = -1;
    }

    /**
     * Pass a texture to the material shader.
     *
     * @param name the name of the texture defined in the material definition
     * (j3md) (for example Texture for Lighting.j3md)
     * @param value the Texture object previously loaded by the asset manager
     */
    public void setTexture(String name, Texture value) {
        if (value == null) {
            // clear it
            clearParam(name);
            return;
        }

        VarType paramType = null;
        switch (value.getType()) {
            case TwoDimensional:
                paramType = VarType.Texture2D;
                break;
            case TwoDimensionalArray:
                paramType = VarType.TextureArray;
                break;
            case ThreeDimensional:
                paramType = VarType.Texture3D;
                break;
            case CubeMap:
                paramType = VarType.TextureCubeMap;
                break;
            default:
                throw new UnsupportedOperationException("Unknown texture type: " + value.getType());
        }

        setTextureParam(name, paramType, value);
    }

    /**
     * Pass a Matrix4f to the material shader.
     *
     * @param name the name of the matrix defined in the material definition (j3md)
     * @param value the Matrix4f object
     */
    public void setMatrix4(String name, Matrix4f value) {
        setParam(name, VarType.Matrix4, value);
    }

    /**
     * Pass a boolean to the material shader.
     *
     * @param name the name of the boolean defined in the material definition (j3md)
     * @param value the boolean value
     */
    public void setBoolean(String name, boolean value) {
        setParam(name, VarType.Boolean, value);
    }

    /**
     * Pass a float to the material shader.
     *
     * @param name the name of the float defined in the material definition (j3md)
     * @param value the float value
     */
    public void setFloat(String name, float value) {
        setParam(name, VarType.Float, value);
    }

    /**
     * Pass a float to the material shader.  This version avoids auto-boxing
     * if the value is already a Float.
     *
     * @param name the name of the float defined in the material definition (j3md)
     * @param value the float value
     */
    public void setFloat(String name, Float value) {
        setParam(name, VarType.Float, value);
    }

    /**
     * Pass an int to the material shader.
     *
     * @param name the name of the int defined in the material definition (j3md)
     * @param value the int value
     */
    public void setInt(String name, int value) {
        setParam(name, VarType.Int, value);
    }

    /**
     * Pass a Color to the material shader.
     *
     * @param name the name of the color defined in the material definition (j3md)
     * @param value the ColorRGBA value
     */
    public void setColor(String name, ColorRGBA value) {
        setParam(name, VarType.Vector4, value);
    }

    /**
     * Pass a Vector2f to the material shader.
     *
     * @param name the name of the Vector2f defined in the material definition (j3md)
     * @param value the Vector2f value
     */
    public void setVector2(String name, Vector2f value) {
        setParam(name, VarType.Vector2, value);
    }

    /**
     * Pass a Vector3f to the material shader.
     *
     * @param name the name of the Vector3f defined in the material definition (j3md)
     * @param value the Vector3f value
     */
    public void setVector3(String name, Vector3f value) {
        setParam(name, VarType.Vector3, value);
    }

    /**
     * Pass a Vector4f to the material shader.
     *
     * @param name the name of the Vector4f defined in the material definition (j3md)
     * @param value the Vector4f value
     */
    public void setVector4(String name, Vector4f value) {
        setParam(name, VarType.Vector4, value);
    }

    private ColorRGBA getAmbientColor(LightList lightList, boolean removeLights) {
        ambientLightColor.set(0, 0, 0, 1);
        for (int j = 0; j < lightList.size(); j++) {
            Light l = lightList.get(j);
            if (l instanceof AmbientLight) {
                ambientLightColor.addLocal(l.getColor());
                if(removeLights){
                    lightList.remove(l);
                }
            }
        }
        ambientLightColor.a = 1.0f;
        return ambientLightColor;
    }

    private static void renderMeshFromGeometry(Renderer renderer, Geometry geom) {
        Mesh mesh = geom.getMesh();
        int lodLevel = geom.getLodLevel();
        if (geom instanceof InstancedGeometry) {
            InstancedGeometry instGeom = (InstancedGeometry) geom;
            int numInstances = instGeom.getActualNumInstances();
            if (numInstances == 0) {
                return;
            }
            if (renderer.getCaps().contains(Caps.MeshInstancing)) {
                renderer.renderMesh(mesh, lodLevel, numInstances, instGeom.getAllInstanceData());
            } else {
                throw new RendererException("Mesh instancing is not supported by the video hardware");
            }
        } else {
            renderer.renderMesh(mesh, lodLevel, 1, null);
        }
    }

    /**
     * Uploads the lights in the light list as two uniform arrays.

 *
     *

     * uniform vec4 g_LightColor[numLights];
 //
     * g_LightColor.rgb is the diffuse/specular color of the light.
 //
     * g_Lightcolor.a is the type of light, 0 = Directional, 1 = Point,
 //
     * 2 = Spot.

     * uniform vec4 g_LightPosition[numLights];
 //
     * g_LightPosition.xyz is the position of the light (for point lights)

     * // or the direction of the light (for directional lights).
 //
     * g_LightPosition.w is the inverse radius (1/r) of the light (for
     * attenuation)

     */
    protected int updateLightListUniforms(Shader shader, Geometry g, LightList lightList, int numLights, RenderManager rm, int startIndex) {
        if (numLights == 0) { // this shader does not do lighting, ignore.
            return 0;
        }

        Uniform lightData = shader.getUniform("g_LightData");
        lightData.setVector4Length(numLights * 3);//8 lights * max 3
        Uniform ambientColor = shader.getUniform("g_AmbientLightColor");

        if (startIndex != 0) {
            // apply additive blending for 2nd and future passes
            rm.getRenderer().applyRenderState(additiveLight);
            ambientColor.setValue(VarType.Vector4, ColorRGBA.Black);
        }else{
            ambientColor.setValue(VarType.Vector4, getAmbientColor(lightList,true));
        }

        int lightDataIndex = 0;
        TempVars vars = TempVars.get();
        Vector4f tmpVec = vars.vect4f1;
        int curIndex;
        int endIndex = numLights + startIndex;
        for (curIndex = startIndex; curIndex < endIndex && curIndex < lightList.size(); curIndex++) {

                Light l = lightList.get(curIndex);
                if(l.getType() == Light.Type.Ambient){
                    endIndex++;
                    continue;
                }
                ColorRGBA color = l.getColor();
                //Color
                lightData.setVector4InArray(color.getRed(),
                        color.getGreen(),
                        color.getBlue(),
                        l.getType().getId(),
                        lightDataIndex);
                lightDataIndex++;

                switch (l.getType()) {
                    case Directional:
                        DirectionalLight dl = (DirectionalLight) l;
                        Vector3f dir = dl.getDirection();
                        //Data directly sent in view space to avoid a matrix mult for each pixel
                        tmpVec.set(dir.getX(), dir.getY(), dir.getZ(), 0.0f);
                        rm.getCurrentCamera().getViewMatrix().mult(tmpVec, tmpVec);
//                        tmpVec.divideLocal(tmpVec.w);
//                        tmpVec.normalizeLocal();
                        lightData.setVector4InArray(tmpVec.getX(), tmpVec.getY(), tmpVec.getZ(), -1, lightDataIndex);
                        lightDataIndex++;
                        //PADDING
                        lightData.setVector4InArray(0,0,0,0, lightDataIndex);
                        lightDataIndex++;
                        break;
                    case Point:
                        PointLight pl = (PointLight) l;
                        Vector3f pos = pl.getPosition();
                        float invRadius = pl.getInvRadius();
                        tmpVec.set(pos.getX(), pos.getY(), pos.getZ(), 1.0f);
                        rm.getCurrentCamera().getViewMatrix().mult(tmpVec, tmpVec);
                        //tmpVec.divideLocal(tmpVec.w);
                        lightData.setVector4InArray(tmpVec.getX(), tmpVec.getY(), tmpVec.getZ(), invRadius, lightDataIndex);
                        lightDataIndex++;
                        //PADDING
                        lightData.setVector4InArray(0,0,0,0, lightDataIndex);
                        lightDataIndex++;
                        break;
                    case Spot:
                        SpotLight sl = (SpotLight) l;
                        Vector3f pos2 = sl.getPosition();
                        Vector3f dir2 = sl.getDirection();
                        float invRange = sl.getInvSpotRange();
                        float spotAngleCos = sl.getPackedAngleCos();
                        tmpVec.set(pos2.getX(), pos2.getY(), pos2.getZ(),  1.0f);
                        rm.getCurrentCamera().getViewMatrix().mult(tmpVec, tmpVec);
                       // tmpVec.divideLocal(tmpVec.w);
                        lightData.setVector4InArray(tmpVec.getX(), tmpVec.getY(), tmpVec.getZ(), invRange, lightDataIndex);
                        lightDataIndex++;

                        //We transform the spot direction in view space here to save 5 varying later in the lighting shader
                        //one vec4 less and a vec4 that becomes a vec3
                        //the downside is that spotAngleCos decoding happens now in the frag shader.
                        tmpVec.set(dir2.getX(), dir2.getY(), dir2.getZ(),  0.0f);
                        rm.getCurrentCamera().getViewMatrix().mult(tmpVec, tmpVec);
                        tmpVec.normalizeLocal();
                        lightData.setVector4InArray(tmpVec.getX(), tmpVec.getY(), tmpVec.getZ(), spotAngleCos, lightDataIndex);
                        lightDataIndex++;
                        break;
                    default:
                        throw new UnsupportedOperationException("Unknown type of light: " + l.getType());
                }
        }
        vars.release();
        //Padding of unsued buffer space
        while(lightDataIndex < numLights * 3) {
            lightData.setVector4InArray(0f, 0f, 0f, 0f, lightDataIndex);
            lightDataIndex++;
        }
        return curIndex;
    }

    protected void renderMultipassLighting(Shader shader, Geometry g, LightList lightList, RenderManager rm) {

        Renderer r = rm.getRenderer();
        Uniform lightDir = shader.getUniform("g_LightDirection");
        Uniform lightColor = shader.getUniform("g_LightColor");
        Uniform lightPos = shader.getUniform("g_LightPosition");
        Uniform ambientColor = shader.getUniform("g_AmbientLightColor");
        boolean isFirstLight = true;
        boolean isSecondLight = false;

        for (int i = 0; i < lightList.size(); i++) {
            Light l = lightList.get(i);
            if (l instanceof AmbientLight) {
                continue;
            }

            if (isFirstLight) {
                // set ambient color for first light only
                ambientColor.setValue(VarType.Vector4, getAmbientColor(lightList, false));
                isFirstLight = false;
                isSecondLight = true;
            } else if (isSecondLight) {
                ambientColor.setValue(VarType.Vector4, ColorRGBA.Black);
                // apply additive blending for 2nd and future lights
                r.applyRenderState(additiveLight);
                isSecondLight = false;
            }

            TempVars vars = TempVars.get();
            Quaternion tmpLightDirection = vars.quat1;
            Quaternion tmpLightPosition = vars.quat2;
            ColorRGBA tmpLightColor = vars.color;
            Vector4f tmpVec = vars.vect4f1;

            ColorRGBA color = l.getColor();
            tmpLightColor.set(color);
            tmpLightColor.a = l.getType().getId();
            lightColor.setValue(VarType.Vector4, tmpLightColor);

            switch (l.getType()) {
                case Directional:
                    DirectionalLight dl = (DirectionalLight) l;
                    Vector3f dir = dl.getDirection();
                    //FIXME : there is an inconstency here due to backward
                    //compatibility of the lighting shader.
                    //The directional light direction is passed in the
                    //LightPosition uniform. The lighting shader needs to be
                    //reworked though in order to fix this.
                    tmpLightPosition.set(dir.getX(), dir.getY(), dir.getZ(), -1);
                    lightPos.setValue(VarType.Vector4, tmpLightPosition);
                    tmpLightDirection.set(0, 0, 0, 0);
                    lightDir.setValue(VarType.Vector4, tmpLightDirection);
                    break;
                case Point:
                    PointLight pl = (PointLight) l;
                    Vector3f pos = pl.getPosition();
                    float invRadius = pl.getInvRadius();

                    tmpLightPosition.set(pos.getX(), pos.getY(), pos.getZ(), invRadius);
                    lightPos.setValue(VarType.Vector4, tmpLightPosition);
                    tmpLightDirection.set(0, 0, 0, 0);
                    lightDir.setValue(VarType.Vector4, tmpLightDirection);
                    break;
                case Spot:
                    SpotLight sl = (SpotLight) l;
                    Vector3f pos2 = sl.getPosition();
                    Vector3f dir2 = sl.getDirection();
                    float invRange = sl.getInvSpotRange();
                    float spotAngleCos = sl.getPackedAngleCos();

                    tmpLightPosition.set(pos2.getX(), pos2.getY(), pos2.getZ(), invRange);
                    lightPos.setValue(VarType.Vector4, tmpLightPosition);

                    //We transform the spot direction in view space here to save 5 varying later in the lighting shader
                    //one vec4 less and a vec4 that becomes a vec3
                    //the downside is that spotAngleCos decoding happens now in the frag shader.
                    tmpVec.set(dir2.getX(), dir2.getY(), dir2.getZ(), 0);
                    rm.getCurrentCamera().getViewMatrix().mult(tmpVec, tmpVec);
                    tmpLightDirection.set(tmpVec.getX(), tmpVec.getY(), tmpVec.getZ(), spotAngleCos);

                    lightDir.setValue(VarType.Vector4, tmpLightDirection);

                    break;
                default:
                    throw new UnsupportedOperationException("Unknown type of light: " + l.getType());
            }
            vars.release();
            r.setShader(shader);
            renderMeshFromGeometry(r, g);
        }

        if (isFirstLight) {
            // Either there are no lights at all, or only ambient lights.
            // Render a dummy "normal light" so we can see the ambient color.
            ambientColor.setValue(VarType.Vector4, getAmbientColor(lightList, false));
            lightColor.setValue(VarType.Vector4, ColorRGBA.BlackNoAlpha);
            lightPos.setValue(VarType.Vector4, nullDirLight);
            r.setShader(shader);
            renderMeshFromGeometry(r, g);
        }
    }

    /**
     * Select the technique to use for rendering this material.
     *

     * If name is "Default", then one of the
     * {@link MaterialDef#getDefaultTechniques() default techniques}
     * on the material will be selected. Otherwise, the named technique
     * will be found in the material definition.
     *

     * Any candidate technique for selection (either default or named)
     * must be verified to be compatible with the system, for that, the
     * renderManager is queried for capabilities.
     *
     * @param name The name of the technique to select, pass "Default" to
     * select one of the default techniques.
     * @param renderManager The {@link RenderManager render manager}
     * to query for capabilities.
     *
     * @throws IllegalArgumentException If "Default" is passed and no default
     * techniques are available on the material definition, or if a name
     * is passed but there's no technique by that name.
     * @throws UnsupportedOperationException If no candidate technique supports
     * the system capabilities.
     */
    public void selectTechnique(String name, RenderManager renderManager) {
        // check if already created
        Technique tech = techniques.get(name);
        // When choosing technique, we choose one that
        // supports all the caps.
        EnumSet<Caps> rendererCaps = renderManager.getRenderer().getCaps();
        if (tech == null) {

            if (name.equals("Default")) {
                List<TechniqueDef> techDefs = def.getDefaultTechniques();
                if (techDefs == null || techDefs.isEmpty()) {
                    throw new IllegalArgumentException("No default techniques are available on material '" + def.getName() + "'");
                }

                TechniqueDef lastTech = null;
                for (TechniqueDef techDef : techDefs) {
                    if (rendererCaps.containsAll(techDef.getRequiredCaps())) {
                        // use the first one that supports all the caps
                        tech = new Technique(this, techDef);
                        techniques.put(name, tech);
                        if(tech.getDef().getLightMode() == renderManager.getPreferredLightMode() ||
                               tech.getDef().getLightMode() == LightMode.Disable){
                            break;
                        }
                    }
                    lastTech = techDef;
                }
                if (tech == null) {
                    throw new UnsupportedOperationException("No default technique on material '" + def.getName() + "'\n"
                            + " is supported by the video hardware. The caps "
                            + lastTech.getRequiredCaps() + " are required.");
                }

            } else {
                // create "special" technique instance
                TechniqueDef techDef = def.getTechniqueDef(name);
                if (techDef == null) {
                    throw new IllegalArgumentException("For material " + def.getName() + ", technique not found: " + name);
                }

                if (!rendererCaps.containsAll(techDef.getRequiredCaps())) {
                    throw new UnsupportedOperationException("The explicitly chosen technique '" + name + "' on material '" + def.getName() + "'\n"
                            + "requires caps " + techDef.getRequiredCaps() + " which are not "
                            + "supported by the video renderer");
                }

                tech = new Technique(this, techDef);
                techniques.put(name, tech);
            }
        } else if (technique == tech) {
            // attempting to switch to an already
            // active technique.
            return;
        }

        technique = tech;
        tech.makeCurrent(def.getAssetManager(), true, rendererCaps, renderManager);

        // shader was changed
        sortingId = -1;
    }

    private void autoSelectTechnique(RenderManager rm) {
        if (technique == null) {
            selectTechnique("Default", rm);
        } else {
            technique.makeCurrent(def.getAssetManager(), false, rm.getRenderer().getCaps(), rm);
        }
    }

    /**
     * Preloads this material for the given render manager.
     *

     * Preloading the material can ensure that when the material is first
     * used for rendering, there won't be any delay since the material has
     * been already been setup for rendering.
     *
     * @param rm The render manager to preload for
     */
    public void preload(RenderManager rm) {
        autoSelectTechnique(rm);

        Renderer r = rm.getRenderer();
        TechniqueDef techDef = technique.getDef();

        Collection<MatParam> params = paramValues.values();
        for (MatParam param : params) {
            param.apply(r, technique);
        }

        r.setShader(technique.getShader());
    }

    private void clearUniformsSetByCurrent(Shader shader) {
        ListMap<String, Uniform> uniforms = shader.getUniformMap();
        int size = uniforms.size();
        for (int i = 0; i < size; i++) {
            Uniform u = uniforms.getValue(i);
            u.clearSetByCurrentMaterial();
        }
    }

    private void resetUniformsNotSetByCurrent(Shader shader) {
        ListMap<String, Uniform> uniforms = shader.getUniformMap();
        int size = uniforms.size();
        for (int i = 0; i < size; i++) {
            Uniform u = uniforms.getValue(i);
            if (!u.isSetByCurrentMaterial()) {
                if (u.getName().charAt(0) != 'g') {
                    // Don't reset world globals!
                    // The benefits gained from this are very minimal
                    // and cause lots of matrix -> FloatBuffer conversions.
                    u.clearValue();
                }
            }
        }
    }

    /**
     * Called by {@link RenderManager} to render the geometry by
     * using this material.
     *

     * The material is rendered as follows:
     *

     *
Determine which technique to use to render the material -
     * either what the user selected via
     * {@link #selectTechnique(java.lang.String, com.jme3.renderer.RenderManager)
     * Material.selectTechnique()},
     * or the first default technique that the renderer supports
     * (based on the technique's {@link TechniqueDef#getRequiredCaps() requested rendering capabilities})

     *
If the technique has been changed since the last frame, then it is notified via
     * {@link Technique#makeCurrent(com.jme3.asset.AssetManager, boolean, java.util.EnumSet)
     * Technique.makeCurrent()}.
     * If the technique wants to use a shader to render the model, it should load it at this part -
     * the shader should have all the proper defines as declared in the technique definition,
     * including those that are bound to material parameters.
     * The technique can re-use the shader from the last frame if
     * no changes to the defines occurred.

     *
Set the {@link RenderState} to use for rendering. The render states are
     * applied in this order (later RenderStates override earlier RenderStates):

     *
{@link TechniqueDef#getRenderState() Technique Definition's RenderState}
     * - i.e. specific renderstate that is required for the shader.

     *
{@link #getAdditionalRenderState() Material Instance Additional RenderState}
     * - i.e. ad-hoc renderstate set per model

     *
{@link RenderManager#getForcedRenderState() RenderManager's Forced RenderState}
     * - i.e. renderstate requested by a {@link com.jme3.post.SceneProcessor} or
     * post-processing filter.

     *
If the technique {@link TechniqueDef#isUsingShaders() uses a shader}, then the uniforms of the shader must be updated.

     *
Uniforms bound to material parameters are updated based on the current material parameter values.

     *
Uniforms bound to world parameters are updated from the RenderManager.
     * Internally {@link UniformBindingManager} is used for this task.

     *
Uniforms bound to textures will cause the texture to be uploaded as necessary.
     * The uniform is set to the texture unit where the texture is bound.

     *
If the technique uses a shader, the model is then rendered according
     * to the lighting mode specified on the technique definition.

     *
{@link LightMode#SinglePass single pass light mode} fills the shader's light uniform arrays
     * with the first 4 lights and renders the model once.

     *
{@link LightMode#MultiPass multi pass light mode} light mode renders the model multiple times,
     * for the first light it is rendered opaque, on subsequent lights it is
     * rendered with {@link BlendMode#AlphaAdditive alpha-additive} blending and depth writing disabled.

     *

     *
For techniques that do not use shaders,
     * fixed function OpenGL is used to render the model (see {@link GL1Renderer} interface):

     *
OpenGL state ({@link FixedFuncBinding}) that is bound to material parameters is updated.

     *
The texture set on the material is uploaded and bound.
     * Currently only 1 texture is supported for fixed function techniques.

     *
If the technique uses lighting, then OpenGL lighting state is updated
     * based on the light list on the geometry, otherwise OpenGL lighting is disabled.

     *
The mesh is uploaded and rendered.

     *

     *

     *
     * @param geom The geometry to render
     * @param lights Presorted and filtered light list to use for rendering
     * @param rm The render manager requesting the rendering
     */
    public void render(Geometry geom, LightList lights, RenderManager rm) {
        autoSelectTechnique(rm);

        Renderer r = rm.getRenderer();

        TechniqueDef techDef = technique.getDef();

        if (rm.getForcedRenderState() != null) {
            r.applyRenderState(rm.getForcedRenderState());
        } else {
            if (techDef.getRenderState() != null) {
                r.applyRenderState(techDef.getRenderState().copyMergedTo(additionalState, mergedRenderState));
            } else {
                r.applyRenderState(RenderState.DEFAULT.copyMergedTo(additionalState, mergedRenderState));
            }
        }

        // update camera and world matrices
        // NOTE: setWorldTransform should have been called already

        // reset unchanged uniform flag
        clearUniformsSetByCurrent(technique.getShader());
        rm.updateUniformBindings(technique.getWorldBindUniforms());

        // setup textures and uniforms
        for (int i = 0; i < paramValues.size(); i++) {
            MatParam param = paramValues.getValue(i);
            param.apply(r, technique);
        }

        Shader shader = technique.getShader();

        // send lighting information, if needed
        switch (techDef.getLightMode()) {
            case Disable:
                break;
            case SinglePass:
                int nbRenderedLights = 0;
                resetUniformsNotSetByCurrent(shader);
                if (lights.size() == 0) {
                    nbRenderedLights = updateLightListUniforms(shader, geom, lights, rm.getSinglePassLightBatchSize(), rm, 0);
                    r.setShader(shader);
                    renderMeshFromGeometry(r, geom);
                } else {
                    while (nbRenderedLights < lights.size()) {
                        nbRenderedLights = updateLightListUniforms(shader, geom, lights, rm.getSinglePassLightBatchSize(), rm, nbRenderedLights);
                        r.setShader(shader);
                        renderMeshFromGeometry(r, geom);
                    }
                }
                return;
            case FixedPipeline:
                throw new IllegalArgumentException("OpenGL1 is not supported");
            case MultiPass:
                // NOTE: Special case!
                resetUniformsNotSetByCurrent(shader);
                renderMultipassLighting(shader, geom, lights, rm);
                // very important, notice the return statement!
                return;
        }

        // upload and bind shader
        // any unset uniforms will be set to 0
        resetUniformsNotSetByCurrent(shader);
        r.setShader(shader);

        renderMeshFromGeometry(r, geom);
    }

    /**
     * Called by {@link RenderManager} to render the geometry by
     * using this material.
     *
     * Note that this version of the render method
     * does not perform light filtering.
     *
     * @param geom The geometry to render
     * @param rm The render manager requesting the rendering
     */
    public void render(Geometry geom, RenderManager rm) {
        render(geom, geom.getWorldLightList(), rm);
    }

    public void write(JmeExporter ex) throws IOException {
        OutputCapsule oc = ex.getCapsule(this);
        oc.write(def.getAssetName(), "material_def", null);
        oc.write(additionalState, "render_state", null);
        oc.write(transparent, "is_transparent", false);
        oc.writeStringSavableMap(paramValues, "parameters", null);
    }

    public void read(JmeImporter im) throws IOException {
        InputCapsule ic = im.getCapsule(this);

        additionalState = (RenderState) ic.readSavable("render_state", null);
        transparent = ic.readBoolean("is_transparent", false);

        // Load the material def
        String defName = ic.readString("material_def", null);
        HashMap<String, MatParam> params = (HashMap<String, MatParam>) ic.readStringSavableMap("parameters", null);

        boolean enableVcolor = false;
        boolean separateTexCoord = false;
        boolean applyDefaultValues = false;
        boolean guessRenderStateApply = false;

        int ver = ic.getSavableVersion(Material.class);
        if (ver < 1) {
            applyDefaultValues = true;
        }
        if (ver < 2) {
            guessRenderStateApply = true;
        }
        if (im.getFormatVersion() == 0) {
            // Enable compatibility with old models
            if (defName.equalsIgnoreCase("Common/MatDefs/Misc/VertexColor.j3md")) {
                // Using VertexColor, switch to Unshaded and set VertexColor=true
                enableVcolor = true;
                defName = "Common/MatDefs/Misc/Unshaded.j3md";
            } else if (defName.equalsIgnoreCase("Common/MatDefs/Misc/SimpleTextured.j3md")
                    || defName.equalsIgnoreCase("Common/MatDefs/Misc/SolidColor.j3md")) {
                // Using SimpleTextured/SolidColor, just switch to Unshaded
                defName = "Common/MatDefs/Misc/Unshaded.j3md";
            } else if (defName.equalsIgnoreCase("Common/MatDefs/Misc/WireColor.j3md")) {
                // Using WireColor, set wireframe renderstate = true and use Unshaded
                getAdditionalRenderState().setWireframe(true);
                defName = "Common/MatDefs/Misc/Unshaded.j3md";
            } else if (defName.equalsIgnoreCase("Common/MatDefs/Misc/Unshaded.j3md")) {
                // Uses unshaded, ensure that the proper param is set
                MatParam value = params.get("SeperateTexCoord");
                if (value != null && ((Boolean) value.getValue()) == true) {
                    params.remove("SeperateTexCoord");
                    separateTexCoord = true;
                }
            }
            assert applyDefaultValues && guessRenderStateApply;
        }

        def = (MaterialDef) im.getAssetManager().loadAsset(new AssetKey(defName));
        paramValues = new ListMap<String, MatParam>();

        // load the textures and update nextTexUnit
        for (Map.Entry<String, MatParam> entry : params.entrySet()) {
            MatParam param = entry.getValue();
            if (param instanceof MatParamTexture) {
                MatParamTexture texVal = (MatParamTexture) param;

                if (nextTexUnit < texVal.getUnit() + 1) {
                    nextTexUnit = texVal.getUnit() + 1;
                }

                // the texture failed to load for this param
                // do not add to param values
                if (texVal.getTextureValue() == null || texVal.getTextureValue().getImage() == null) {
                    continue;
                }
            }

            if (im.getFormatVersion() == 0 && param.getName().startsWith("m_")) {
                // Ancient version of jME3 ...
                param.setName(param.getName().substring(2));
            }

            if (def.getMaterialParam(param.getName()) == null) {
                logger.log(Level.WARNING, "The material parameter is not defined: {0}. Ignoring..",
                                          param.getName());
            } else {
                checkSetParam(param.getVarType(), param.getName());
                paramValues.put(param.getName(), param);
            }
        }

        if (applyDefaultValues) {
            // compatability with old versions where default vars were
            // not available
            for (MatParam param : def.getMaterialParams()) {
                if (param.getValue() != null && paramValues.get(param.getName()) == null) {
                    setParam(param.getName(), param.getVarType(), param.getValue());
                }
            }
        }
        if (guessRenderStateApply && additionalState != null) {
            // Try to guess values of "apply" render state based on defaults
            // if value != default then set apply to true
            additionalState.applyPolyOffset = additionalState.offsetEnabled;
            additionalState.applyAlphaFallOff = additionalState.alphaTest;
            additionalState.applyAlphaTest = additionalState.alphaTest;
            additionalState.applyBlendMode = additionalState.blendMode != BlendMode.Off;
            additionalState.applyColorWrite = !additionalState.colorWrite;
            additionalState.applyCullMode = additionalState.cullMode != FaceCullMode.Back;
            additionalState.applyDepthTest = !additionalState.depthTest;
            additionalState.applyDepthWrite = !additionalState.depthWrite;
            additionalState.applyPointSprite = additionalState.pointSprite;
            additionalState.applyStencilTest = additionalState.stencilTest;
            additionalState.applyWireFrame = additionalState.wireframe;
        }
        if (enableVcolor) {
            setBoolean("VertexColor", true);
        }
        if (separateTexCoord) {
            setBoolean("SeparateTexCoord", true);
        }
    }
}


text:
// ==========================================================================
//                                mini_bowtie
// ==========================================================================
// Copyright (c) 2006-2012, Knut Reinert, FU Berlin
// All rights reserved.
//

#include <iostream>
#include <seqan/basic.h>
#include <seqan/sequence.h>
#include <seqan/file.h>
#include <seqan/index.h>
#include <seqan/store.h>

using namespace seqan;

void search() {};

int main(int argc, char *argv[])
{
    // type definitions
    typedef String<Dna5> TString;
    typedef StringSet<TString> TStringSet;
    typedef Index<StringSet<TString>, FMIndex<> > TIndex;
    typedef Iterator<TIndex, TopDown<ParentLinks<> > >::Type TIter;

    // reversing the sequences for backward search
    // backward search
    // declaration and initialization of the fragment store
    // forward search
    // combining the contigs of the reference into one string set

    // reading the command line arguments
    if (argc < 3) {
    std::cerr << "Invalid number of arguments." << std::endl
                  << "USAGE: mini_bowtie GENOME.fasta READS.fasta OUT.sam" << std::endl;
    }
    FragmentStore<> fragStore;

    if (!loadContigs(fragStore, argv[1]))
        return 1;
    if (!loadReads(fragStore, argv[2]))
        return 1;

    StringSet<TString> text;
    /*
        clear(fmIndex);
        for (unsigned i = 0; i < length(fragStore.contigStore); ++i)
        {
            appendValue(text, fragStore.contigStore[i].seq);
        }
    fmIndex = TIndex(text);
    TIndex fmIndex(text);
    TIter it(fmIndex);
    search();
    search();
    clear(it);
    clear(it);
    reverse(text);
    reverse(fragStore.readSeqStore);
    it = TIter(fmIndex);
    return 0;
    return 1;
    */
}