text:
/**
 *
 */
package nz.co.senanque.login;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.security.auth.login.LoginException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import nz.co.senanque.login.users.UserRepository;
import nz.co.senanque.login.users.UserRepositoryImpl;
import nz.co.senanque.permissionmanager.PermissionManager;
import nz.co.senanque.resourceloader.MessageResource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * Spring bean that is fetched from the Spring context explicitly by the filter rather than injected.
 * This doesn't make any difference to the bean itself, of course. It optionally injects an {link nz.co.senanque.login.AuthenticationDelegate}
 * and if there is none it uses itself instead. But the {link nz.co.senanque.login.AuthenticationDelegate} it implements
 * is demo-ware so you should provide your own implementation for production.
 *

 * To test if the current request has been authenticated the HttpSession is examined for an attribute {link nz.co.senanque.login.AuthenticationDelegate.USERNAME}
 * containing a valid string.
 *

 * There are facilities to ensure image files etc bypass the authentication mechanism, as well as a mechanism to serve up some files
 * from the classpath, ie those needed for the login pages.
 *
 * @author Roger Parkinson
 *
 */
@Component("requestValidator")
@MessageResource("messages")
public class RequestValidatorImpl implements AuthenticationDelegate, MessageSourceAware, RequestValidator {

	private static Logger m_logger = LoggerFactory.getLogger(RequestValidatorImpl.class);

	private String m_loginPage = LOGIN_URL;
	private String[] m_ignoreURLs;
	private String[] m_flags = new String[]{"English","French"};
	private String[] m_langs = new String[]{"en","fr"};
    @Value("${nz.co.senanque.login.RequestValidatorImpl.defaultLogin:}")
    private transient String m_defaultLogin;
	@Autowired(required=false) @Qualifier("applicationVersion") private String m_applicationVersion;

    private String[] m_imageExtensions = new String[]{".ico",".gif",".png",".jpg",".jpeg",".css",};

	@Autowired(required=false) private AuthenticationDelegate m_authenticationDelegate;

	private MessageSource m_messageSource;

	@Autowired(required=false) private UserRepository m_users;

    @Value("${nz.co.senanque.login.mobilePathPrefix:mobile}")
	private String m_mobilePathPrefix;

	@PostConstruct
	public void init() {
		if (m_ignoreURLs == null) {
			m_ignoreURLs = new String[]{LOGIN_URL};
		}
		if (m_authenticationDelegate == null) {
			m_authenticationDelegate = this;
		}
	}

	/* (non-Javadoc)
	 * @see nz.co.senanque.login.RequestValidator#isURLIgnored(javax.servlet.http.HttpServletRequest)
	 */
	public boolean isURLIgnored(HttpServletRequest req) {
		String url = req.getRequestURI();
		HttpSession session = req.getSession(true);
		Object o = session.getAttribute(PermissionManager.USERNAME);
		m_logger.debug("checking url {} current user {} session {}",url,o,session.getId());
		if (o != null) {
			m_logger.debug("true");
			return true; // ignore URLs when we are already authenticated
		}
		if (StringUtils.hasText(m_defaultLogin)) {
			fakeLogin(req);
			return true;
		}
		for (String ext: m_imageExtensions) {
			if (url.endsWith(ext)) {
				return false;
			}
		}
		String context = req.getContextPath();
		for (String ignoreURL: m_ignoreURLs) {
			if (url.startsWith(context+ignoreURL)) {
				return true;
			}
		}
		return false;
	}

	private void fakeLogin(HttpServletRequest req) {
		String[] login = StringUtils.split(m_defaultLogin, "/");
		Set<String> permissions;
		try {
			permissions = m_authenticationDelegate.authenticate(req.getServletContext(),login[0],login[1]);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		HttpSession session = req.getSession(true);
		session.setAttribute(PermissionManager.PERMISSIONS, permissions);
		session.setAttribute(PermissionManager.USERNAME, login[0]);
		session.setAttribute(LOCALE, "en");
		m_logger.debug("Setting user: {} on session {}",login[0],req.getSession().getId());

	}

	/* (non-Javadoc)
	 * @see nz.co.senanque.login.RequestValidator#authenticate(javax.servlet.http.HttpServletRequest)
	 */
	public void authenticate(HttpServletRequest req) throws IOException, LoginException {
		String user = req.getParameter("user");
		String password = req.getParameter("password");
		String locale = req.getParameter("locale");
		if (StringUtils.isEmpty(user) || StringUtils.isEmpty(password)) {
			// assume we just changed the locale
			throw new LocaleChangeException(locale);
		}
		Set<String> permissions = m_authenticationDelegate.authenticate(req.getServletContext(),user,password);
		HttpSession session = req.getSession(true);
		session.setAttribute(PermissionManager.PERMISSIONS, permissions);
		session.setAttribute(PermissionManager.USERNAME, user);
		session.setAttribute(LOCALE, locale);
		m_logger.debug("Setting user: {} on session {}",user,req.getSession().getId());
	}
	/* (non-Javadoc)
	 * @see nz.co.senanque.login.RequestValidator#setErrorAttribute(javax.servlet.http.HttpServletRequest, java.lang.String)
	 */
	public void setErrorAttribute(HttpServletRequest req, String error) {
		req.getSession().setAttribute(ERROR_ATTRIBUTE, error);
		m_logger.debug("Setting error: {} on session {}",error,req.getSession().getId());
	}
	public void setLocale(HttpServletRequest req, String locale) {
		req.getSession().setAttribute(LOCALE, locale);
		m_logger.debug("Setting locale: {} on session {}",locale,req.getSession().getId());
	}

	/* (non-Javadoc)
	 * @see nz.co.senanque.login.RequestValidator#getErrorAttribute(javax.servlet.http.HttpServletRequest)
	 */
	public String getErrorAttribute(HttpServletRequest req) {
		m_logger.debug("Getting error: {} on session {}",
				(String)req.getSession().getAttribute(ERROR_ATTRIBUTE),
				req.getSession().getId());
		return (String)req.getSession().getAttribute(ERROR_ATTRIBUTE);
	}

	public String getLocale(HttpServletRequest req) {
		m_logger.debug("Getting locale: {} on session {}",
				(String)req.getSession().getAttribute(LOCALE),
				req.getSession().getId());
		return (String)req.getSession().getAttribute(LOCALE);
	}

	public String[] getIgnoreURLs() {
		return m_ignoreURLs;
	}

	public void setIgnoreURLs(String[] ignoreURLs) {
		m_ignoreURLs = ignoreURLs;
	}

	public void setLoginPage(String loginPage) {
		m_loginPage = loginPage;
	}

	public String getLoginPage() {
		return m_loginPage;
	}

	/* (non-Javadoc)
	 * @see nz.co.senanque.login.RequestValidator#write(javax.servlet.http.HttpServletRequest, javax.servlet.ServletContext, javax.servlet.http.HttpServletResponse)
	 */
	public boolean write(HttpServletRequest req,ServletContext servletContext,
			HttpServletResponse httpServletResponse) throws IOException {

		String contextPath = servletContext.getContextPath();
		String uri = req.getRequestURI();
		uri = StringUtils.delete(uri, contextPath);
		if (uri.startsWith("/")) {
			uri = uri.substring(1);
		}
		if (uri.endsWith("css")) {
			String css = getLoginCSS(uri, servletContext);
			httpServletResponse.setContentType("text/css; charset=UTF-8");
			httpServletResponse.getOutputStream().print(css);
			return true;
		}
		try {
			for (String ext: m_imageExtensions) {
				if (uri.endsWith(ext)) {
					httpServletResponse.setContentType("image/*");
					InputStream is = getStream(uri, servletContext);
					OutputStream out = httpServletResponse.getOutputStream();
					pipe(is,out);
					return true;
				}
			}

		} catch (Exception e) {
			m_logger.warn("{}",e.toString());
			return false;
		}
		if (m_logger.isDebugEnabled()) {
			m_logger.debug("ContentType: {}",httpServletResponse.getContentType());
			m_logger.debug("status: {}",httpServletResponse.getStatus());
			Enumeration<String> nameEnum = req.getHeaderNames();
			while (nameEnum.hasMoreElements()) {
				String name = nameEnum.nextElement();
				m_logger.debug("header name: {} value: {}",name,req.getHeader(name));
			}
			nameEnum = req.getAttributeNames();
			while (nameEnum.hasMoreElements()) {
				String name = nameEnum.nextElement();
				m_logger.debug("Attribute name: {} value: {}",name,req.getAttribute(name));
			}
			nameEnum = req.getParameterNames();
			while (nameEnum.hasMoreElements()) {
				String name = nameEnum.nextElement();
				m_logger.debug("Parameter name: {} value: {}",name,req.getParameter(name));
			}
		}
		m_logger.debug("Context path: {} uri: {} content-type: {}",contextPath,uri, req.getContentType());
		String login = getLoginHTML(getErrorAttribute(req),getLocale(req), servletContext);
		httpServletResponse.setContentType("text/html; charset=UTF-8");
		httpServletResponse.getOutputStream().print(login);
		return true;
	}

	private void pipe(InputStream in, OutputStream out) throws IOException {
		byte[] buffer = new byte[1024];
		int len = in.read(buffer);
		while (len != -1) {
		    out.write(buffer, 0, len);
		    len = in.read(buffer);
		}
	}

	protected String getLoginHTML(String error, String locale, ServletContext servletContext) throws IOException {

		m_logger.debug("Current locale {}",locale);
		Locale useLocale = Locale.getDefault();
		if (locale != null) {
			Locale.setDefault(new Locale(locale));
			useLocale = new Locale(locale);
		}
		String flags = getLocales(useLocale);
		m_logger.debug("Current locale {}",useLocale);
		String s = getFile("login.html",servletContext).replace("~FLAGS",flags);
		final MessageSourceAccessor messageSourceAccessor = new MessageSourceAccessor(m_messageSource);
		String t = messageSourceAccessor.getMessage("login.title",useLocale);
		m_logger.debug("login.title={}",t);
		t = messageSourceAccessor.getMessage("login.name",useLocale);
		m_logger.debug("login.name={}",t);
		String contextPath = servletContext.getContextPath();
		String c = s.replace("~CONTEXTPATH", contextPath);
		c = c.replace("~TITLE", messageSourceAccessor.getMessage("login.title","Welcome to Madura",useLocale));
		c = c.replace("~NAME", messageSourceAccessor.getMessage("login.name","User",useLocale));
		c = c.replace("~PASSWORD", messageSourceAccessor.getMessage("login.password","Password",useLocale));
		c = c.replace("~LOGIN", messageSourceAccessor.getMessage("login.login","Login",useLocale));
		c = c.replace("~HELP", messageSourceAccessor.getMessage("login.help","Help",useLocale));
		c = c.replace("~ERROR", (error==null?"":error));
		c = c.replace("~LOCALE", (locale==null?"":locale.toString()));
		c = c.replace("~VERSION", (m_applicationVersion==null)?"":m_applicationVersion);
		m_logger.debug("\n{}",c);
		return c;
	}

	private String getLocales(Locale currentLocale) {
		String currentFlag ="";
		for (int i=0;i<m_langs.length;i++) {
			if (currentLocale.getLanguage().equals(new Locale(m_langs[i]).getLanguage())) {
				currentFlag = m_flags[i];
				}

		}

		StringBuilder ret = new StringBuilder("<select name=\"locale\" class=\"icon-menu\" onchange=\"this.form.submit()\" ");
		ret.append("style=\"background-image:url(~CONTEXTPATH/flags/~CURRENTFLAG.png);\">".replace("~CURRENTFLAG", currentFlag));
		for (int i=0;i<m_langs.length;i++) {
			if (currentLocale.getLanguage().equals(new Locale(m_langs[i]).getLanguage())) {
				ret.append("<option value=\"~LANG\" selected style=\"background-image:url(~CONTEXTPATH/flags/~FLAG.png)\">~FLAG</option>"
						.replace("~FLAG", m_flags[i]).replace("~LANG", m_langs[i]));
			} else {
				ret.append("<option value=\"~LANG\" style=\"background-image:url(~CONTEXTPATH/flags/~FLAG.png)\">~FLAG</option>"
						.replace("~FLAG", m_flags[i]).replace("~LANG", m_langs[i]));
			}
		}
		ret.append("</select>");
		return ret.toString();
	}

	protected String getLoginCSS(String fileName, ServletContext servletContext) throws IOException {
		String s = getFile(fileName,servletContext);
		String contextPath = servletContext.getContextPath();
		return s.replace("~CONTEXTPATH", contextPath);
	}

	private String getFile(String fileName,ServletContext servletContext) throws IOException {
		StringBuilder sb = new StringBuilder();
		InputStream is = getStream(fileName,servletContext);
		while (true) {
			byte[] bytes = new byte[1000];
			int i = 0;
			try {
				i = is.read(bytes);
			} catch (IOException e) {
				throw new IOException("Failed to open "+fileName,e);
			}
			if (i == -1) {
				break;
			}
			sb.append(new String(bytes, 0, i));
		}
		return sb.toString();
	}

	private InputStream getStream(String fileName,ServletContext servletContext) throws IOException {
		InputStream is = servletContext.getResourceAsStream("/WEB-INF/"+fileName);
		if (is == null) {
			is = this.getClass().getResourceAsStream(fileName);
		}
		if (is == null) {
			throw new IOException("failed to find "+fileName);
		}
		return is;
	}

	/* (non-Javadoc)
	 * @see nz.co.senanque.login.RequestValidator#authenticate(javax.servlet.ServletContext, java.lang.String, java.lang.String)
	 */
	public Set<String> authenticate(ServletContext servletContext, String user, String password) throws IOException, LoginException {
		if (m_users == null) {
			m_users = new UserRepositoryImpl(servletContext);
		}
		return m_users.authenticate(servletContext, user, password);
	}

	public void setMessageSource(MessageSource messageSource) {
		m_messageSource = messageSource;
	}

	public UserRepository getUsers() {
		return m_users;
	}

	public void setUsers(UserRepository users) {
		m_users = users;
	}

	public String getDefaultLogin() {
		return m_defaultLogin;
	}

	public void setDefaultLogin(String defaultLogin) {
		m_defaultLogin = defaultLogin;
	}

	@Override
	public String getMobilePathPrefix() {
		return m_mobilePathPrefix;
	}

	public void setMobilePathPrefix(String mobilePathPrefix) {
		m_mobilePathPrefix = mobilePathPrefix;
	}

}


text:
package persistance.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;
import model.Company;
import model.GenericBuilder;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@Repository
public class DaoCompany implements IDaoCompany {
  private final JdbcTemplate jdbcTemplate;

  //STOP_CHECKSTYLE
  @Autowired
  public DaoCompany(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
  }
  //START_CHECKSTYLE

  /**
     * create company in db.
     * @param c company obj
     * @return generated id
     */
    public Long create(Company c) {
      long generatedKey = 0;
      try {
        SimpleJdbcInsert inserter =
            new SimpleJdbcInsert(jdbcTemplate)
                .withTableName("company")
                .usingGeneratedKeyColumns("id");
        SqlParameterSource parameters = new MapSqlParameterSource()
            .addValue("name", c.getName());
        Number newId = inserter.executeAndReturnKey(parameters);
        generatedKey = newId.longValue();
        c.setId(generatedKey);
        LOGGER.info(" Company created, generated ID : " + generatedKey);
      } catch (Exception e) {
        LOGGER.error("Error creating company " + e.getMessage() + e.getStackTrace());
        throw e;
      }
      return generatedKey;
    }

    /**
     * uate company in db.
     * @param c company obj
     */
    public void update(Company c) {
      int affectedRows = 0;
      try {
        Object[] params = {c.getName(), c.getId()};
        String sql = "UPDATE company SET " +
            "name = ?" +
            " WHERE company.id = ?";

        affectedRows = jdbcTemplate.update(sql, params);
        LOGGER.info(affectedRows + " rows updated");
      } catch (Exception e) {
        LOGGER.error("Error updating company of ID " + c.getId() + e.getMessage() + e.getStackTrace());
        throw e;
      }
      //return affectedRows;
    }

    /**
     * retrieve all companies.
     * @param min offset
     * @param max nb to return
     * @return companies list
     */
    public ArrayList<Company> selectAll(Long min, Long max) {
      ArrayList<Company> resultList = new ArrayList<>();
      try {
        String sql = "SELECT * FROM company " +
            "LIMIT ?, ?";
        resultList = (ArrayList<Company>) this.jdbcTemplate.query(
            sql, new Object[] {min, max}, new CompanyMapper());
      } catch (Exception e) {
        LOGGER.error("Error getting companies" + e.getMessage() + e.getStackTrace());
        throw e;
      }

      return resultList;
    }

    /**
     * retrieve all companies.
     * @return companies list
     */
    public ArrayList<Company> selectAll() {
      ArrayList<Company> resultList = new ArrayList<>();
      try {
        String sql = "SELECT * FROM company ";
        resultList = (ArrayList<Company>) this.jdbcTemplate.query(
            sql, new Object[] {}, new CompanyMapper());
      } catch (Exception e) {
        LOGGER.error("Error getting companies" + e.getMessage() + e.getStackTrace());
        throw e;
      }

      return resultList;
    }

    /**
     * retrieve company by id.
     * @param id id
     * @return company obj
     */
    public Company getById(Long id) {
      Company c = new Company();
      try {
        String sql = "SELECT * FROM company WHERE company.id = ?";

        c = (Company) this.jdbcTemplate.queryForObject(
            sql, new Object[] {id }, new CompanyMapper());
      } catch (Exception e) {
        LOGGER.error("Error retrieving company of ID " + id + e.getMessage() + e.getStackTrace());
        throw e;
      }

      return c;
    }

    /**
     * delete from db.
     * @param id id
     * @return deleted rows numbers
     */
    public int delete(Long id) {
      int affectedRows = 0;
      try {
        String sql = "DELETE FROM company WHERE company.id = ?";
        Object[] params = {id};
        affectedRows = jdbcTemplate.update(sql, params);
        LOGGER.info(affectedRows + " rows updated");
      } catch (Exception e) {
        LOGGER.error("Error deleting company of ID " + id + e.getMessage() + e.getStackTrace());
        throw e;
      }
      return affectedRows;
    }
}

class CompanyMapper implements RowMapper<Company> {
  /**
   * JDBCTemplate row to computer object mapper.
   * @param rs rs
   * @param rowNum rownum
   * @return computer
   * @throws SQLException ex
   */
  public Company mapRow(ResultSet rs, int rowNum) throws SQLException {
    Company c = GenericBuilder.of(Company::new)
        .with(Company::setId, rs.getLong("company.id"))
        .with(Company::setName, rs.getString("company.name"))
        .build();
    return c;
  }
}

redpajama_set_name: RedPajamaGithub


text:
#include "RenderFactory.h"
#include "Camera.h"
#include "Mesh.h"

#include <fstream>
#include <string>

#include <GG/Core/Vector.h>
#include <GG/Core/Rect.h>
#include <GG/Core/Log.h>
#include <GG/Core/MathDebug.h>
#include <GG/Graphics/IVertexBuffer.h>
#include <GG/Resources/ResourceManager.h>

namespace GG
{

	RenderFactory::RenderFactory() : _tempShader(nullptr)
	{
		loadTempAssets();
	}

	RenderFactory::~RenderFactory()
	{
	}

	void RenderFactory::loadTempAssets()
	{
		//ResourceManager * rm = ResourceManager::GetInstance();
		//_tempTexture	= rm->getResource<Texture2D>(STRING_ID("abrick_albedo"));
		//_roughnessTex	= rm->getResource<Texture2D>(STRING_ID("brick_spec"));
		//_normalTex		= rm->getResource<Texture2D>(STRING_ID("brick_norm"));

		//_tempShader		= rm->getResource<Shader>(STRING_ID("cookTorrence"));
	}

	void RenderFactory::addCommand(Material * mat, Model * geo, const Matrix4 & worldMatrix )
	{
		_renderCommand3DList.push_back(
			RenderCommand3D { mat, geo, worldMatrix }
		);
	}

	void RenderFactory::clearAllCommands()
	{
		_renderCommand3DList.clear();
	}

	void RenderFactory::renderAll( const Camera * camera )
	{
		ResourceManager * rm = ResourceManager::GetInstance();
		loadTempAssets();

		if( camera == nullptr )
		{
			TRACE_ERROR( "Camera Node does not contain Camera!" );
			return;
		}

		_setViewport( camera->getViewport() );
		_clearRenderBuffer( camera->getClearColor(), camera->getClearMode() );

		RenderState::GetInstance()->setViewMatrix(camera->getViewMatrix());
		RenderState::GetInstance()->setProjectionMatrix(camera->getProjectionMatrix());

		_render3DList(camera);
	}

// -------------------------------------------------------------------------------

	void RenderFactory::_render3DList(const Camera * camera)
	{
		RenderState * rs = RenderState::GetInstance();
		Material *	currentMat	= nullptr;

		Matrix4 viewProjection = rs->getProjectionMatrix() * rs->getViewMatrix();

		auto it = _renderCommand3DList.begin();
		for(; it != _renderCommand3DList.end(); ++it)
		{
			const RenderCommand3D * command = &( *it );
			if( command == nullptr )
			{
				TRACE_ERROR( "Render Command is null!" );
				continue;
			}

			rs->setModelMatrix(command->modelMatrix);

			Material * mat = command->material;
			if(mat != nullptr && mat != currentMat)
			{
				_setMaterial(mat);
				currentMat = mat;
			}

			_tempShader->setParameter("inMVP", viewProjection * command->modelMatrix);
			_tempShader->setParameter("inViewMat", rs->getViewMatrix());
			_tempShader->setParameter("inModelMat", command->modelMatrix);
			_tempShader->setParameter("inEyePos", camera->getEntity()->getSceneNode()->getWorldPosition());

			if( command->geometry != nullptr )
			{
				command->geometry->bind();
				command->geometry->render(DrawMode::TRIANGLE_LIST);
			}
		}
	}

	void RenderFactory::_setViewport( const Vector4 & viewport ) const
	{
		RenderState::GetInstance()->setViewport(viewport);
	}

	void RenderFactory:: _clearRenderBuffer(
		const Vector4 & clearColor,
		uint clearMode ) const
	{
		if( clearMode != RenderState::ClearMode::CM_NONE )
		{
			RenderState::GetInstance()->setClearColor(clearColor);
			RenderState::GetInstance()->clearRenderBuffer(clearMode);
		}
	}

	void RenderFactory::_opaqueSort( const Vector3 & cameraEye )
	{
		auto opaqueSort =
			[ &cameraEye ]( RenderCommand3D a, RenderCommand3D b )
		{
			if( a.material == nullptr || b.material == nullptr )
				return false;

			/*int16 aAlphaMode = ( int16 )a.material->GetAlphaMode();
			int16 bAlphaMode = ( int16 )b.material->GetAlphaMode();

			bool alphaCompare		=	aAlphaMode < bAlphaMode;
			bool userFlagCompare	=	aAlphaMode == bAlphaMode  &&
										a.material->GetUserFlags() <
										b.material->GetUserFlags();

			return	alphaCompare || userFlagCompare;*/
			return true;
		};

		std::sort(
			_renderCommand3DList.begin(),
			_renderCommand3DList.end(),
			opaqueSort
		);
	}

	void RenderFactory::_transparentSort( const Vector3 & cameraEye )
	{
		auto transparentSort =
			[ &cameraEye ]( RenderCommand3D a, RenderCommand3D b )
		{
			if( a.material == nullptr || b.material == nullptr )
				return false;

		/*	int16 aAlphaMode = ( int16 )a.material->GetAlphaMode();
			int16 bAlphaMode = ( int16 )b.material->GetAlphaMode();

			bool alphaCompare		=	aAlphaMode < bAlphaMode;
			bool userFlagCompare	=	aAlphaMode == bAlphaMode  &&
				a.material->GetUserFlags() <
				b.material->GetUserFlags();

			return	alphaCompare || userFlagCompare;*/
			return true;
		};

		std::sort(
			_renderCommand3DList.begin(),
			_renderCommand3DList.end(),
			transparentSort
		);
	}

	void RenderFactory::_setMaterial(Material * material)
	{
		if(material == nullptr)
		{
			TRACE_ERROR("Material is null!");
			return;
		}

		RenderState * rs = RenderState::GetInstance();
		rs->setBlendmode(material->renderStateBlock.blendMode);
		rs->setCullMode(material->renderStateBlock.cullMode);
		rs->setDepthTesting(material->renderStateBlock.isDepthTesting);
		rs->setWindingMode(material->renderStateBlock.windingMode);
		rs->setDepthRange(
			material->renderStateBlock.depthRange.x,
			material->renderStateBlock.depthRange.y
		);

		ResourceManager * rm = ResourceManager::GetInstance();
		_tempShader = rm->getResource<Shader>(material->renderStateBlock.shaderId);
		_tempShader->bind();

		static float t = 0.0f;
		t += 0.016f;
		//_tempShader->setParameter("time", t);

		_tempShader->setParameter("lightList[0].position", Vector3(1.0f, 3.0f, 5.0f));
		_tempShader->setParameter("lightList[0].color", Vector4(.8, 0.749, 0.681, 2.1f));
		_tempShader->setParameter("lightList[0].radius", 20.0f);
		_tempShader->setParameter("lightList[0].type", 1);

		_tempShader->setParameter("lightList[1].position", Vector3((sinf(t) * 10.0f) - 5.0f, 3.0f, -8.0f));
		_tempShader->setParameter("lightList[1].color", Vector4(.3, 0.849, 0.481, 1.5f));
		_tempShader->setParameter("lightList[1].radius", 5.0f);
		_tempShader->setParameter("lightList[1].type", 1);

		_tempShader->setParameter("lightList[2].position", Vector3(10.0f, 3.0f, (cosf(t* 3.0f) * 10.0f) - 5.0f));
		_tempShader->setParameter("lightList[2].color", Vector4(.8f, 0.849, 0.21, 0.8f));
		_tempShader->setParameter("lightList[2].radius", 7.0f);
		_tempShader->setParameter("lightList[2].type", 1);

		material->bindToShader(_tempShader);
	}
}


text:
using System;
using System.Collections.Generic;

namespace Beerendonk.Transit.Impl
{
    /// <summary>
    /// Represents a link.
    /// </summary>
    internal class Link : ILink
    {
        private const string LINK = "link";
        private const string IMAGE = "image";

        private const string HREF = "href";
        private const string REL = "rel";
        private const string PROMPT = "prompt";
        private const string NAME = "name";
        private const string RENDER = "render";

        private IDictionary<string, object> dictionary;

        /// <summary>
        /// Initializes a new instance of the <see cref="Link"/> class.
        /// </summary>
        /// <param name="href">The href.</param>
        /// <param name="rel">The rel.</param>
        /// <param name="name">The name.</param>
        /// <param name="render">The render.</param>
        /// <param name="prompt">The prompt.</param>
        /// <exception cref="System.ArgumentNullException">
        /// href
        /// or
        /// rel
        /// </exception>
        /// <exception cref="System.ArgumentException">Value of render must be "link" or "image".</exception>
        public Link(Uri href, string rel, string name, string render, string prompt)
        {
            var dictionary = new Dictionary<string, object>();

            if (href == null)
            {
                throw new ArgumentNullException("href");
            }
            dictionary.Add(HREF, href);

            if (rel == null)
            {
                throw new ArgumentNullException("rel");
            }
            dictionary.Add(REL, rel);

            if (name != null)
            {
                dictionary.Add(NAME, name);
            }

            if (prompt != null)
            {
                dictionary.Add(PROMPT, prompt);
            }

            if (render != null)
            {
                if ((render == LINK) || (render == IMAGE))
                {
                    dictionary.Add(RENDER, render);
                }
                else
                {
                    throw new ArgumentException("Value of render must be \"link\" or \"image\".");
                }
            }

            this.dictionary = dictionary;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Link"/> class.
        /// </summary>
        /// <param name="dictionary">The dictionary.</param>
        public Link(IDictionary<string, object> dictionary)
        {
            this.dictionary = dictionary;
        }

        /// <summary>
        /// Converts the link to a dictionary.
        /// </summary>
        /// <returns>The dictionary.</returns>
        public IDictionary<string, object> ToDictionary()
        {
            return dictionary;
        }

        /// <summary>
        /// Gets the href.
        /// </summary>
        /// <value>
        /// The href.
        /// </value>
        public Uri Href
        {
            get { return (Uri)dictionary[HREF]; }
        }

        /// <summary>
        /// Gets the rel.
        /// </summary>
        /// <value>
        /// The rel.
        /// </value>
        public string Rel
        {
            get { return (string)dictionary[REL]; }
        }

        /// <summary>
        /// Gets the name.
        /// </summary>
        /// <value>
        /// The name.
        /// </value>
        public string Name
        {
            get { return (string)dictionary[NAME]; }
        }

        /// <summary>
        /// Gets the prompt.
        /// </summary>
        /// <value>
        /// The prompt.
        /// </value>
        public string Prompt
        {
            get { return (string)dictionary[PROMPT]; }
        }

        /// <summary>
        /// Gets the render semantic
        /// </summary>
        /// <value>
        /// The render.
        /// </value>
        public string Render
        {
            get { return (string)dictionary[RENDER]; }
        }
    }
}


text:
import {
  each,
  difference,
} from 'lodash';
import {
  actions as castActions,
  selectors as castSelectors,
} from 'morpheus/casts';
import {
  selectors as sceneSelectors,
} from 'morpheus/scene';
import {
  selectors as inputSelectors,
} from 'morpheus/input';
import {
  actions as gameActions,
  selectors as gameSelectors,
} from 'morpheus/game';
import {
  isActive,
  selectors as gamestateSelectors,
} from 'morpheus/gamestate';
import store from 'store';
import loggerFactory from 'utils/logger';

const logger = loggerFactory('flatspot');

const ORIGINAL_HEIGHT = 400;
const ORIGINAL_WIDTH = 640;
const ORIGINAL_ASPECT_RATIO = ORIGINAL_WIDTH / ORIGINAL_HEIGHT;

export default function ({ dispatch, scene }) {
  const clickStartPos = { left: 0, top: 0 };
  const castSelectorForScene = castSelectors.forScene(scene);
  const castActionsForScene = castActions.forScene(scene);

  let wasActiveHotspots = [];
  const possibleValidClick = false;
  let wasMouseDowned = false;
  let wasMouseMoved = false;
  let wasMouseUpped = false;
  let mouseDown = false;
  let width;
  let height;
  let clipWidth;
  let clipHeight;
  let widthScaler;
  let heightScaler;
  const clip = {
    horizontal: 100,
    vertical: 100,
  };

  function handleHotspotDispatches({
    type,
    top,
    left,
    hotspots,
  }) {
    let cursor = 0;
    hotspots.every((hotspot) => {
      const handled = dispatch(castActionsForScene.special.handleMouseEvent({
        type,
        top,
        left,
        hotspot,
      }));
      if (handled) {
        cursor = handled;
      }
      return handled;
    });
    return cursor;
  }

  function updateState({ clientX, clientY }) {
    const state = store.getState();
    const inputEnabled = inputSelectors.enabled(state);
    if (!inputEnabled) {
      return;
    }
    const location = gameSelectors.location(state);
    const hotspots = castSelectorForScene.special.hotspotData(state);
    const isCurrent = sceneSelectors.currentSceneData(state) === scene;
    const isExiting = castSelectorForScene.isExiting(state);
    const acceptsMouseEvents = isCurrent && !isExiting;
    if (!acceptsMouseEvents) {
      return;
    }
    const nowActiveHotspots = [];
    const left = clientX - location.x;
    const top = clientY - location.y;
    // Update cursor location
    dispatch(gameActions.setCursorLocation({ top, left }));

    const newWidth = gameSelectors.width(store.getState());
    const newHeight = gameSelectors.height(store.getState());

    if (width !== newWidth || height !== newHeight) {
      width = newWidth;
      height = newHeight;
      const onScreenAspectRatio = newWidth / newHeight;
      if (onScreenAspectRatio > ORIGINAL_ASPECT_RATIO) {
        const adjustedHeight = width / ORIGINAL_ASPECT_RATIO;
        clipHeight = adjustedHeight - height;
        clipWidth = 0;
        widthScaler = width / ORIGINAL_WIDTH;
        heightScaler = adjustedHeight / ORIGINAL_HEIGHT;
      } else {
        const adjustedWidth = height * ORIGINAL_ASPECT_RATIO;
        clipWidth = adjustedWidth - width;
        clipHeight = 0;
        widthScaler = adjustedWidth / ORIGINAL_WIDTH;
        heightScaler = height / ORIGINAL_HEIGHT;
      }
    }

    const adjustedClickPos = {
      top: (top + (clipHeight / 2)) / heightScaler,
      left: (left + (clipWidth / 2)) / widthScaler,
    };

    each(hotspots, (hotspot) => {
      const {
        rectTop,
        rectBottom,
        rectLeft,
        rectRight,
      } = hotspot;
      if (adjustedClickPos.top > rectTop
        && adjustedClickPos.top < rectBottom
        && adjustedClickPos.left > rectLeft
        && adjustedClickPos.left < rectRight) {
        nowActiveHotspots.push(hotspot);
      }
    });
    // Update our state
    // logger.info('Handling mouse event', JSON.stringify({
    //   nowActiveHotspots,
    //   wasMouseUpped,
    //   wasMouseMoved,
    //   wasMouseDowned,
    //   adjustedClickPos,
    //   originalClickPos: {
    //     top,
    //     left,
    //   },
    // }, null, 2));
    // Events for hotspots we have left
    handleHotspotDispatches({
      type: 'MouseOver',
      top: adjustedClickPos.top,
      left: adjustedClickPos.left,
      hotspots: nowActiveHotspots,
    });

    handleHotspotDispatches({
      type: 'MouseLeave',
      top: adjustedClickPos.top,
      left: adjustedClickPos.left,
      hotspots: difference(wasActiveHotspots, nowActiveHotspots),
    });

    // Events for hotspots we have entered
    handleHotspotDispatches({
      type: 'MouseEnter',
      top: adjustedClickPos.top,
      left: adjustedClickPos.left,
      hotspots: difference(nowActiveHotspots, wasActiveHotspots),
    });

    // User initiated event inside a hotspot so could be valid
    if (!mouseDown && wasMouseDowned && nowActiveHotspots.length) {
      mouseDown = true;
      handleHotspotDispatches({
        type: 'MouseDown',
        top: adjustedClickPos.top,
        left: adjustedClickPos.left,
        hotspots: nowActiveHotspots,
      });
    }

    if (wasMouseMoved) {
      handleHotspotDispatches({
        type: 'MouseMove',
        top: adjustedClickPos.top,
        left: adjustedClickPos.left,
        hotspots: nowActiveHotspots,
      });
    }

    if (wasMouseMoved && mouseDown) {
      handleHotspotDispatches({
        type: 'MouseStillDown',
        top: adjustedClickPos.top,
        left: adjustedClickPos.left,
        hotspots: nowActiveHotspots,
      });
    }

    // User pressed and released mouse button inside a valid hotspot
    // TODO: debounce??
    if (wasMouseUpped && nowActiveHotspots.length) {
      mouseDown = false;
      handleHotspotDispatches({
        type: 'MouseUp',
        top: adjustedClickPos.top,
        left: adjustedClickPos.left,
        hotspots: nowActiveHotspots,
      });
      handleHotspotDispatches({
        type: 'MouseClick',
        top: adjustedClickPos.top,
        left: adjustedClickPos.left,
        hotspots: nowActiveHotspots,
      });
    }

    handleHotspotDispatches({
      type: 'MouseNone',
      top: adjustedClickPos.top,
      left: adjustedClickPos.left,
      hotspots: difference(hotspots, nowActiveHotspots),
    });

    handleHotspotDispatches({
      type: 'Always',
      top: adjustedClickPos.top,
      left: adjustedClickPos.left,
      hotspots: hotspots
        .filter(h => h.castId === 0),
    });

    nowActiveHotspots.every((hotspot) => {
      // Some special cases
      const gamestates = gamestateSelectors.forState(store.getState());
      if (isActive({ cast: hotspot, gamestates })) {
        const {
          type,
          cursorShapeWhenActive,
        } = hotspot;
        if (wasMouseUpped && type >= 5 && type <= 8) {
          dispatch(gameActions.setOpenHandCursor());
          return false;
        } else if (wasMouseDowned || wasMouseMoved) {
          if (type >= 5 && type <= 8) {
            const currentCursor = gameSelectors.morpheusCursor(store.getState());
            if (currentCursor !== 10009) {
              dispatch(gameActions.setOpenHandCursor());
            }
            return false;
          } else if (cursorShapeWhenActive) {
            dispatch(gameActions.setCursor(cursorShapeWhenActive));
            return false;
          }
        }
      }
      return true;
    });
    wasActiveHotspots = nowActiveHotspots;
    wasMouseMoved = false;
    wasMouseUpped = false;
    wasMouseDowned = false;

    dispatch(castActionsForScene.special.update(scene));
  }

  function onMouseDown(mouseEvent) {
    wasMouseDowned = true;
    updateState(mouseEvent);
  }

  function onMouseMove(mouseEvent) {
    wasMouseMoved = true;
    updateState(mouseEvent);
  }

  function onMouseUp(mouseEvent) {
    wasMouseUpped = true;
    updateState(mouseEvent);
  }

  function onTouchStart({ touches }) {
    if (touches.length) {
      wasMouseDowned = true;
      updateState(touches[0]);
    }
  }

  function onTouchMove({ touches }) {
    if (touches.length) {
      wasMouseMoved = true;
      updateState(touches[0]);
    }
  }

  function onTouchEnd({ touches }) {
    if (touches.length) {
      wasMouseUpped = true;
      updateState(touches[0]);
    }
  }

  function onTouchCancel(/* touchEvent */) {
    // TODO....
  }

  return {
    onMouseUp,
    onMouseMove,
    onMouseDown,
    onTouchStart,
    onTouchMove,
    onTouchEnd,
    onTouchCancel,
  };
}


text:
/**
 * @private
 * @class Bancha.scaffold.form.override.Panel
 *
 * This override adds support for defining a scaffold config in a formpanel
 * configuration.
 *
 * @author Roland Schuetz <mail@rolandschuetz.at>
 * @docauthor Roland Schuetz <mail@rolandschuetz.at>
 */
Ext.define('Bancha.scaffold.form.override.Panel', {
    requires: [
        'Ext.form.Panel',
        'Bancha.scaffold.form.Config',
        'Bancha.scaffold.data.Validators',
        'Bancha.scaffold.form.field.override.VTypes',
        'Bancha.scaffold.Util'
    ]
}, function() {

    /**
     * @class Ext.form.Panel
     * **This is only available inside Ext JS.**
     *
     * After requiring *'Bancha.scaffold.form.override.Panel'*, form panels have
     * an additional scaffold configuration.
     *
     * The simplest usage is:
     *
     *     Ext.create("Ext.form.Panel", {
     *         scaffold: 'MyApp.model.User', // the model name
     *     });
     *
     * A more complex usage example:
     *
     *     Ext.create("Ext.form.Panel", {
     *
     *         scaffold: {
     *             // define the model name here
     *             target: 'MyApp.model.User',
     *
     *             // you can tell the form to automatically load a record for edting, by id
     *             loadRecord: 3,
     *
     *             // define which buttons should be displayed
     *             buttons: ['reset','save'],
     *
     *             // advanced configs can be set here:
     *             textfieldDefaults: {
     *                 emptyText: 'Please fill this out'
     *             },
     *             datefieldDefaults: {
     *                 format: 'm/d/Y'
     *             },
     *             onSave: function() {
     *                 Ext.MessageBox.alert("Tada","You've pressed the form save button");
     *             }
     *         },
     *
     *         // and add some styling
     *         height: 350,
     *         width: 650,
     *         frame:true,
     *         title: 'Form Panel',
     *         renderTo: 'formpanel',
     *         bodyStyle:'padding:5px 5px 0',
     *         fieldDefaults: {
     *             msgTarget: 'side',
     *             labelWidth: 75
     *         },
     *         defaults: {
     *             anchor: '100%'
     *         }
     *     });
     *
     * It currently creates fields for:
     *
     *  - string
     *  - integer
     *  - float (precision is read from metadata)
     *  - boolean (checkboxes)
     *  - date
     *
     * It's recognizing following validation rules on the model to add validations
     * to the form fields:
     *
     *  - format
     *  - file
     *  - length
     *  - range
     *  - presence
     *
     * You have three possible interceptors:
     *
     *  - {@link Bancha.scaffold.form.Config#cfg-beforeBuild}         : executed before #buildConfig
     *  - {@link Bancha.scaffold.form.Config#cfg-transformFieldConfig}: executed after a field config is created
     *  - {@link Bancha.scaffold.form.Config#cfg-afterBuild}          : executed after #buildConfig created the config
     *
     *  If you use the scaffold config and don't define an id,
     * it will be created and can not be changed anymore afterwards.
     *
     * @author Roland Schuetz <mail@rolandschuetz.at>
     * @docauthor Roland Schuetz <mail@rolandschuetz.at>
     */
    Ext.apply(Ext.form.Panel, {
        /**
         * @cfg {Bancha.scaffold.form.Config|Ext.data.Model|Object|String|false} scaffold
         *
         * The simplest configuration is to set a model class or model name as scaffold
         * config. All fields, validation rules and other configurations are taken from
         * this model.
         *
         * For more complex configurations you can set a {@link Bancha.scaffold.form.Config}
         * config or class. This config must have the model name defined as target
         * config. Any property from {@link Bancha.scaffold.form.Config} can be defined here.
         */
        /**
         * @property {Bancha.scaffold.form.Config|False} scaffold
         * If this panel was scaffolded, all initial configs are stored here, otherwise false.
         */
        scaffold: false
    });

    // add scaffolding support
    Ext.override(Ext.form.Panel, {
        /**
         * @private
         */
        initComponent: function () {
            var isModel, config;

            if(this.scaffold) {
                // check if the scaffold config is a model class or string
                isModel = Ext.isString(this.scaffold) || Bancha.scaffold.Util.isModel(this.scaffold);

                // if there's a model or config object, transform to config class
                // normally we would use this.scaffold.isInstance instead of $className, but that was introduced in Ext JS 4.1
                if (isModel || (Ext.isObject(this.scaffold) && !this.scaffold.$className)) {
                    this.scaffold.triggeredFrom = 'Ext.form.Panel';
                    this.scaffold = Ext.create('Bancha.scaffold.form.Config', this.scaffold);
                }

                // apply scaffolding
                config = Ext.form.Panel.buildConfig(this.scaffold, this.initialConfig);
                Ext.apply(this, config);
                Ext.apply(this.initialConfig, config);
            }

            // continue with standard behaviour
            this.callOverridden();
        },
        statics: {

            /**
             * @private
             * @property
             * Maps model field configs with field types and additional configs
             */
            fieldToFieldConfigs: {
                'auto': {
                    xtype: 'textfield'
                },
                'string': {
                    xtype: 'textfield'
                },
                'int': {
                    xtype: 'numberfield',
                    allowDecimals: false
                },
                'float': {
                    xtype: 'numberfield'
                },
                'boolean': {
                    xtype: 'checkboxfield'
                },
                'bool': {
                    xtype: 'checkboxfield'
                },
                // a synonym
                'date': {
                    xtype: 'datefield'
                }
                // TODO OPTIMIZE Add combobox support
            },

            /**
             * @private
             * @property {Function} internalTransformFieldConfig
             * This function just hides id columns and makes it uneditable.
             * @param {Object} fieldConfig the field config to transform
             * @param {String} modelType A standard model field type like 'string'
             * (also supports 'file' for compability with http://bancha.io)
             * @return {Object} Returns an Ext.form.field.* configuration object
             */
            internalTransformFieldConfig: function (fieldConfig, modelType) {
                if (fieldConfig.name === 'id') {
                    fieldConfig.xtype = 'hiddenfield';
                }

                return fieldConfig;
            },

            /**
             * @private
             *
             * Parses ExtJS 4 validation rules.
             *
             * Analysis the validation rules for a field and adds validation rules to the field config.
             * For what is supported see {@link Bancha.scaffold.form.Config}
             *
             * @param {Object} field A Ext.form.field.* config
             * @param {Array} validations An array of Ext.data.validations of the model
             * @param {Bancha.scaffold.form.Config} config A Bancha.scaffold.form.Config config
             * @return {Object} Returns a Ext.form.field.* config
             */
            addValidationRuleConfigs: (function () {
                /*
                 * closure these in so they are only created once.
                 * we first create the regex and then get the string of them to not have to delete the backslashes
                 * have a bit cleaner code. It doesn't matter for performance cause it's done only once
                 */
                var alpha = /^[a-zA-Z_]+$/.toString(),
                    alphanum = /^[a-zA-Z0-9_]+$/.toString(),
                    email = /^(\w+)([\-+.][\w]+)*@(\w[\-\w]*\.){1,5}([A-Za-z]){2,6}$/.toString(),
                    url = /(((^https?)|(^ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i.toString();

                return function (field, validations, config) {
                    var name = field.name, // it's used so often, make a shortcut
                        msgAddition;

                    Ext.Array.forEach(validations, function (rule) {
                        if (rule.field && rule.field !== name) {
                            // If there's a name property it means that's validation syntax,
                            // otherwise already filtered validators.
                            // For validation rules these are all fields, not just the mathing ones, so filter
                            return;
                        }

                        switch (rule.type) {
                        case 'presence':
                            field.allowBlank = false;
                            break;
                        case 'length':
                            //<debug>
                            // length validation works only only on textfields
                            if (field.xtype !== 'textfield') {
                                msgAddition = (field.xtype === 'numberfield') ?
                                                'Use the range rule to force minimal and maximal values.' : '';
                                Ext.Error.raise({
                                    plugin: 'Bancha Scaffold',
                                    msg: [
                                        'Bancha Scaffold: The model has a validation rule ',
                                        'length for the field ' + name + ', but this field ',
                                        'is of type ' + field.xtype + ', so the rule makes ',
                                        'no sense. ' + msgAddition
                                    ].join('')
                                });
                            }
                            //</debug>
                            if (field.xtype === 'textfield') {
                                // Ext JS 4
                                if (Ext.isDefined(rule.min)) {
                                    field.minLength = rule.min;
                                }
                                if (Ext.isDefined(rule.max)) {
                                    field.maxLength = rule.max;
                                }
                                // Ext JS 5
                                if (rule.getMin && Ext.isDefined(rule.getMin())) {
                                    field.minLength = rule.getMin();
                                }
                                if (rule.getMax && Ext.isDefined(rule.getMax())) {
                                    field.maxLength = rule.getMax();
                                }
                            }
                            break;
                        case 'format':
                            //<debug>
                            // length validation works only only on textfields
                            if (field.xtype !== 'textfield') {
                                Ext.Error.raise({
                                    plugin: 'Bancha Scaffold',
                                    msg: [
                                        'Bancha Scaffold: The model has a validation rule ',
                                        'format for the field ' + name + ', but this field ',
                                        'is of type ' + field.xtype + ', so the rule makes ',
                                        'no sense.'
                                    ].join('')
                                });
                            }
                            //</debug>
                            switch ((rule.matcher || rule.getMatcher()).toString()) {
                            case alpha:
                                field.vtype = 'alpha';
                                break;
                            case alphanum:
                                field.vtype = 'alphanum';
                                break;
                            case email:
                                field.vtype = 'email';
                                break;
                            case url:
                                field.vtype = 'url';
                                break;
                            default:
                                //<debug>
                                if (Ext.global.console && Ext.isFunction(Ext.global.console.warn)) {
                                    Ext.global.console.warn([
                                        'Bancha Scaffold: Currently Bancha.scaffold.form.Config ',
                                        'only recognizes the model Ext.data.validations format ',
                                        'rules with the matcher regex of Ext.form.field.VType ',
                                        'alpha, alphanum, email and url. This rule with matcher ',
                                        rule.matcher.toString() + ' will just be ignored.'
                                    ].join(''));
                                }
                                //</debug>
                                break;
                            }
                            break;
                        case 'range':
                            // range validation works only only on numberfields
                            //<debug>
                            if (field.xtype !== 'numberfield') {
                                Ext.Error.raise({
                                    plugin: 'Bancha Scaffold',
                                    msg: [
                                        'Bancha Scaffold: The model has a validation rule ',
                                        'range for the field ' + name + ', but this ',
                                        'field is of type ' + field.xtype + ', so the rule ',
                                        'makes no sense. A numberfield is expected.'
                                    ].join('')
                                });
                            }
                            //</debug>
                            if (field.xtype === 'numberfield') {
                                // Ext JS 4
                                if (Ext.isDefined(rule.min)) {
                                    field.minValue = rule.min;
                                }
                                if (Ext.isDefined(rule.max)) {
                                    field.maxValue = rule.max;
                                }
                                if (Ext.isDefined(rule.precision)) {
                                    field.decimalPrecision = rule.precision;
                                }
                                // Ext JS 5
                                if (rule.getMin && Ext.isDefined(rule.getMin())) {
                                    field.minValue = rule.getMin();
                                }
                                if (rule.getMax && Ext.isDefined(rule.getMax())) {
                                    field.maxValue = rule.getMax();
                                }
                                if (Ext.isDefined(rule._precision) || Ext.isDefined((rule.config || {}).precision)) {
                                    field.decimalPrecision = rule._precision || (rule.config || {}).precision;
                                }
                            }
                            break;
                        case 'file':
                            // make the field a fileuploadfield
                            field.xtype = 'fileuploadfield';
                            Ext.apply(field, config.fileuploadfieldDefaults);

                            // add validation rules
                            var extension = rule.getExtension ? rule.getExtension() : rule.extension;
                            if (Ext.isString(extension)) {
                                extension = [extension];
                            }
                            if (Ext.isArray(extension)) {
                                field.vtype = 'fileExtension';
                                field.validExtensions = extension;
                            }
                            break;
                        default:
                            //<debug>
                            if (Ext.global.console && Ext.isFunction(Ext.global.console.warn)) {
                                Ext.global.console.warn([
                                    'Bancha Scaffold: Could not recognize rule ',
                                    Ext.encode(rule) + ' when trying to create a ',
                                    'form field field.'
                                ].join(''));
                            }
                            //</debug>
                            break;
                        }
                        // TODO OPTIMIZE Also include inclusion and exclusion
                    }); //eo forEach
                    return field;
                }; //eo return fn
            }()),

            /**
             * @private
             *
             * Parses ExtJS 5 validator rules.
             *
             * Analysis the validator rules for a field and adds validation rules to the field config.
             * For what is supported see {@link Bancha.scaffold.form.Config}
             *
             * @param {Object} field A Ext.form.field.* config
             * @param {Array} validators An array of Ext.data.validators.*'s of the model
             * @param {Bancha.scaffold.form.Config} config A Bancha.scaffold.form.Config config
             * @return {Object} Returns a Ext.form.field.* config
             */
            addValidatorRuleConfigs: function (field, validators, config) {
                var fieldValidators = validators[field.name];
                if(!fieldValidators) {
                    return field; // no validator rules found
                }
                if(!Ext.isArray(fieldValidators)) {
                    fieldValidators = [fieldValidators]; // always have an array
                }

                return this.addValidationRuleConfigs(field, fieldValidators, config);
            },

            /**
             * @private
             * Builds a field with all defaults defined here
             * @param {String} type The model field type
             * @param {Object} defaults (optional) Defaults like textfieldDefaults as property of this config.
             * See {@link #buildConfig}'s config property
             * @return {Object} Returns a Ext.form.field.* config
             */
            buildDefaultFieldFromModelType: function (type, defaults) {
                defaults = defaults || {};
                var field = Ext.clone(this.fieldToFieldConfigs[type]),
                    fieldDefaults = Ext.clone(defaults.fieldDefaults || this.fieldDefaults),
                    // make a new object of defaults
                    fieldTypeDefaults = Ext.clone(defaults[field.xtype + 'Defaults'] || this[field.xtype + 'Defaults']);
                return Ext.apply(fieldDefaults, field, fieldTypeDefaults);
            },

            /**
             * @private
             * Creates a Ext.form.Field config from an model field type
             * @param {String} type The model's current field
             * @param {Bancha.scaffold.form.Config} config A config object
             * @param {Array} validations (optional) An array of Ext.data.validations of the model
             * @param {Object} isEditorfield (optional) True to don't add field label (usefull e.g. in an editor grid)
             * @param {Object} nonEditorFieldModelField (optional) Dirty hack to set the fieldname on
             * form panel creations, should be refactored!
             * @return {Object} Returns a field config
             */
            buildFieldConfig: function (modelField, config, validations, isEditorfield) {
                var type = Ext.versions.extjs.major === 5 ? modelField.type : modelField.type.type,
                    model = config.target,
                    field = this.buildDefaultFieldFromModelType(type, config),
                    Util = Bancha.scaffold.Util,
                    defaultAltFormats,
                    associatedModel;

                // infer name
                field.name = modelField.name;
                if (!isEditorfield) {
                    field.fieldLabel = Util.humanize(modelField.name);
                }

                // infer date format into editor (not needed for editor fields)
                if(type==='date' && !isEditorfield && modelField.dateFormat) {
                    if(!field.format) {
                        // keep it simple and use the model date format as display format
                        field.format = modelField.dateFormat;
                    } else {
                        // allow the developer to override the date format

                        // to make sure reading and writing still works as expected
                        // add the model date format to altFormats for reading
                        defaultAltFormats = (((Ext.form.field || {}).Date || {}).prototype || {}).altFormats ||
                                    'm/d/Y|n/j/Y|n/j/y|m/j/y|n/d/y|m/j/Y|n/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d|Y-m-d|n-j|n/j';
                        field.altFormats = (field.altFormats || defaultAltFormats)+'|'+modelField.dateFormat;

                        // and enforce the submit value to match the model date format
                        field.submitFormat = modelField.dateFormat;
                    }
                }

                // add some additional validation rules from model validation rules
                if (Ext.isDefined(validations) && validations.length) {
                    field = this.addValidationRuleConfigs(field, validations, config);
                }
                if (Ext.isDefined(validations) && Ext.Object.getSize(validations)>0) {
                    field = this.addValidatorRuleConfigs(field, validations, config);
                }
                if(!field) {
                    return;
                }

                // check for associations
                associatedModel = Util.getBelongsToModel(modelField, model);
                if(associatedModel) {
                    Ext.apply(field, {
                        xtype: 'combobox',
                        store: Util.getStore(associatedModel, config),
                        displayField: Util.getDisplayFieldName(associatedModel),
                        valueField: associatedModel.prototype.idProperty || 'id',
                        queryMode: 'local'
                    });
                }

                // now make custom transforms
                field = this.internalTransformFieldConfig(field,type);
                if (typeof config.transformFieldConfig === 'function') {
                    field = config.transformFieldConfig(field, type);
                }

                // fileuploads are currently not supported in editor fields (ext doesn't render them usable)
                if (isEditorfield && field.xtype === 'fileuploadfield') {
                    field = undefined; // TODO Maybe on double click open a modal window for file uploads
                }

                return field;
            },

            /**
             * @private
             * This function is used if you are using Bancha.scaffold.form.Config with
             * the full Bancha library. It will automatically find all
             * api configurations
             */
            buildBanchaApiConfig: function(model, initialApi) {
                initialApi = initialApi || {};

                //<debug>
                if (!Bancha.initialized) {
                    // the user is using Bancha, but hasn't initialized yet
                    Ext.Error.raise({
                        plugin: 'Bancha Scaffold',
                        msg: [
                            'Bancha Scaffold: Bancha is not yet initalized, please ',
                            'init before using Ext.form.Panel with a scaffold config.'
                        ].join('')
                    });
                }
                //</debug>

                var modelName = Ext.ClassManager.getName(model),
                    stubName = modelName.substr(Bancha.modelNamespace.length + 1),
                    stub = Bancha.getStub(stubName);

                //<debug>
                if (!Ext.isDefined(stub)) {
                    Ext.Error.raise({
                        plugin: 'Bancha Scaffold',
                        msg: [
                            'Bancha Scaffold: Ext.form.Panel used with a scaffold config ',
                            'expects an remotable bancha model, but got an "normal" model ',
                            'or something else'
                        ].join('')
                    });
                }
                //</debug>

                return {
                    // The server-side method to call for load() requests
                    load: initialApi.read || stub.read,
                    // as first and only param you must add data: {id: id} when loading
                    // The server-side must mark the submit handler as a 'formHandler'
                    submit: initialApi.submit || stub.submit
                };
            },

            /**
             * @private
             * You only need this is you're adding additional buttoms to the form inside the
             * afterBuild function.
             * Since the form panel doesn't give us an useful scope to get the form panel,
             * this function will create an proper scope. The scope provides two functions:
             *  - this.getPanel() to get the form panel
             *  - this.getForm() to get the basic form
             *
             * @param {Function} handler A button handler function to apply the scope to
             * @param {Number|String} id The form panel id
             */
            buildButtonScope: (function () {
                var scopePrototype = {
                    getPanel: function () {
                        return this.panel || Ext.ComponentManager.get(this.id);
                    },
                    getForm: function () {
                        return this.form || this.getPanel().getForm();
                    }
                };

                return function (id) {
                    return Ext.apply({
                        id: id
                    }, scopePrototype);
                };
            }()),

            /**
             * @private
             * Builds form configs from the metadata, for scaffolding purposes.
             * By default data is loaded from the server if an id is supplied and
             * onSave it pushed the data to the server.
             *
             * Guesses are made by model field configs and validation rules.
             * @param {Bancha.scaffold.form.Config} config The config object to apply
             * @param {Object} initialPanelConfig   (optional) Some additional Ext.form.Panel
             *                                      configs which are applied to the config
             * @return {Object}                     object with Ext.form.Panel configs
             */
            buildConfig: function (config, initialPanelConfig) {
                initialPanelConfig = initialPanelConfig || {};
                var fields = [],
                    model = Bancha.scaffold.Util.getModel(config.target),
                    me = this,
                    formConfig,
                    prototypeFieldKeys,
                    fieldNames,
                    validations,
                    isExtJS5,
                    id,
                    loadFn;

                //<debug>
                if(!config.$className) { // normally we would use config.isInstance here, but that was introduced in Ext JS 4.1
                    Ext.Error.raise({
                        plugin: 'Bancha Scaffold',
                        msg: [
                            'Bancha Scaffold: Ext.form.Panel#buildConfig expects a object ',
                            'of class Bancha.scaffold.form.Config.'
                        ].join('')
                    });
                }
                //</debug>

                // build initial config
                formConfig = config.beforeBuild(model, config, initialPanelConfig) || {};

                // in Firefox fields.keys is a native function with Ext JS 4
                prototypeFieldKeys = typeof model.prototype.fields.keys === 'function' ? false : model.prototype.fields.keys;

                // if there is a fields config, use this for ordering
                // Otherwise use fields.keys for Sencha Touch and Ext JS 4
                fieldNames = config.fields || prototypeFieldKeys || Ext.Object.getKeys(model.fieldsMap);

                // build all columns
                validations = model.prototype.validations || model.validators; // ST & Ext JS 4 || Ext JS 5
                isExtJS5 = Ext.versions.extjs.major === 5;
                Ext.each(fieldNames, function(fieldName) {
                    if(Ext.Array.indexOf(config.exclude, fieldName) === -1) { // if not excluded
                        var field = isExtJS5 ? model.getField(fieldName) : model.prototype.fields.getByKey(fieldName);
                        fields.push(
                            me.buildFieldConfig(field, config, validations)
                        );
                    }
                });

                // probably not neccessary in Ext JS 4 and 5!
                // if one of the fields is a fileupload, mark the form
                Ext.each(fields, function (field) {
                    if (field.xtype === 'fileuploadfield') {
                        formConfig.isUpload = true;
                        formConfig.fileUpload = true;
                        return false;
                    }
                    return true;
                });

                // for scoping reason we have to force an id here
                id = initialPanelConfig.id || Ext.id(null, 'formpanel-');
                formConfig.id = id;

                // build buttons
                if(!config.hasOwnProperty('buttons')) {
                    // this a default, so clone before instanciating
                    // See also test case "should clone all configs, so that you
                    // can create multiple forms from the same defaults"
                    config.buttons = Ext.clone(config.buttons || []);
                }
                config.buttons = Bancha.scaffold.Util.replaceButtonPlaceHolders(config.buttons,
                                                            config, this.buildButtonScope(id));

                // extend formConfig
                Ext.apply(formConfig, initialPanelConfig, {
                    id: id,
                    api: config.buildApiConfig(model, initialPanelConfig.api),
                    paramOrder: ['data'],
                    items: fields,
                    buttons: config.buttons
                });

                // the scaffold config of the grid is saved as well
                formConfig.scaffold = config;

                // autoload the record
                if (Ext.isDefined(config.loadRecord) && config.loadRecord !== false) {
                    // load the record on component load
                    loadFn = function (component, options) {
                        component.load({
                            params: {
                                data: {
                                    data: {
                                        id: config.loadRecord
                                    }
                                } // bancha expects it this way
                            }
                        });
                    };
                    // if there's already a function, batch them
                    formConfig.listeners = formConfig.listeners || {};
                    if (formConfig.listeners.afterrender) {
                        formConfig.listeners.afterrender = Ext.Function.createSequence(formConfig.listeners.afterrender, loadFn);
                    } else {
                        formConfig.listeners.afterrender = loadFn;
                    }
                }

                // return after interceptor
                return config.afterBuild(formConfig, model, config, initialPanelConfig) || formConfig;
            }
        } // eo statics
    }); //eo override

    // Ext JS prior to 4.1 does not yet support statics, manually add them
    if(parseInt(Ext.versions.extjs.shortVersion,10) < 410) {
        Ext.apply(Ext.form.Panel, Ext.form.Panel.prototype.statics);
    }
});


text:
class DogsController < ApplicationController
  before_action :set_dog, only: [:show, :edit, :update, :destroy]

  # GET /dogs
  def index
    @dogs = Dog.all
  end

  # GET /dogs/1
  def show
  end

  # GET /dogs/new
  def new
    @dog = Dog.new
  end

  # GET /dogs/1/edit
  def edit

  end

  # POST /dogs
  def create
    @dog = Dog.new(dog_params)

    if @dog.save
      redirect_to @dog, notice: 'Dog was successfully created.'
    else
      render :new
    end
  end

  # PATCH/PUT /dogs/1
  def update
    if @dog.update(dog_params)
      redirect_to @dog, notice: 'Dog was successfully updated.'
    else
      render :edit
    end
  end

  # DELETE /dogs/1
  def destroy
    @dog.destroy
    redirect_to dogs_url, notice: 'Dog was successfully destroyed.'
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_dog
      @dog = Dog.find(params[:id])
    end

    # Only allow a trusted parameter "white list" through.
    def dog_params
      params.require(:dog).permit(:name)
    end
end


text:
package org.apache.bookkeeper.stream.storage.impl.cluster;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import org.apache.bookkeeper.discover.RegistrationClient;
import org.apache.bookkeeper.stream.storage.api.cluster.ClusterController;
import org.apache.bookkeeper.stream.storage.api.cluster.ClusterControllerLeader;
import org.apache.bookkeeper.stream.storage.api.cluster.ClusterControllerLeaderSelector;
import org.apache.bookkeeper.stream.storage.api.cluster.ClusterMetadataStore;
import org.apache.bookkeeper.stream.storage.conf.StorageConfiguration;
import org.apache.bookkeeper.stream.storage.impl.sc.StorageContainerController;
import org.apache.commons.configuration.CompositeConfiguration;
import org.junit.Before;
import org.junit.Test;

/**
 * Unit test {@link ClusterControllerImpl}.
 */
public class ClusterControllerImplTest {

    private ClusterControllerLeaderSelector leaderSelector;

    private ClusterController service;

    @Before
    public void setup() {
        this.leaderSelector = mock(ClusterControllerLeaderSelector.class);
        this.service = new ClusterControllerImpl(
            mock(ClusterMetadataStore.class),
            mock(RegistrationClient.class),
            mock(StorageContainerController.class),
            leaderSelector,
            new StorageConfiguration(new CompositeConfiguration()));
    }

    @Test
    public void testInitialize() {
        verify(leaderSelector, times(1))
            .initialize(any(ClusterControllerLeader.class));
    }

    @Test
    public void testStart() {
        service.start();
        verify(leaderSelector, times(1)).start();
    }

    @Test
    public void testStop() {
        service.start();
        service.stop();
        verify(leaderSelector, times(1)).close();
    }

}


text:
package azkaban.webapp;

import azkaban.executor.Executor;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonPropertyOrder;

/**
 * This POJO is used by GSON library to create a status JSON object. This class represents status
 * for azkaban cluster.
 */
@JsonPropertyOrder({"version", "pid", "installationPath", "usedMemory", "xmx", "isDatabaseUp", "executorStatusMap"})
public class ClusterStatus extends Status {

  @JsonProperty("executorStatusMap")
  private final Map<Integer, Executor> executorStatusMap;

  public ClusterStatus(final String version,
      final String pid,
      final String installationPath,
      final long usedMemory,
      final long xmx,
      final boolean isDatabaseUp,
      final Map<Integer, Executor> executorStatusMap) {
    super(version, pid, installationPath, usedMemory, xmx, isDatabaseUp);
    this.executorStatusMap = ImmutableMap.copyOf(executorStatusMap);
  }

  public Map<Integer, Executor> getExecutorStatusMap() {
    return executorStatusMap;
  }
}


text:
class GURL;

namespace storage {
class QuotaManager;
}

// Implementation of BrowsingDataQuotaHelper.  Since a client of
// BrowsingDataQuotaHelper should live in UI thread and QuotaManager lives in
// IO thread, we have to communicate over thread using PostTask.
class BrowsingDataQuotaHelperImpl : public BrowsingDataQuotaHelper {
 public:
  void StartFetching(const FetchResultCallback& callback) override;
  void RevokeHostQuota(const std::string& host) override;

 private:
  using PendingHosts = std::set<std::pair<std::string, storage::StorageType>>;
  using QuotaInfoMap = std::map<std::string, QuotaInfo>;

  explicit BrowsingDataQuotaHelperImpl(storage::QuotaManager* quota_manager);
  ~BrowsingDataQuotaHelperImpl() override;

  // Calls QuotaManager::GetOriginModifiedSince for each storage type.
  void FetchQuotaInfoOnIOThread(const FetchResultCallback& callback);

  // Callback function for QuotaManager::GetOriginModifiedSince.
  void GotOrigins(PendingHosts* pending_hosts,
                  const base::Closure& completion,
                  const std::set<GURL>& origins,
                  storage::StorageType type);

  // Calls QuotaManager::GetHostUsage for each (origin, type) pair.
  void OnGetOriginsComplete(const FetchResultCallback& callback,
                            PendingHosts* pending_hosts);

  // Callback function for QuotaManager::GetHostUsage.
  void GotHostUsage(QuotaInfoMap* quota_info,
                    const base::Closure& completion,
                    const std::string& host,
                    storage::StorageType type,
                    int64 usage);

  // Called when all QuotaManager::GetHostUsage requests are complete.
  void OnGetHostsUsageComplete(const FetchResultCallback& callback,
                               QuotaInfoMap* quota_info);

  void RevokeHostQuotaOnIOThread(const std::string& host);
  void DidRevokeHostQuota(storage::QuotaStatusCode status, int64 quota);

  scoped_refptr<storage::QuotaManager> quota_manager_;

  base::WeakPtrFactory<BrowsingDataQuotaHelperImpl> weak_factory_;

  friend class BrowsingDataQuotaHelper;
  friend class BrowsingDataQuotaHelperTest;

  DISALLOW_COPY_AND_ASSIGN(BrowsingDataQuotaHelperImpl);
};

#endif  // CHROME_BROWSER_BROWSING_DATA_BROWSING_DATA_QUOTA_HELPER_IMPL_H_


text:
====================================
Sphinx theme for documentation sites
====================================

Sphinx is commonly used for documentation sites, but there is a lack of simple
and elegant themes. This small theme tries to fix that through a minimalist
approach, offering a great way to build a small documentation without great
expectations that distract from the site's actual use: documenting a project.

--------
Features
--------

The main features offered by the theme are:

- Minimalist and reactive look
- `HTML5`_
- `Bootstrap 4`_
- `Font Awesome`_ icons
- Prepared for `Facebook's Open Graph`_ and `Twitter Cards`_

.. toctree::
   :hidden:

   acquire
   usage
   configuration
   other_config
   development

.. _HTML5: http://www.w3.org/TR/html5/
.. _Bootstrap 4: http://getbootstrap.com
.. _Font Awesome: https://fortawesome.github.io/Font-Awesome/
.. _highlight.js: https://highlightjs.org/
.. _Facebook's Open Graph: http://ogp.me/
.. _Twitter Cards: https://dev.twitter.com/cards/overview


text:
package com.shuframework.javaeedemo.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class MyInterceptor2 implements HandlerInterceptor{
	@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("MyInterceptor2.preHandle()在请求处理之前进行调用(Controller方法调用之前)");

        // 只有返回true才会继续向下执行,返回false取消当前请求
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

        System.out.println("MyInterceptor2.postHandle()请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)");

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

        System.out.println("MyInterceptor2.afterCompletion()在整个请求结束之后被调用,也就是在DispatcherServlet渲染了对应的视图之后执行(主要是用于进行资源清理工作)");

    }
}


text:
var bodyParser = require('body-parser');

var urlencodedParser = bodyParser.urlencoded({ extended: false });

module.exports = function(app) {

	app.get('/', function(req, res) {
		res.render('index');
	});

	app.get('/person/:id', function(req, res) {
		res.render('person', { ID: req.params.id, Qstr: req.query.qstr });
	});

	app.post('/person', urlencodedParser, function(req, res) {
		res.send('Thank you!');
		console.log(req.body.firstname);
		console.log(req.body.lastname);
	});

}


text:
package org.r4j;

public class Election {

	private final int members;

	private int votes = 0;

	private final long term;

	public Election(int members, long term) {
		super();
		this.members = members;
		this.term = term;
	}

	public int getMembers() {
		return members;
	}

	public int getVotes() {
		return votes;
	}

	public long getTerm() {
		return term;
	}

	public void incrementVotes() {
		votes++;
	}

	public boolean hasWon() {
		return members/2 < votes;
	}

}


text:
import pandas
import ujson as json
from tqdm import tqdm
import random

all_record = list()
with open('/home/data/corpora/YELP/yelp_dataset_challenge_round13/user.json', 'r') as f:
    for line in f:
        all_record.append(json.loads(line))

with open('selected_user_ids.json', 'r') as f:
    selected_user_ids = json.load(f)
# random.shuffle(selected_user_ids)
selected_user_ids = set(selected_user_ids[:20000])

selected_edges = list()

for tmp_record in tqdm(all_record):
    if tmp_record['user_id'] in selected_user_ids:
        tmp_friends = tmp_record['friends'].split(', ')
        for friend_id in tmp_friends:
            if friend_id in selected_user_ids:
                selected_edges.append((tmp_record['user_id'], friend_id))

print('extracted edges:', len(selected_edges))

with open('selected_edges.json', 'w') as f:
    json.dump(selected_edges, f)

print('end')


text:
import Service, { inject, service } from '@ember/service';
import { Object as EmberObject } from '@ember/-internals/runtime';
import { buildOwner } from 'internal-test-helpers';
import { moduleFor, AbstractTestCase } from 'internal-test-helpers';

moduleFor(
  'inject - decorator',
  class extends AbstractTestCase {
    ['@test works with native decorators'](assert) {
      let owner = buildOwner();

      class MainService extends Service {}

      class Foo extends EmberObject {
        @inject('main') main;
      }

      owner.register('service:main', MainService);
      owner.register('foo:main', Foo);

      let foo = owner.lookup('foo:main');

      assert.ok(foo.main instanceof Service, 'service injected correctly');
    }

    ['@test uses the decorated property key if not provided'](assert) {
      let owner = buildOwner();

      class MainService extends Service {}

      class Foo extends EmberObject {
        @inject main;
      }

      owner.register('service:main', MainService);
      owner.register('foo:main', Foo);

      let foo = owner.lookup('foo:main');

      assert.ok(foo.main instanceof Service, 'service injected correctly');
    }
  }
);

moduleFor(
  'service - decorator',
  class extends AbstractTestCase {
    ['@test works with native decorators'](assert) {
      let owner = buildOwner();

      class MainService extends Service {}

      class Foo extends EmberObject {
        @service('main') main;
      }

      owner.register('service:main', MainService);
      owner.register('foo:main', Foo);

      let foo = owner.lookup('foo:main');

      assert.ok(foo.main instanceof Service, 'service injected correctly');
    }

    ['@test uses the decorated property key if not provided'](assert) {
      let owner = buildOwner();

      class MainService extends Service {}

      class Foo extends EmberObject {
        @service main;
      }

      owner.register('service:main', MainService);
      owner.register('foo:main', Foo);

      let foo = owner.lookup('foo:main');

      assert.ok(foo.main instanceof Service, 'service injected correctly');
    }
  }
);


text:
package cmd

import (
	"context"
	"fmt"
	"time"

	"github.com/fatih/color"
	"github.com/google/go-github/github"
	"github.com/spf13/cobra"
	"github.com/w3st3ry/tekleader/tekleader"
)

const (
	cVersion    = "v" + tekleader.Version
	repOwner    = "w3st3ry"
	projectName = "tekleader"
)

func init() {
	RootCmd.AddCommand(versionCmd)
}

var versionCmd = &cobra.Command{
	Use:   "version",
	Short: "Prints the tekleader version and any available update",
	Long: "Display information about current tekleader version\n" +
		"and check if a new release is available on GitHub.",
	RunE: func(cmd *cobra.Command, args []string) error {
		client := github.NewClient(nil)

		ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)

		color.White("Version information:\n")
		current, _, err := client.Repositories.GetReleaseByTag(ctx, repOwner, projectName, cVersion)
		printRelease(current, err)
		if err != nil {
			defer cancel()
			return nil
		}

		releases, _, err := client.Repositories.ListReleases(ctx, repOwner, projectName, &github.ListOptions{PerPage: 1})
		latest := releases[len(releases)-1]

		if *current.TagName == *latest.TagName {
			color.Green("Your version is up to date.")
		} else {
			color.Yellow("A new version is available:\n")
			printRelease(latest, err)
			color.Yellow("Visit %s for more information about tekleader", *latest.HTMLURL)
		}

		defer cancel()
		return err
	},
}

func printRelease(release *github.RepositoryRelease, err error) {
	if err != nil {
		color.Red("Your version is not recognized or invalid! Check the error(s) below.\n%v", err)
		return
	}

	print := fmt.Printf
	print("* Release name: %s\n", *release.Name)
	print("* Related git tag: %s\n", *release.TagName)
	print("* Stable release: %t\n", !*release.Prerelease)

	if release.PublishedAt != nil && !release.PublishedAt.IsZero() {
		print("* Release date: %s\n", *release.PublishedAt)
	}
}


text:
@class BarRequest;
@class BarRequestBuilder;
@class BarResponse;
@class BarResponseBuilder;
@class BoolMessage;
@class BoolMessageBuilder;
@class FooClientMessage;
@class FooClientMessageBuilder;
@class FooRequest;
@class FooRequestBuilder;
@class FooResponse;
@class FooResponseBuilder;
@class FooServerMessage;
@class FooServerMessageBuilder;
@class ForeignMessage;
@class ForeignMessageBuilder;
@class ImportMessage;
@class ImportMessageBuilder;
@class Int32Message;
@class Int32MessageBuilder;
@class Int64Message;
@class Int64MessageBuilder;
@class MoreBytes;
@class MoreBytesBuilder;
@class MoreString;
@class MoreStringBuilder;
@class NestedTestAllTypes;
@class NestedTestAllTypesBuilder;
@class OneBytes;
@class OneBytesBuilder;
@class OneString;
@class OneStringBuilder;
@class OptionalGroup_extension;
@class OptionalGroup_extensionBuilder;
@class PublicImportMessage;
@class PublicImportMessageBuilder;
@class RepeatedGroup_extension;
@class RepeatedGroup_extensionBuilder;
@class SparseEnumMessage;
@class SparseEnumMessageBuilder;
@class TestAllExtensions;
@class TestAllExtensionsBuilder;
@class TestAllTypes;
@class TestAllTypesBuilder;
@class TestAllTypesNestedMessage;
@class TestAllTypesNestedMessageBuilder;
@class TestAllTypesOptionalGroup;
@class TestAllTypesOptionalGroupBuilder;
@class TestAllTypesRepeatedGroup;
@class TestAllTypesRepeatedGroupBuilder;
@class TestCamelCaseFieldNames;
@class TestCamelCaseFieldNamesBuilder;
@class TestCommentInjectionMessage;
@class TestCommentInjectionMessageBuilder;
@class TestDeprecatedFields;
@class TestDeprecatedFieldsBuilder;
@class TestDupFieldNumber;
@class TestDupFieldNumberBar;
@class TestDupFieldNumberBarBuilder;
@class TestDupFieldNumberBuilder;
@class TestDupFieldNumberFoo;
@class TestDupFieldNumberFooBuilder;
@class TestDynamicExtensions;
@class TestDynamicExtensionsBuilder;
@class TestDynamicExtensionsDynamicMessageType;
@class TestDynamicExtensionsDynamicMessageTypeBuilder;
@class TestEagerMessage;
@class TestEagerMessageBuilder;
@class TestEmptyMessage;
@class TestEmptyMessageBuilder;
@class TestEmptyMessageWithExtensions;
@class TestEmptyMessageWithExtensionsBuilder;
@class TestExtremeDefaultValues;
@class TestExtremeDefaultValuesBuilder;
@class TestFieldOrderings;
@class TestFieldOrderingsBuilder;
@class TestForeignNested;
@class TestForeignNestedBuilder;
@class TestLazyMessage;
@class TestLazyMessageBuilder;
@class TestLiteImportsNonlite;
@class TestLiteImportsNonliteBuilder;
@class TestMultipleExtensionRanges;
@class TestMultipleExtensionRangesBuilder;
@class TestMutualRecursionA;
@class TestMutualRecursionABuilder;
@class TestMutualRecursionB;
@class TestMutualRecursionBBuilder;
@class TestNestedExtension;
@class TestNestedExtensionBuilder;
@class TestNestedMessageHasBits;
@class TestNestedMessageHasBitsBuilder;
@class TestNestedMessageHasBitsNestedMessage;
@class TestNestedMessageHasBitsNestedMessageBuilder;
@class TestOneof;
@class TestOneof2;
@class TestOneof2Builder;
@class TestOneof2FooGroup;
@class TestOneof2FooGroupBuilder;
@class TestOneof2NestedMessage;
@class TestOneof2NestedMessageBuilder;
@class TestOneofBackwardsCompatible;
@class TestOneofBackwardsCompatibleBuilder;
@class TestOneofBackwardsCompatibleFooGroup;
@class TestOneofBackwardsCompatibleFooGroupBuilder;
@class TestOneofBuilder;
@class TestOneofFooGroup;
@class TestOneofFooGroupBuilder;
@class TestPackedExtensions;
@class TestPackedExtensionsBuilder;
@class TestPackedTypes;
@class TestPackedTypesBuilder;
@class TestParsingMerge;
@class TestParsingMergeBuilder;
@class TestParsingMergeOptionalGroup;
@class TestParsingMergeOptionalGroupBuilder;
@class TestParsingMergeRepeatedFieldsGenerator;
@class TestParsingMergeRepeatedFieldsGeneratorBuilder;
@class TestParsingMergeRepeatedFieldsGeneratorGroup1;
@class TestParsingMergeRepeatedFieldsGeneratorGroup1Builder;
@class TestParsingMergeRepeatedFieldsGeneratorGroup2;
@class TestParsingMergeRepeatedFieldsGeneratorGroup2Builder;
@class TestParsingMergeRepeatedGroup;
@class TestParsingMergeRepeatedGroupBuilder;
@class TestReallyLargeTagNumber;
@class TestReallyLargeTagNumberBuilder;
@class TestRecursiveMessage;
@class TestRecursiveMessageBuilder;
@class TestRepeatedScalarDifferentTagSizes;
@class TestRepeatedScalarDifferentTagSizesBuilder;
@class TestRequired;
@class TestRequiredBuilder;
@class TestRequiredForeign;
@class TestRequiredForeignBuilder;
@class TestRequiredOneof;
@class TestRequiredOneofBuilder;
@class TestRequiredOneofNestedMessage;
@class TestRequiredOneofNestedMessageBuilder;
@class TestUnpackedExtensions;
@class TestUnpackedExtensionsBuilder;
@class TestUnpackedTypes;
@class TestUnpackedTypesBuilder;
@class Uint32Message;
@class Uint32MessageBuilder;
@class Uint64Message;
@class Uint64MessageBuilder;

@interface UnittestLiteImportsNonliteRoot : NSObject {
}
+ (PBExtensionRegistry*) extensionRegistry;
+ (void) registerAllExtensions:(PBMutableExtensionRegistry*) registry;
@end

#define TestLiteImportsNonlite_message @"message"
@interface TestLiteImportsNonlite : PBGeneratedMessage<GeneratedMessageProtocol> {
@private
  BOOL hasMessage_:1;
  TestAllTypes* message;
}
- (BOOL) hasMessage;
@property (readonly, strong) TestAllTypes* message;

+ (instancetype) defaultInstance;
- (instancetype) defaultInstance;

- (BOOL) isInitialized;
- (void) writeToCodedOutputStream:(PBCodedOutputStream*) output;
- (TestLiteImportsNonliteBuilder*) builder;
+ (TestLiteImportsNonliteBuilder*) builder;
+ (TestLiteImportsNonliteBuilder*) builderWithPrototype:(TestLiteImportsNonlite*) prototype;
- (TestLiteImportsNonliteBuilder*) toBuilder;

+ (TestLiteImportsNonlite*) parseFromData:(NSData*) data;
+ (TestLiteImportsNonlite*) parseFromData:(NSData*) data extensionRegistry:(PBExtensionRegistry*) extensionRegistry;
+ (TestLiteImportsNonlite*) parseFromInputStream:(NSInputStream*) input;
+ (TestLiteImportsNonlite*) parseFromInputStream:(NSInputStream*) input extensionRegistry:(PBExtensionRegistry*) extensionRegistry;
+ (TestLiteImportsNonlite*) parseFromCodedInputStream:(PBCodedInputStream*) input;
+ (TestLiteImportsNonlite*) parseFromCodedInputStream:(PBCodedInputStream*) input extensionRegistry:(PBExtensionRegistry*) extensionRegistry;
@end

@interface TestLiteImportsNonliteBuilder : PBGeneratedMessageBuilder {
@private
  TestLiteImportsNonlite* resultTestLiteImportsNonlite;
}

- (TestLiteImportsNonlite*) defaultInstance;

- (TestLiteImportsNonliteBuilder*) clear;
- (TestLiteImportsNonliteBuilder*) clone;

- (TestLiteImportsNonlite*) build;
- (TestLiteImportsNonlite*) buildPartial;

- (TestLiteImportsNonliteBuilder*) mergeFrom:(TestLiteImportsNonlite*) other;
- (TestLiteImportsNonliteBuilder*) mergeFromCodedInputStream:(PBCodedInputStream*) input;
- (TestLiteImportsNonliteBuilder*) mergeFromCodedInputStream:(PBCodedInputStream*) input extensionRegistry:(PBExtensionRegistry*) extensionRegistry;

- (BOOL) hasMessage;
- (TestAllTypes*) message;
- (TestLiteImportsNonliteBuilder*) setMessage:(TestAllTypes*) value;
- (TestLiteImportsNonliteBuilder*) setMessageBuilder:(TestAllTypesBuilder*) builderForValue;
- (TestLiteImportsNonliteBuilder*) mergeMessage:(TestAllTypes*) value;
- (TestLiteImportsNonliteBuilder*) clearMessage;
@end

// @@protoc_insertion_point(global_scope)