text:
package org.apache.commons.beanutils2;

import java.util.HashMap;
import java.util.Map;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

/**
 * JUnit Test Case containing microbenchmarks for PropertyUtils.
 *
 */

public class PropertyUtilsBenchCase extends TestCase {

    /**
     * Constructs a new instance of this test case.
     *
     * @param name Name of the test case
     */
    public PropertyUtilsBenchCase(final String name) {

        super(name);

    }

    // Basic loop counter
    private long counter = 100000;

    // DynaClass for inDyna and outDyna
    private DynaClass dynaClass = null;

    // Input objects that have identical sets of properties and values.
    private BenchBean inBean = null;
    private DynaBean inDyna = null;
    private Map<String, Object> inMap = null;

    // Output objects that have identical sets of properties.
    private BenchBean outBean = null;
    private DynaBean outDyna = null;

    // PropertyUtilsBean instance to be used
    private PropertyUtilsBean pu = null;

    /**
     * Sets up instance variables required by this test case.
     */
    @Override
    public void setUp() throws Exception {

        // Set up loop counter (if property specified)
        final String prop = System.getProperty("counter");
        if (prop != null) {
            counter = Long.parseLong(prop);
        }

        // Set up DynaClass for our DynaBean instances
        dynaClass = new BasicDynaClass
            ("BenchDynaClass", null,
             new DynaProperty[]{
                 new DynaProperty("booleanProperty", Boolean.TYPE),
                 new DynaProperty("byteProperty", Byte.TYPE),
                 new DynaProperty("doubleProperty", Double.TYPE),
                 new DynaProperty("floatProperty", Float.TYPE),
                 new DynaProperty("intProperty", Integer.TYPE),
                 new DynaProperty("longProperty", Long.TYPE),
                 new DynaProperty("shortProperty", Short.TYPE),
                 new DynaProperty("stringProperty", String.class),
             });

        // Create input instances
        inBean = new BenchBean();
        inMap = new HashMap<>();
        inMap.put("booleanProperty", new Boolean(inBean.getBooleanProperty()));
        inMap.put("byteProperty", new Byte(inBean.getByteProperty()));
        inMap.put("doubleProperty", new Double(inBean.getDoubleProperty()));
        inMap.put("floatProperty", new Float(inBean.getFloatProperty()));
        inMap.put("intProperty", new Integer(inBean.getIntProperty()));
        inMap.put("longProperty", new Long(inBean.getLongProperty()));
        inMap.put("shortProperty", new Short(inBean.getShortProperty()));
        inMap.put("stringProperty", inBean.getStringProperty());
        inDyna = dynaClass.newInstance();
        for (final Map.Entry<String, Object> e : inMap.entrySet()) {
            inDyna.set(e.getKey(), e.getValue());
        }

        // Create output instances
        outBean = new BenchBean();
        outDyna = dynaClass.newInstance();
        inDyna = dynaClass.newInstance();
        for (final Map.Entry<String, Object> e : inMap.entrySet()) {
            outDyna.set(e.getKey(), e.getValue());
        }

        // Set up PropertyUtilsBean instance we will use
        pu = PropertyUtilsBean.getInstance();

    }

    /**
     * Creates the tests included in this test suite.
     */
    public static Test suite() {

        return new TestSuite(PropertyUtilsBenchCase.class);

    }

    /**
     * Tear down instance variables required by this test case.
     */
    @Override
    public void tearDown() {

        dynaClass = null;
        inBean = null;
        inDyna = null;
        inMap = null;
        outBean = null;
        outDyna = null;
        pu = null;

    }

    // Time copyProperties() from a bean
    public void testCopyPropertiesBean() throws Exception {

        long startMillis;
        long stopMillis;

        // Bean->Bean
        for (long i = 0; i < counter; i++) {
            pu.copyProperties(outBean, inBean);
        }
        startMillis = System.currentTimeMillis();
        for (long i = 0; i < counter; i++) {
            pu.copyProperties(outBean, inBean);
        }
        stopMillis = System.currentTimeMillis();
        System.err.println("PU.copyProperties(bean,bean), count=" + counter +
                           ", time=" + (stopMillis - startMillis));

        // Bean->Dyna
        for (long i = 0; i < counter; i++) {
            pu.copyProperties(outDyna, inBean);
        }
        startMillis = System.currentTimeMillis();
        for (long i = 0; i < counter; i++) {
            pu.copyProperties(outDyna, inBean);
        }
        stopMillis = System.currentTimeMillis();
        System.err.println("PU.copyProperties(dyna,bean), count=" + counter +
                           ", time=" + (stopMillis - startMillis));

    }

    // Time copyProperties() from a DynaBean
    public void testCopyPropertiesDyna() throws Exception {

        long startMillis;
        long stopMillis;

        // Dyna->Bean
        for (long i = 0; i < counter; i++) {
            pu.copyProperties(outBean, inDyna);
        }
        startMillis = System.currentTimeMillis();
        for (long i = 0; i < counter; i++) {
            pu.copyProperties(outBean, inDyna);
        }
        stopMillis = System.currentTimeMillis();
        System.err.println("PU.copyProperties(bean,dyna), count=" + counter +
                           ", time=" + (stopMillis - startMillis));

        // Dyna->Dyna
        for (long i = 0; i < counter; i++) {
            pu.copyProperties(outDyna, inDyna);
        }
        startMillis = System.currentTimeMillis();
        for (long i = 0; i < counter; i++) {
            pu.copyProperties(outDyna, inDyna);
        }
        stopMillis = System.currentTimeMillis();
        System.err.println("PU.copyProperties(dyna,dyna), count=" + counter +
                           ", time=" + (stopMillis - startMillis));

    }

    // Time copyProperties() from a Map
    public void testCopyPropertiesMap() throws Exception {

        long startMillis;
        long stopMillis;

        // Dyna->Bean
        for (long i = 0; i < counter; i++) {
            pu.copyProperties(outBean, inMap);
        }
        startMillis = System.currentTimeMillis();
        for (long i = 0; i < counter; i++) {
            pu.copyProperties(outBean, inMap);
        }
        stopMillis = System.currentTimeMillis();
        System.err.println("PU.copyProperties(bean, map), count=" + counter +
                           ", time=" + (stopMillis - startMillis));

        // Dyna->Dyna
        for (long i = 0; i < counter; i++) {
            pu.copyProperties(outDyna, inMap);
        }
        startMillis = System.currentTimeMillis();
        for (long i = 0; i < counter; i++) {
            pu.copyProperties(outDyna, inMap);
        }
        stopMillis = System.currentTimeMillis();
        System.err.println("PU.copyProperties(dyna, map), count=" + counter +
                           ", time=" + (stopMillis - startMillis));

    }

}


text:
package org.uberfire.ext.wires.client.demo.trees.shapes;

import com.ait.lienzo.client.core.shape.Circle;
import org.uberfire.ext.wires.core.trees.client.shapes.WiresBaseTreeNode;

/**
 * Example Node that can only have WiresExampleTreeNode2 types of node added as children
 */
public class WiresExampleTreeNode2 extends WiresExampleTreeNode1 {

    public WiresExampleTreeNode2(final Circle shape) {
        super(shape);
    }

    @Override
    public boolean acceptChildNode(final WiresBaseTreeNode child) {
        return child instanceof WiresExampleTreeNode2;
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TestDataSeeding.Model;

namespace TestDataSeeding.DbClient
{
    internal class MsSqlQueryBuilder
    {
        /// <summary>
        /// Creates the select query to retrieve the given entity.
        /// </summary>
        /// <param name="entityStructure">An entity structure.</param>
        /// <param name="primaryKeyValues">An string list containing the primary keys.</param>
        /// <returns>The SQL SELECT query string.</returns>
        internal string CreateSelectQuery(EntityStructure entityStructure, List<string> primaryKeyValues)
        {
            //SELECT @Attribute1, @AttributeN//
            StringBuilder builder = new StringBuilder("SELECT ");

            string separator = "";
            for (var i = 0; i < entityStructure.Attributes.Count; i++)
            {
                string attribute = entityStructure.Attributes.ElementAt(i).Key;
                string type = entityStructure.Attributes.ElementAt(i).Value;

                builder.Append(separator)
                       .Append(ConvertAttribute(attribute,type));
                separator = ", ";
            }

            // FROM @TableName WHERE @KeyAttribute1 = @KeyValue1 AND @KeyAttributeN = @KeyValueN//
            builder.Append(" FROM ")
                   .Append(entityStructure.Name)
                   .Append(" WHERE ");

            separator = "";
            for (var i = 0; i < entityStructure.PrimaryKeys.Count; i++)
            {
                string attribute = entityStructure.PrimaryKeys[i];
                string type = entityStructure.Attributes[entityStructure.PrimaryKeys[i]];

                builder.Append(separator)
                       .Append('"').Append(attribute).Append('"').Append(" = ")
                       .Append(ConvertValue(primaryKeyValues[i], type));
                separator = " AND ";
            }

            return builder.ToString();
        }

        /// <summary>
        /// Creates the select query to retrieve the given entities.
        /// </summary>
        /// <param name="entityStructure">An entity structure.</param>
        /// <param name="keyValues">The dictionary with the given keys and values.</param>
        /// <returns>The SQL SELECT query string.</returns>
        internal string CreateSelectQuery(EntityStructure entityStructure, Dictionary<string, string> keyValues)
        {
            //SELECT @Attribute1, @AttributeN//
            StringBuilder builder = new StringBuilder("SELECT ");

            string separator = "";
            for (var i = 0; i < entityStructure.Attributes.Count; i++)
            {
                string attribute = entityStructure.Attributes.ElementAt(i).Key;
                string type = entityStructure.Attributes.ElementAt(i).Value;

                builder.Append(separator)
                       .Append(ConvertAttribute(attribute, type));
                separator = ", ";
            }
            // FROM @TableName WHERE @KeyAttribute1 = @KeyValue1 AND @KeyAttributeN = @KeyValueN//
            builder.Append(" FROM ")
                   .Append(entityStructure.Name)
                   .Append(" WHERE ");

            separator = "";
            for (var i = 0; i < keyValues.Count; i++)
            {
                string attribute = keyValues.ElementAt(i).Key;
                string type = entityStructure.Attributes[keyValues.ElementAt(i).Key];

                builder.Append(separator)
                       .Append('"').Append(attribute).Append('"').Append(" = ")
                       .Append(ConvertValue(keyValues.ElementAt(i).Value, type));
                separator = " AND ";
            }

            return builder.ToString();
        }

        /// <summary>
        /// Creates the update query which updates the given entity.
        /// </summary>
        /// <param name="entity">An entity.</param>
        /// <param name="entityStructure">The structure of the given entity.</param>
        /// <returns>The SQL UPDATE query string.</returns>
        internal string CreateUpdateQuery(Entity entity, EntityStructure entityStructure)
        {
            //we get the names of those attributes which are not PrimaryKeys
            var nonPrimaryKeyAttributes = entityStructure.Attributes.Where(attribute => !entityStructure.IsPrimaryKey(attribute.Key));

            //UPDATE @Tablename SET @Attribute1 = @Value1 , @AttributeN = @ValueN//
            StringBuilder builder = new StringBuilder("UPDATE ");
            builder.Append(entity.Name)
                   .Append(" SET ");

            string separator = "";
            foreach (var item in nonPrimaryKeyAttributes)
            {
                string value = entity.AttributeValues[item.Key];
                string type = item.Value;

                builder.Append(separator)
                       .Append('"')
                       .Append(item.Key)
                       .Append('"')
                       .Append(" = ")
                       .Append(ConvertValue(value,type));
                separator = ", ";
            }
            // WHERE @KeyAttribute1 = @KeyValue1 AND @KeyAttributeN = @KeyValueN//
            builder.Append(" WHERE ");

            separator = "";
            for (var i = 0; i < entityStructure.PrimaryKeys.Count; i++)
            {
                string attribute = entityStructure.PrimaryKeys[i];
                string value = entity.AttributeValues[entityStructure.PrimaryKeys[i]];
                string type = entityStructure.Attributes[entityStructure.PrimaryKeys[i]];

                builder.Append(separator)
                       .Append('"').Append(attribute).Append('"').Append(" = ")
                       .Append(ConvertValue(value,type));

                separator = " AND ";
            }

            return builder.ToString();
        }

        /// <summary>
        /// Creates the insert query to insert the given entity.
        /// </summary>
        /// <param name="entity">An entity.</param>
        /// <param name="entityStructure">The structure of the given entity.</param>
        /// <returns>The SQL INSERT query string.</returns>
        internal string CreateInsertQuery(Entity entity, EntityStructure entityStructure)
        {
            //INSERT INTO @Tablename VALUES (@Value1, @ValueN)//
            StringBuilder builder = new StringBuilder("INSERT INTO ");
            builder.Append(entity.Name)
                   .Append(" VALUES (");

            string separator = "";
            for (int i = 0; i < entity.AttributeValues.Count; i++)
            {
                string value = entity.AttributeValues.ElementAt(i).Value;
                string type = entityStructure.Attributes[entity.AttributeValues.ElementAt(i).Key];

                builder.Append(separator)
                       .Append(ConvertValue(value,type));

                separator=", ";
            }

            builder.Append(")");

            return builder.ToString();
        }

        /// <summary>
        /// Prepares the <paramref name="attribute"/> for a SELECT command.
        /// </summary>
        /// <param name="attribute">The attribute to be handled.</param>
        /// <param name="type">Type of the <paramref name="attribute"/>.</param>
        /// <returns>The attribte string for the SELECT <paramref name="attribute"/> command. </returns>
        private string ConvertAttribute(string attribute, string type)
        {
            StringBuilder builder = new StringBuilder();

            string[] datetimes = { "date", "time", "datetime", "datetime2", "smalldatetime", "datetimeoffset" };
            string[] binaries = { "binary", "varbinary" };
            string image = "image";
            string timestamp = "timestamp";

            //CONVERT(VARCHAR(34), "@DatetimeAttribute", 126) AS "@DatetimeAttribute"
            if (datetimes.Contains(type))
            {
                builder.Append("CONVERT(VARCHAR(34), ").Append('"').Append(attribute).Append('"')
                       .Append(", 126) AS ").Append('"').Append(attribute).Append('"');
                return builder.ToString();
            }
            //CONVERT(VARCHAR(MAX), "@BinaryAttribute", 1) AS "@BinaryAttribute"
            else if (binaries.Contains(type))
            {
                builder.Append("CONVERT(VARCHAR(MAX), ").Append('"').Append(attribute).Append('"')
                       .Append(", 1) AS ").Append('"').Append(attribute).Append('"');
                return builder.ToString();
            }
            //CONVERT(VARCHAR(MAX), CONVERT(VARBINARY(MAX), "@ImageAttribute", 1), 1) AS "@ImageAttribute"
            else if (type == image)
            {
                builder.Append("CONVERT(VARCHAR(MAX), CONVERT(VARBINARY(MAX), ")
                       .Append('"').Append(attribute).Append('"').Append(", 1), 1) AS ")
                       .Append('"').Append(attribute).Append('"');
                return builder.ToString();
            }
            //'null' AS "@TimestampAttribute"
            else if (type == timestamp)
            {
                builder.Append("'null' AS ").Append('"').Append(attribute).Append('"');
                return builder.ToString();
            }
            //"@OtherAttribute"
            else
            {
                builder.Append('"').Append(attribute).Append('"');
                return builder.ToString();
            }
        }

        /// <summary>
        /// Prepares the <paramref name="value"/> for an insert command or where statement.
        /// </summary>
        /// <param name="value">The value to be handled.</param>
        /// <param name="type">Type of the <paramref name="value"/>.</param>
        /// <returns>The value string for the Insert <paramref name="value"/> command or where statement.</returns>
        private string ConvertValue(string value, string type)
        {
            if (value == "") return "null";

            string[] strings = { "char", "varchar", "text", "sql_variant", "bit", "xml",
                                 "geography", "geometry", "hierarchyid", "uniqueidentifier" };
            string[] nstrings = { "nchar", "nvarchar", "ntext" };
            string[] datetimes = { "date", "time", "datetime", "datetime2", "smalldatetime", "datetimeoffset" };

            StringBuilder builder = new StringBuilder();

            //'stringValue'// -also escapes the sql quote signs(')
            if (strings.Contains(type))
            {
                builder.Append("'")
                   .Append(value.Replace("'", "''"))
                   .Append("'");
                return builder.ToString();
            }
            //N'stringValue'// -also escapes the sql quote signs(')
            else if (nstrings.Contains(type))
            {
                builder.Append("N'")
                   .Append(value.Replace("'", "''"))
                   .Append("'");
                return builder.ToString();
            }
            //'datetimeValue'//
            else if (datetimes.Contains(type))
            {
                builder.Append("'")
                   .Append(value)
                   .Append("'");
                return builder.ToString();
            }
            //numericValue//
            else
            {
                return value;
            }
        }
    }
}


text:
package tk.exarus.kpi.security

import scala.io.Source.fromResource

/**
  * Thread-safe. Immutable.
  *
  * @author Ruslan Gunawardana
  */
class CiphertextRepository {
  import CiphertextRepository.ciphertextPaths

  def ciphertext(num: Int): String = fromResource(ciphertextPaths(num)).mkString
}

object CiphertextRepository {
  private val ciphertextPaths = Seq("1.txt", "2.txt", "3.txt", "4.txt") map ("ciphertext/" + _)
}


text:
package services

import com.typesafe.config.ConfigFactory

/**
 *
 */
object ConfigService extends BaseService {

  private lazy val rootConfig = ConfigFactory.load()

  val currentInstanceName = "rbcwidget"

  def getConfigNames(name: String) : List[String] = {
    import collection.JavaConversions._
    rootConfig.getConfig(name).root().keySet.toList
  }

}


text:
json2text generate free-format text from JSON templates (e.g. HTML generation).

Install package globally:
```
npm install json2text -g
```

## Tools
 - ```j2t [EXTENSION]```: compile templates
 - ```j2n FILE```: generate template stubs from FILE
 - ```j2f FILE [EXTENSION]```: convers ```_text``` fields from FILE to ```_file``` fields.

## How to use example

### 1. Define template elements
Create file with ```.j2.node.json``` extension (e.g. ```elements.j2.node.json```). Include the following text:
```
[
	{
		"_name": "list",
		"style": "disc",
		"_text": "<ul style='list-style-type:%%style%%'>\n%%_text%%</ul>"
	}, {
		"_name": "item",
		"_text": "<li> %%_text%% </li>\n"
	}
]
```

JSON fields:
 - ```_name```: node(s) names.
 - ```_text```: node's templating string.
 - OPTIONAL: other fileds represent arguments with default values (e.g. ```style```)

### 2. Define template layout
Create file with ```.j2.json``` extension (e.g. ```layout.j2.json```). Include the following text:
```
{
	"_node": "list",
	"style": "circle",
	"_child": [
		{"_node": "item", "_child": "list item #1"},
		{"_node": "item", "_child": "list item #2"}
	]
}
```

JSON fields:
 - ```_node```: element name
 - ```_child```: (string|object|list): node content
 - OPTIONAL: other fileds represent arguments values (e.g. ```style = circle```)

### 3. Compile template
Run:
```
j2t html
```

This command will search current work directory file-tree for ```.j2.node.json``` and ```.j2.json``` files and would compile ```.html``` output files (```.out``` by default):
```
<ul style='list-style-type:circle'>
<li> list item #1 </li>
<li> list item #2 </li>
</ul>
```

## Features and info
 - Each ```.j2.node.json``` and ```.j2.json``` change leads to output file(s) regeneration
 - JSON fields starts with ```_ (underscore)``` (e.g. ```_node```, ```_name```) are reserved for json2text future use, don't use them for attributes

## TODO
 - Replace ```fsmonitor```. Updates detection on Mac is reported to be slow. Copy & paste does not detected
 - Add flag to generate ones and exit
 - Color console print


text:
namespace SvNaum.Web.Controllers
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;

    using SvNaum.Models;

    public class HomeController : BaseController
    {
        public ActionResult Index()
        {
            List<NewsSingle> news = new List<NewsSingle>();

            news = this.Repo.FindAll<NewsSingle>(this.Context.News).Reverse().ToList();

            return View(news);
        }

        [HttpGet]
        public ActionResult Timetable()
        {
            List<Ministration> result = new List<Ministration>();

            try
            {
                result = this.Repo.FindAll<Ministration>(this.Context.Ministration).OrderBy(m => m.Date).ToList();
            }
            catch (System.Exception)
            {

            }

            return View(result);
        }

        public ActionResult Pictures()
        {
            var imagesGroups = new List<ImagesGroup>();

            try
            {
                imagesGroups = this.Repo.FindAll<ImagesGroup>(this.Context.ImagesGroups).Reverse().ToList();
            }
            catch (System.Exception)
            {

            }

            return View(imagesGroups);
        }

        public ActionResult Sermons(int page = 0, string id = null)
        {
            if (page < 0)
            {
                page = 0;
            }

            this.ViewBag.PrevPage = page - 1;
            this.ViewBag.NextPage = page + 1;

            long sermonsCount = this.Context.Sermons.Count();
            this.ViewBag.SermonsCount = sermonsCount;

            if (!string.IsNullOrEmpty(id))
            {
                var ids = this.Repo.FindAll(this.Context.Sermons).SetFields(new string[] { "_id", "Date" }).OrderByDescending(s => s.Date).ToList();

                for (int i = 0; i < ids.Count; i++)
                {
                    if (ids[i].Id == id)
                    {
                        this.ViewBag.PrevPage = i - 1;
                        this.ViewBag.NextPage = i + 1;

                        break;
                    }
                }

                var sermonById = this.Repo.FindOneById<Sermon>(this.Context.Sermons, id);

                return View(sermonById);
            }

            Sermon sermon = new Sermon();

            try
            {
                sermon = this.Repo.FindAll<Sermon>(this.Context.Sermons).OrderByDescending(s => s.Date).Skip(page).FirstOrDefault();

                if (sermon == null)
                {
                    sermon = this.Repo.FindAll<Sermon>(this.Context.Sermons).OrderByDescending(s => s.Date).FirstOrDefault();
                    this.ViewBag.NextPage = 1;
                    this.ViewBag.PrevPage = -1;
                }
            }
            catch (System.Exception)
            {

            }

            return View(sermon);
        }

        public ActionResult Breviary(int page = 0, string id = null)
        {
            if (page < 0)
            {
                page = 0;
            }

            this.ViewBag.PrevPage = page - 1;
            this.ViewBag.NextPage = page + 1;

            long prayersCount = this.Context.Prayers.Count();
            this.ViewBag.PrayersCount = prayersCount;

            if (!string.IsNullOrEmpty(id))
            {
                var ids = this.Repo.FindAll(this.Context.Prayers).SetFields(new string[] { "_id" }).Reverse().ToList();

                for (int i = 0; i < ids.Count; i++)
                {
                    if (ids[i].Id == id)
                    {
                        this.ViewBag.PrevPage = i - 1;
                        this.ViewBag.NextPage = i + 1;

                        break;
                    }
                }

                var prayerById = this.Repo.FindOneById(this.Context.Prayers, id);

                return View(prayerById);
            }

            Prayer prayer = new Prayer();

            try
            {
                prayer = this.Repo.FindAll(this.Context.Prayers).Reverse().Skip(page).FirstOrDefault();

                if (prayer == null)
                {
                    prayer = this.Repo.FindAll(this.Context.Prayers).Reverse().FirstOrDefault();
                    this.ViewBag.NextPage = 1;
                    this.ViewBag.PrevPage = -1;
                }
            }
            catch (System.Exception)
            {

            }

            return View(prayer);
        }
    }
}


text:
<?php
/*
 * This Module helps in Database Administration For MySQL Currently
 *
 * Author: Bismay Kumar Mohapatra bismay4u@gmail.com on 24/02/2012
 * Author: Kshyana Prava kshyana23@gmail.com on 24/02/2012
 * Version: 1.0
 */
if(!defined('ROOT')) exit('No direct script access allowed');
session_check(true);
user_admin_check(true);

_js(array("dialogs"));

function loadDbConsole($site=null) {
	if($site==null) {
		$site=SITENAME;
	}
	checkUserSiteAccess($site);
	$webPath=getWebPath(__FILE__);
	$rootPath=getRootPath(__FILE__);
	$rand=rand(1000,9999)*10000;
	$InstanceID="DBCONSOLE_$rand";
	$_SESSION[$InstanceID."_SITE"]=$site;

	if($site=="admincp" && $_SESSION["SESS_PRIVILEGE_ID"]<=2) {
		$dbFile=ROOT."config/db.cfg";
	} else {
		$dbFile=ROOT.APPS_FOLDER.$site."/config/db.cfg";
	}
	if(file_exists($dbFile)) {
		LoadConfigFile($dbFile);

		if(!(strlen($GLOBALS['DBCONFIG']["DB_DRIVER"])>0 &&
			strlen($GLOBALS['DBCONFIG']["DB_USER"])>0 &&
			strlen($GLOBALS['DBCONFIG']["DB_PASSWORD"])>0 &&
			strlen($GLOBALS['DBCONFIG']["DB_HOST"])>0 &&
			strlen($GLOBALS['DBCONFIG']["DB_DATABASE"])>0)) {

			dispErrMessage("DB Configuration Is Wrong For Site $site.
Please correct under Configurations>Database","Wrong DB Configuration",203);
			return;
		}

		$con=new Database($GLOBALS['DBCONFIG']["DB_DRIVER"]);
		$a=$con->connect($GLOBALS['DBCONFIG']["DB_USER"],$GLOBALS['DBCONFIG']["DB_PASSWORD"],$GLOBALS['DBCONFIG']["DB_HOST"],$GLOBALS['DBCONFIG']["DB_DATABASE"]);
		if(!$a) {
			dispErrMessage("DB Configuration Is Not Correct For Site $site.
Please correct under Configurations>Database","Wrong DB Configuration",401);
			return;
		}
		$_SESSION[$InstanceID."_CONN"]=$con;
	} else {
		dispErrMessage("DB Configuration Missing For Site $site","Missing DB Configuration",204);
		return;
	}
include "plugins.php";

?>
<link href='<?=$webPath?>style.css' rel='stylesheet' type='text/css' media='all' />

		<?php
			foreach($dbeditplugins as $a=>$b) {
				$pg=$b["page"];
				$title=$b["title"];
				$tips=$b["tips"];
				$icon=$b["icon"];
				echo "<button title='$tips' forpg='#$pg' onclick='showPage(\"#$pg\");'>
$title
</button>";
			}
		?>

	<?php
		foreach($dbeditplugins as $a=>$b) {
			$pg=$b["page"];
			$title=$b["title"];
			$tips=$b["tips"];
			$icon=$b["icon"];
			if($a==0) echo "
";
			else echo "
";
			include "pages/$pg.php";
			echo "
";
		}
	?>

<?php } ?>


text:
package com.eqt.ssc.util;

import org.junit.Test;
import static org.junit.Assert.*;

public class AWSUtilTest {

//	@Test
//	public void testWrap() {
//		String key = "key";
//		String secret = "secret";
//		String id = "id";
//		String packed = "key:secret:id";
//
//		String packAWSCredentials = AWSUtils.packAWSCredentials(key, secret, id);
//
//		assertEquals(packed, packAWSCredentials);
//	}

}


text:
#import "FIRAuthDataResult.h"

@class FIROAuthCredential;

NS_ASSUME_NONNULL_BEGIN

@interface FIRAuthDataResult () <NSSecureCoding>

/** @fn initWithUser:additionalUserInfo:
    @brief Designated initializer.
    @param user The signed in user reference.
    @param additionalUserInfo The additional user info if available.
 */
- (nullable instancetype)initWithUser:(FIRUser *)user
                   additionalUserInfo:(nullable FIRAdditionalUserInfo *)additionalUserInfo;

/** @fn initWithUser:additionalUserInfo:
    @brief Designated initializer.
    @param user The signed in user reference.
    @param additionalUserInfo The additional user info if available.
    @param credential The updated OAuth credential if available.
 */
- (nullable instancetype)initWithUser:(FIRUser *)user
                   additionalUserInfo:(nullable FIRAdditionalUserInfo *)additionalUserInfo
                           credential:(nullable FIROAuthCredential *)credential
    NS_DESIGNATED_INITIALIZER;

@end

NS_ASSUME_NONNULL_END


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Buellia calciseda Erichsen

### Remarks
null


text:
package me.lachlanap.balloonbox.core.screen.eol;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import java.text.NumberFormat;
import java.util.LinkedHashMap;
import java.util.Map;
import me.lachlanap.balloonbox.core.level.EndOfLevelInfo;
import me.lachlanap.balloonbox.core.messaging.MessageBus;
import me.lachlanap.balloonbox.core.screen.AbstractScreen;

/**
 *
 * @author lachlan
 */
public class EndOfLevelScreen extends AbstractScreen {

    private static final int P_X = 540;
    private static final int P_Y = 470;
    private final String levelName;
    private final boolean won;
    private final Map<String, String> data = new LinkedHashMap<>();

    public EndOfLevelScreen(MessageBus messageBus, EndOfLevelInfo info) {
        super(messageBus);

        levelName = info.levelName;
        won = info.lives > 0;

        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(2);

        if (info.lives > 0) {
            data.put("Time", nf.format(info.timeSpent) + " seconds");
            data.put("Balloons", nf.format(info.balloons));
            data.put("Lives Left", nf.format(info.lives));
        } else {
            data.put("You", "Failed");
            data.put("Time", nf.format(info.timeSpent) + " seconds");
            data.put("Balloons", nf.format(info.balloons));
        }
    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(1, 1, 1, 0);
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

        batch.begin();
        fontBig.setColor(Color.BLACK);
        fontBig.drawMultiLine(batch, levelName,
                              P_X, P_Y + 20,
                              0, BitmapFont.HAlignment.CENTER);

        int i = 1;
        for (String key : data.keySet()) {
            fontBig.drawMultiLine(batch, key + ":",
                                  P_X - 10, P_Y - i * fontBig.getLineHeight(),
                                  0, BitmapFont.HAlignment.RIGHT);
            i++;
        }

        fontBig.setColor(Color.RED);
        i = 1;
        for (String value : data.values()) {
            fontBig.drawMultiLine(batch, value,
                                  P_X + 10, P_Y - i * fontBig.getLineHeight(),
                                  0, BitmapFont.HAlignment.LEFT);
            i++;
        }

        batch.end();
    }

    @Override
    public boolean touchUp(int screenX, int screenY, int pointer, int button) {
        if (button != Input.Buttons.LEFT)
            return true;

        if (screenX < 540) {
            if (won)
                gotoNextMap();
            else
                gotoSameMap();
        } else
            gotoMainMenu();

        return true;
    }

    private void gotoNextMap() {
        messageBus.nextLevel();
    }

    private void gotoSameMap() {
        messageBus.restartLevel();
    }

    private void gotoMainMenu() {
        messageBus.exitLevel();
    }
}


text:
void HS_Win32Security_LocalFreeFinaliser(void* p) {
  LocalFree(p);
}

void HS_Win32Security_CloseHandleFinaliser(HANDLE h) {
  CloseHandle(h);
}


text:
window.Loader = {};
Loader.load = function(imagePaths){

	// When all images loaded, call dat callback
	var assetsToLoad = imagePaths.length;
	var _onAssetLoad = function(){
		assetsToLoad--;
		if(assetsToLoad==0){
			Loader.onload();
		}
	};

	// Load 'em all
	for(var i=0;i<imagePaths.length;i++){
		var img = new Image();
		img.onload = _onAssetLoad;
		img.src = imagePaths[i];
	}

};


text:
module Mysql
  module Helpers
    module FreeBSD
      def base_dir
        base_dir = '/usr/local'
        base_dir
      end

      def include_dir
        include_dir = '/usr/local/etc/mysql/conf.d'
        include_dir
      end

      def my_cnf
        my_cnf = '/usr/local/etc/my.cnf'
        my_cnf
      end

      def pid_file
        pid_file = '/var/db/mysql/mysqld.pid'
        pid_file
      end

      def prefix_dir
        prefix_dir = '/usr/local'
        prefix_dir
      end

      def rc_name
        rc_name = 'mysql-server'
        rc_name
      end

      def run_dir
        run_dir = '/var/run/mysqld'
        run_dir
      end

      def pass_string
        if new_resource.parsed_server_root_password.empty?
          pass_string = ''
        else
          pass_string = '-p' + Shellwords.escape(new_resource.parsed_server_root_password)
        end

        pass_string = '-p' + ::File.open('/etc/.mysql_root').read.chomp if ::File.exist?('/etc/.mysql_root')
        pass_string
      end

      def socket_file
        socket_file = '/tmp/mysqld.sock'
        socket_file
      end
    end
  end
end


text: xd-shell --cmdfile stream-destroy.xd


text:
require 'fastlane_core'
require 'credentials_manager'

module Produce
  class Options
    def self.available_options
      user = CredentialsManager::AppfileConfig.try_fetch_value(:apple_dev_portal_id)
      user ||= CredentialsManager::AppfileConfig.try_fetch_value(:apple_id)

      [
        FastlaneCore::ConfigItem.new(key: :username,
                                     short_option: "-u",
                                     env_name: "PRODUCE_USERNAME",
                                     description: "Your Apple ID Username",
                                     default_value: user),
        FastlaneCore::ConfigItem.new(key: :app_identifier,
                                     env_name: "PRODUCE_APP_IDENTIFIER",
                                     short_option: "-a",
                                     description: "App Identifier (Bundle ID, e.g. com.krausefx.app)",
                                     default_value: CredentialsManager::AppfileConfig.try_fetch_value(:app_identifier)),
        FastlaneCore::ConfigItem.new(key: :bundle_identifier_suffix,
                                     short_option: "-e",
                                     env_name: "PRODUCE_APP_IDENTIFIER_SUFFIX",
                                     optional: true,
                                     description: "App Identifier Suffix (Ignored if App Identifier does not ends with .*)"),
        FastlaneCore::ConfigItem.new(key: :app_name,
                                     env_name: "PRODUCE_APP_NAME",
                                     short_option: "-q",
                                     description: "App Name"),
        FastlaneCore::ConfigItem.new(key: :app_version,
                                     short_option: "-z",
                                     optional: true,
                                     env_name: "PRODUCE_VERSION",
                                     description: "Initial version number (e.g. '1.0')"),
        FastlaneCore::ConfigItem.new(key: :sku,
                                     env_name: "PRODUCE_SKU",
                                     short_option: "-y",
                                     description: "SKU Number (e.g. '1234')",
                                     default_value: Time.now.to_i.to_s,
                                     is_string: true),
        FastlaneCore::ConfigItem.new(key: :language,
                                     short_option: "-m",
                                     env_name: "PRODUCE_LANGUAGE",
                                     description: "Primary Language (e.g. 'English', 'German')",
                                     default_value: "English",
                                     verify_block: proc do |language|
                                     end),
        FastlaneCore::ConfigItem.new(key: :company_name,
                                     short_option: "-c",
                                     env_name: "PRODUCE_COMPANY_NAME",
                                     description: "The name of your company. Only required if it's the first app you create",
                                     optional: true),
        FastlaneCore::ConfigItem.new(key: :skip_itc,
                                     short_option: "-i",
                                     env_name: "PRODUCE_SKIP_ITC",
                                     description: "Skip the creation of the app on iTunes Connect",
                                     is_string: false,
                                     default_value: false),
        FastlaneCore::ConfigItem.new(key: :skip_devcenter,
                                     short_option: "-d",
                                     env_name: "PRODUCE_SKIP_DEVCENTER",
                                     description: "Skip the creation of the app on the Apple Developer Portal",
                                     is_string: false,
                                     default_value: false),
        FastlaneCore::ConfigItem.new(key: :team_id,
                                     short_option: "-b",
                                     env_name: "PRODUCE_TEAM_ID",
                                     description: "The ID of your Developer Portal team if you're in multiple teams",
                                     optional: true,
                                     default_value: CredentialsManager::AppfileConfig.try_fetch_value(:team_id),
                                     verify_block: proc do |value|
                                       ENV["FASTLANE_TEAM_ID"] = value.to_s
                                     end),
        FastlaneCore::ConfigItem.new(key: :team_name,
                                     short_option: "-l",
                                     env_name: "PRODUCE_TEAM_NAME",
                                     description: "The name of your Developer Portal team if you're in multiple teams",
                                     optional: true,
                                     default_value: CredentialsManager::AppfileConfig.try_fetch_value(:team_name),
                                     verify_block: proc do |value|
                                       ENV["FASTLANE_TEAM_NAME"] = value.to_s
                                     end),
        FastlaneCore::ConfigItem.new(key: :itc_team_id,
                                     short_option: "-k",
                                     env_name: "PRODUCE_ITC_TEAM_ID",
                                     description: "The ID of your iTunes Connect team if you're in multiple teams",
                                     optional: true,
                                     is_string: false, # as we also allow integers, which we convert to strings anyway
                                     default_value: CredentialsManager::AppfileConfig.try_fetch_value(:itc_team_id),
                                     verify_block: proc do |value|
                                       ENV["FASTLANE_ITC_TEAM_ID"] = value.to_s
                                     end),
        FastlaneCore::ConfigItem.new(key: :itc_team_name,
                                     short_option: "-p",
                                     env_name: "PRODUCE_ITC_TEAM_NAME",
                                     description: "The name of your iTunes Connect team if you're in multiple teams",
                                     optional: true,
                                     default_value: CredentialsManager::AppfileConfig.try_fetch_value(:itc_team_name),
                                     verify_block: proc do |value|
                                       ENV["FASTLANE_ITC_TEAM_NAME"] = value.to_s
                                     end)
      ]
    end
  end
end


text:
suite('ParentNodeInterface', function() {

  test('childElementCount', function() {
    var div = document.createElement('div');
    div.innerHTML = 'ac';
    assert.equal(div.childElementCount, 1);
    div.appendChild(document.createElement('d'));
    assert.equal(div.childElementCount, 2);
    div.appendChild(document.createTextNode('e'));
    assert.equal(div.childElementCount, 2);

    var sr = div.createShadowRoot();
    sr.innerHTML = 'f<content></content>g';

    div.offsetHeight;  // trigger rendering

    assert.equal(sr.childElementCount, 1);
    assert.equal(div.childElementCount, 2);
  });

  test('children', function() {
    var div = document.createElement('div');
    div.innerHTML = 'ac';
    var b = div.firstChild.nextSibling;

    assertArrayEqual(div.children, [b]);
    var d = div.appendChild(document.createElement('d'));
    assertArrayEqual(div.children, [b, d]);
    div.appendChild(document.createTextNode('e'));
    assertArrayEqual(div.children, [b, d]);

    var sr = div.createShadowRoot();
    sr.innerHTML = 'f<content></content>g';
    var content = sr.firstChild.nextSibling;

    div.offsetHeight;  // trigger rendering

    assertArrayEqual(sr.children, [content]);
    assertArrayEqual(div.children, [b, d]);
  });

  test('firstElementChild', function() {
    var div = document.createElement('div');
    div.innerHTML = 'ac';
    var b = div.firstChild.nextSibling;

    assert.equal(div.firstElementChild, b);

    var sr = div.createShadowRoot();
    sr.innerHTML = 'f<content></content>g';
    var content = sr.firstChild.nextSibling;

    div.offsetHeight;  // trigger rendering

    assert.equal(sr.firstElementChild, content);
    assert.equal(div.firstElementChild, b);
  });

  test('lastElementChild', function() {
    var div = document.createElement('div');
    div.innerHTML = 'ac';
    var b = div.firstChild.nextSibling;

    assert.equal(div.lastElementChild, b);

    var sr = div.createShadowRoot();
    sr.innerHTML = 'f<content></content>g';
    var content = sr.firstChild.nextSibling;

    div.offsetHeight;  // trigger rendering

    assert.equal(sr.lastElementChild, content);
    assert.equal(div.lastElementChild, b);
  });

});


text:
import { tags } from '@angular-devkit/core';
import { SchematicsException } from '@angular-devkit/schematics';

// Must start with a letter, and must contain only alphanumeric characters or dashes.
// When adding a dash the segment after the dash must also start with a letter.
export const htmlSelectorRe = /^[a-zA-Z][.0-9a-zA-Z]*(:?-[a-zA-Z][.0-9a-zA-Z]*)*$/;

export function validateHtmlSelector(selector: string): void {
  if (selector && !htmlSelectorRe.test(selector)) {
    throw new SchematicsException(tags.oneLine`Selector (${selector})
        is invalid.`);
  }
}


text:
/**
 * @file resize
 *
 * @author 天翔Skyline(skyline0705@gmail.com)
 * 10 May 2017
 */

import {raf, caf, getAnimationEventName} from '@/common/util';
import {prefix, needPrefix} from '@/common/config';

const animationName = 'platform-ui-resize';
const keyFramePrefix = needPrefix ? `-${prefix}-` : '';

function resetTrigger(trigger) {
    const expand = trigger.firstElementChild;
    const contract = trigger.lastElementChild;
    const expandChild = expand.firstElementChild;

    contract.scrollLeft = contract.scrollWidth;
    contract.scrollTop = contract.scrollHeight;
    expandChild.style.width = expand.offsetWidth + 1 + 'px';
    expandChild.style.height = expand.offsetHeight + 1 + 'px';
    expand.scrollLeft = expand.scrollWidth;
    expand.scrollTop = expand.scrollHeight;
}

function createAnimationStyle() {
    const animationKeyframes = `
        @${keyFramePrefix}keyframes ${animationName} {
            from {
                opacity: 0;
            }
            to {
                opacity: 0;
            }
        }`;
    const animationStyle = `${keyFramePrefix}animation: 1ms ${animationName};`;
    return {animationKeyframes, animationStyle};
}

function createResizeStyle() {
    if (document.getElementById('platform-ui-resize-triggers')) {
        return;
    }
    const {animationKeyframes, animationStyle} = createAnimationStyle();
    // Chrome的bug,地址:https://code.google.com/p/chromium/issues/detail?id=286360
    const css = `
        ${animationKeyframes}
        .resize-triggers {
            visibility: hidden; opacity: 0;
            ${animationStyle}
        }
        .resize-triggers,
        .resize-triggers > div,
        .contract-trigger:before {
            display: block;
            position: absolute;
            top: 0;
            left: 0;
            z-index: -1;
            height: 100%;
            width: 100%;
            overflow: hidden;
            z-index: -1;
        }
        .resize-triggers > div {
            background: #eee;
            overflow: auto;
        }
        .contract-trigger:before {
            content: '';
            width: 200%;
            height: 200%;
        }`;

    const head = document.getElementsByTagName('head')[0];
    const style = document.createElement('style');

    style.type = 'text/css';
    if (style.styleSheet) {
        style.styleSheet.cssText = css;
    } else {
        style.appendChild(document.createTextNode(css));
    }
    style.id = 'platform-ui-resize-triggers';

    head.appendChild(style);
}

function generateResizeTrigger() {
    const trigger = document.createElement('div');
    trigger.className = 'resize-triggers';
    trigger.innerHTML = `

    `;
    return trigger;
}

function checkTrigger(element) {
    /* eslint-disable no-underscore-dangle */
    return element.offsetWidth !== element.__resizeOldRect.width
        || element.offsetHeight !== element.__resizeOldRect.height;
}

function scroll(event) {
    /* eslint-disable no-underscore-dangle */
    resetTrigger(this.__resizeTrigger);
    if (this.__resizeRAFId) {
        caf(this.__resizeRAFId);
    }
    this.__resizeRAFId = raf(() => {
        if (checkTrigger(this)) {
            this.__resizeOldRect.width = this.offsetWidth;
            this.__resizeOldRect.height = this.offsetHeight;
            this.__resizeListener.forEach(fn => {
                fn.call(this, event);
            });
        }
    });
}

function animation(event) {
    if (event.animationName === animationName) {
        resetTrigger(this);
    }
}

const animationStart = getAnimationEventName('animationstart');
export default {
    bind(el, {value}) {
        createResizeStyle();
        if (getComputedStyle(el).position === 'static') {
            el.style.position = 'relative';
        }
        /* eslint-disable no-underscore-dangle */
        el.__resizeTrigger = generateResizeTrigger();
        el.__resizeListener = el.__resizeListener || [];
        el.__resizeListener.push(value);
        el.appendChild(el.__resizeTrigger);
        resetTrigger(el.__resizeTrigger);
        el.__resizeOldRect = {
            width: el.offsetWidth,
            height: el.offsetHeight
        };
        el.addEventListener('scroll', scroll, true);
        // 动画触发resetTrigger,保证滚动监听正常
        el.__resizeTrigger.addEventListener(animationStart, animation);
    },
    unbind(el, {value}) {
        el.removeEventListener('scroll', scroll);
        el.__resizeTrigger.removeEventListener(animationStart, animation);
        /* eslint-disable no-underscore-dangle */
        const index = el.__resizeListener.indexOf(value);
        el.__resizeListener.splice(index, 1);
        if (!el.__resizeListener.length) {
            el.__resizeListener = null;
        }
        el.removeChild(el.__resizeTrigger);
        el.__resizeTrigger = null;
        el.__resizeOldRect = null;
    }
};


text:
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (IBAction)selectOwner:(UIButton *)sender {
    DLPickerView *pickerView = [[DLPickerView alloc] initWithDataSource:@[@[@"Bei Jing",@"Shang Hai"], @[@"Li Lei",@"Han Meimei"]]
                                                       withSelectedItem:[sender.titleLabel.text componentsSeparatedByString:OwnerSeparator]
                                                      withSelectedBlock:^(id selectedItem) {
                                                          [sender setTitle:[selectedItem componentsJoinedByString:OwnerSeparator] forState:UIControlStateNormal];
                                                      }
                                ];

    pickerView.shouldDismissWhenClickShadow = YES;

    [pickerView show];
}

- (IBAction)selectOwnerGender:(UIButton *)sender {
    DLPickerView *pickerView = [[DLPickerView alloc] initWithDataSource:@[@"Man",@"Woman"]
                                                       withSelectedItem:sender.titleLabel.text
                                                      withSelectedBlock:^(id selectedItem) {
                                                          [sender setTitle:selectedItem forState:UIControlStateNormal];
                                                      }
                                ];

    [pickerView show];
}

- (IBAction)selectTime:(UIButton *)sender {
    DLPickerView *pickerView = [[DLPickerView alloc] initWithPlistName:@"Time"
                                                      withSelectedItem:[sender.titleLabel.text componentsSeparatedByString:TimeSeparator]
                                                     withSelectedBlock:^(id selectedItem) {
                                                         [sender setTitle:[selectedItem componentsJoinedByString:TimeSeparator] forState:UIControlStateNormal];
                                                     }
                                ];

    [pickerView show];
}

@end


text:
/*
 * ReferenceData.h
 *
 *  Created on: March 10, 2010
 *      Author: lawrence.daniels@gmail.com
 */

#ifndef CLASSDATA_H_
#define CLASSDATA_H_

#include "../CodeBuffer.h"

/**
 * Represents a unit of reference data, and is used to
 * refer to fields, methods, and classes by name.
 */
class ReferenceData {
private:
	OFFSET_T codeOffset;
	OFFSET_T dataOffset;
	const char* content;
	int referenceId;

public:

	/**
	 * Constructor
	 */
	ReferenceData( int referenceId, const char* content, OFFSET_T codeOffset = 0 );

	/**
	 * Destruction
	 */
	virtual ~ReferenceData();

	/**
	 * Adds the given data to the class
	 * @param data the class data
	 */
	void addData( ReferenceData* );

	/**
	 * Compiles the class into byte code
	 */
	int compile( CodeBuffer*, OFFSET_T );

	/**
	 * Decompiles the class from byte code
	 */
	static ReferenceData* decompile( CodeBuffer* );

	/**
	 * Returns the contents of the data
	 */
	const char* getContent();

	/**
	 * Returns the memory offset of the code reference
	 */
	OFFSET_T getCodeOffset();

	/**
	 * Sets the memory offset of the data
	 */
	void setCodeOffset( OFFSET_T );

	/**
	 * Returns the memory offset of the data
	 */
	OFFSET_T getDataOffset();

	/**
	 * Sets the memory offset of the data
	 */
	void setDataOffset( OFFSET_T );

	/**
	 * Returns the reference identifier
	 */
	int getReferenceId();

	/**
	 * Sets the reference identifier
	 */
	void setReferenceId( int );

};

#endif /* CLASSDATA_H_ */


text:
/**
 * @author Sergey Burlak
 */
package javax.swing.plaf.basic;

import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.io.StringBufferInputStream;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.TransferHandler;
import javax.swing.UIManager;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileSystemView;
import javax.swing.filechooser.FileView;
import javax.swing.plaf.FileChooserUI;

import org.apache.harmony.x.swing.StringConstants;
import org.apache.harmony.x.swing.Utilities;

public class BasicFileChooserUI extends FileChooserUI {

    protected class AcceptAllFileFilter extends FileFilter {
        public AcceptAllFileFilter() {
        }

        public boolean accept(final File f) {
            return true;
        }
        public String getDescription() {
            return UIManager.getString("FileChooser.acceptAllFileFilterText");
        }
    }

    protected class BasicFileView extends FileView {
        protected Hashtable<java.io.File, javax.swing.Icon> iconCache = new Hashtable<java.io.File, javax.swing.Icon>();

        public BasicFileView() {
        }

        public void clearIconCache() {
            iconCache.clear();
        }

        public String getName(final File f) {
            return fileChooser.getFileSystemView().getSystemDisplayName(f);
        }

        public String getDescription(final File f) {
            return getName(f);
        }

        public String getTypeDescription(final File f) {
            return fileChooser.getFileSystemView().getSystemTypeDescription(f);
        }

        public Icon getCachedIcon(final File f) {
            return f == null ? null : (Icon)iconCache.get(f);
        }

        public void cacheIcon(final File f, final Icon i) {
            if (f == null || i == null) {
                return;
            }
            iconCache.put(f, i);
        }

        public Icon getIcon(final File f) {
            Icon result = getCachedIcon(f);
            if (result == null) {
                result = getIconForFile(f);
                cacheIcon(f, result);
            }

            return result;
        }

        public Boolean isHidden(final File f) {
            return f.isHidden() ? Boolean.TRUE : Boolean.FALSE;
        }

        private Icon getIconForFile(final File file) {
            FileSystemView view = getFileChooser().getFileSystemView();
            if (file == null) {
                return null;
            } else if (view.isComputerNode(file)) {
                return computerIcon;
            } else if (view.isFloppyDrive(file)) {
                return floppyDriveIcon;
            } else if (view.isDrive(file)) {
                return hardDriveIcon;
            } else if (file.isFile()) {
                return fileIcon;
            } else if (file.isDirectory()) {
                return directoryIcon;
            } else {
                return null;
            }
        }
    }

    protected class ApproveSelectionAction extends AbstractAction {
        protected ApproveSelectionAction() {
            putValue(Action.NAME, approveButtonText);
            putValue(Action.SHORT_DESCRIPTION, approveButtonToolTipText);
            putValue(Action.MNEMONIC_KEY, new Integer(approveButtonMnemonic));
        }

        public void actionPerformed(final ActionEvent e) {
            String fileName = getFileName();
            if (Utilities.isEmptyString(fileName)) {
                return;
            }
            if (fileChooser.isMultiSelectionEnabled()) {
                List selectedFiles = new ArrayList();
                String[] fileNames = splitFileNames(fileName);
                for (int i = 0; i < fileNames.length; i++) {
                    selectedFiles.add(translateFile(fileNames[i]));
                }
                fileChooser.setSelectedFiles((File[])selectedFiles.toArray(new File[selectedFiles.size()]));
            } else {
                fileChooser.setSelectedFile(translateFile(fileName));
            }

            fileChooser.approveSelection();
        }

        private File translateFile(final String fileName) {
            if (Utilities.isEmptyString(fileName)) {
                return null;
            }

            File candidateFile = new File(fileName);
            if (candidateFile.isAbsolute()) {
                return candidateFile;
            }

            if (fileName.startsWith("\"")) {
                String nakedFileName = fileName.endsWith("\"")
                                       ? fileName.substring(1, fileName.length() - 1)
                                       : fileName.substring(1);

                File fileInCurrentDir = fileChooser.getFileSystemView().getChild(fileChooser.getCurrentDirectory(), nakedFileName);
                if (fileInCurrentDir != null
                    && fileInCurrentDir.exists()
                    && fileChooser.getFileSystemView().isFileSystem(fileInCurrentDir)) {

                    return fileInCurrentDir;
                } else {
                    return fileChooser.getFileSystemView().createFileObject(nakedFileName);
                }
            } else {
                return fileChooser.getFileSystemView().createFileObject(fileChooser.getCurrentDirectory(), fileName);
            }
        }

        private String[] splitFileNames(final String fileNames) {
            if (fileNames == null) {
                return new String[0];
            }

            List result = new LinkedList();
            int wordBegin = 0;
            boolean insideWord = false;
            for (int i = 0; i < fileNames.length(); i++) {
                char curChar = fileNames.charAt(i);
                if (Character.isWhitespace(curChar) && !insideWord) {
                    continue;
                }

                if (curChar == '\"') {
                    if (!insideWord) {
                        insideWord = true;
                        wordBegin = i;
                    } else {
                        result.add(fileNames.substring(wordBegin, i + 1));
                        insideWord = false;
                    }
                }
            }
            if (insideWord || result.isEmpty()) {
                return new String[] {fileNames};
            } else {
                return (String[])result.toArray(new String[result.size()]);
            }
        }
    }

    protected class CancelSelectionAction extends AbstractAction {
        protected CancelSelectionAction() {
            putValue(AbstractAction.NAME, cancelButtonText);
            putValue(AbstractAction.SHORT_DESCRIPTION, cancelButtonToolTipText);
        }

        public void actionPerformed(final ActionEvent e) {
            fileChooser.cancelSelection();
        }
    }

    protected class ChangeToParentDirectoryAction extends AbstractAction {
        protected ChangeToParentDirectoryAction() {
            putValue(AbstractAction.NAME, upFolderButtonText);
            putValue(AbstractAction.SHORT_DESCRIPTION, upFolderButtonToolTipText);
            putValue(AbstractAction.SMALL_ICON, upFolderIcon);
        }

        public void actionPerformed(final ActionEvent e) {
            fileChooser.changeToParentDirectory();
        }
    }

    protected class GoHomeAction extends AbstractAction {
        protected GoHomeAction() {
            putValue(AbstractAction.NAME, homeFolderButtonText);
            putValue(AbstractAction.SHORT_DESCRIPTION, homeFolderButtonToolTipText);
            putValue(AbstractAction.SMALL_ICON, homeFolderIcon);
        }

        public void actionPerformed(final ActionEvent e) {
            fileChooser.setCurrentDirectory(fileChooser.getFileSystemView().getHomeDirectory());
        }
    }

    protected class NewFolderAction extends AbstractAction {
        protected NewFolderAction() {
            putValue(AbstractAction.NAME, newFolderButtonText);
            putValue(AbstractAction.SHORT_DESCRIPTION, newFolderButtonToolTipText);
            putValue(AbstractAction.SMALL_ICON, newFolderIcon);
        }

        public void actionPerformed(final ActionEvent e) {
            try {
                File newFolder = fileChooser.getFileSystemView().createNewFolder(fileChooser.getCurrentDirectory());
                fileChooser.rescanCurrentDirectory();
                fileChooser.setSelectedFile(newFolder);
            } catch (IOException ioe) {
            }
        }
    }

    protected class UpdateAction extends AbstractAction {
        protected UpdateAction() {
            putValue(AbstractAction.NAME, updateButtonText);
            putValue(AbstractAction.SHORT_DESCRIPTION, updateButtonToolTipText);
        }

        public void actionPerformed(final ActionEvent e) {
            fileChooser.rescanCurrentDirectory();
        }
    }

    protected class DoubleClickListener extends MouseAdapter {
        private JList list;

        public DoubleClickListener(final JList list) {
            this.list = list;
        }

        public void mouseClicked(final MouseEvent e) {
            if (e.getButton() != MouseEvent.BUTTON1) {
                return;
            }

            if (e.getClickCount() != 2) {
                return;
            }
            File file = (File)list.getSelectedValue();
            if (file != null && file.isDirectory()) {
                getFileChooser().setCurrentDirectory(file);
                return;
            }

            approveSelectionAction.actionPerformed(null);
        }
    }

    //Never used by Metal L&F
    protected class SelectionListener implements ListSelectionListener {
        public void valueChanged(final ListSelectionEvent e) {
        }
    }

    private class PropertyChangeHandler implements PropertyChangeListener {
        public void propertyChange(final PropertyChangeEvent event) {
            String changedProperty = event.getPropertyName();
            if (JFileChooser.DIALOG_TYPE_CHANGED_PROPERTY.equals(changedProperty)) {
                final int type = ((Integer)event.getNewValue()).intValue();
                setButtonsAttrs(type);
            } else if (JFileChooser.DIALOG_TITLE_CHANGED_PROPERTY.equals(changedProperty)) {
                dialogTitleText = (String)event.getNewValue();
            } else if (JFileChooser.APPROVE_BUTTON_TEXT_CHANGED_PROPERTY.equals(changedProperty)) {
                if (event.getNewValue() == null) {
                    setButtonsAttrs(fileChooser.getDialogType());
                } else {
                    approveButtonText = (String)event.getNewValue();
                }
            } else if (StringConstants.COMPONENT_ORIENTATION.equals(changedProperty)) {
                ComponentOrientation co = (ComponentOrientation)event.getNewValue();
                fileChooser.applyComponentOrientation(co);
            }
        }
    }

    // TODO: file flavor should also be supported
    private class FileChooserTransferHandler extends TransferHandler {
        private final String lineSeparator = System.getProperty("line.separator");

        public int getSourceActions(final JComponent c) {
            return COPY;
        }

        protected Transferable createTransferable(final JComponent c) {
            File[] selectedFiles;
            if (fileChooser.isMultiSelectionEnabled()) {
                selectedFiles = fileChooser.getSelectedFiles();
            } else {
                selectedFiles = fileChooser.getSelectedFile() != null
                                ? new File[] {fileChooser.getSelectedFile()}
                                : null;
            }

            if (selectedFiles == null || selectedFiles.length == 0) {
                if (isDirectorySelected()) {
                    selectedFiles = new File[] {getDirectory()};
                } else {
                    return null;
                }
            }

            final File[] transferingFiles = selectedFiles;
            return new Transferable() {
                public Object getTransferData(final DataFlavor flavor) throws UnsupportedFlavorException, IOException {
                    if (flavor.equals(DataFlavor.stringFlavor)
                        || flavor.equals(DataFlavor.plainTextFlavor)) {

                        StringBuilder content = new StringBuilder();
                        for (int i = 0; i < transferingFiles.length; i++) {
                            content.append(transferingFiles[i].getAbsolutePath());
                            if (i < transferingFiles.length - 1) {
                                content.append(lineSeparator);
                            }
                        }

                        return flavor.equals(DataFlavor.stringFlavor) ? (Object)content.toString()
                                                                      : new StringBufferInputStream(content.toString());
                    }

                    throw new UnsupportedFlavorException(flavor);
                }

                public boolean isDataFlavorSupported(final DataFlavor flavor) {
                    return flavor.equals(DataFlavor.stringFlavor)
                           || flavor.equals(DataFlavor.plainTextFlavor);
                }

                public DataFlavor[] getTransferDataFlavors() {
                    return new DataFlavor[] {DataFlavor.stringFlavor, DataFlavor.plainTextFlavor};
                }
            };
        }
    }

    protected Icon directoryIcon;
    protected Icon fileIcon;
    protected Icon computerIcon;
    protected Icon hardDriveIcon;
    protected Icon floppyDriveIcon;
    protected Icon newFolderIcon;
    protected Icon upFolderIcon;
    protected Icon homeFolderIcon;
    protected Icon listViewIcon;
    protected Icon detailsViewIcon;
    protected int saveButtonMnemonic;
    protected int openButtonMnemonic;
    protected int cancelButtonMnemonic;
    protected int updateButtonMnemonic;
    protected int helpButtonMnemonic;
    protected int directoryOpenButtonMnemonic;
    protected String saveButtonText;
    protected String openButtonText;
    protected String cancelButtonText;
    protected String updateButtonText;
    protected String helpButtonText;
    protected String directoryOpenButtonText;
    protected String saveButtonToolTipText;
    protected String openButtonToolTipText;
    protected String cancelButtonToolTipText;
    protected String updateButtonToolTipText;
    protected String helpButtonToolTipText;
    protected String directoryOpenButtonToolTipText;
    private String newFolderButtonText;
    private String newFolderButtonToolTipText;
    private String upFolderButtonText;
    private String upFolderButtonToolTipText;
    private String homeFolderButtonText;
    private String homeFolderButtonToolTipText;

    private JFileChooser fileChooser;
    private BasicDirectoryModel model;
    private FileView fileView;
    private JPanel accessoryPanel;

    private String openDialogTitleText;
    private String saveDialogTitleText;

    private String dialogTitleText;
    private String approveButtonText;
    private String approveButtonToolTipText;
    private int approveButtonMnemonic;
    private boolean isDirectorySelected;

    private PropertyChangeListener propertyChangeHandler;
    private AcceptAllFileFilter acceptAllFileFilter = new AcceptAllFileFilter();
    private String fileName;
    private File directory;

    private Action approveSelectionAction;
    private Action updateAction;
    private Action cancelSelectionAction;
    private Action changeToParentDirAction;
    private Action goHomeAction;
    private Action newFolderAction;

    public BasicFileChooserUI(final JFileChooser fc) {
        this.fileChooser = fc;
    }

    public void installUI(final JComponent c) {
        fileChooser = (JFileChooser)c;

        fileView = new BasicFileView();
        createModel();

        installDefaults(fileChooser);
        installIcons(fileChooser);
        installStrings(fileChooser);
        installComponents(fileChooser);
        installListeners(fileChooser);

        fileChooser.setTransferHandler(new FileChooserTransferHandler());
    }

    public void uninstallUI(final JComponent c) {
        uninstallListeners(fileChooser);
        uninstallComponents(fileChooser);
        uninstallDefaults(fileChooser);
        uninstallIcons(fileChooser);
        uninstallStrings(fileChooser);
        model = null;
        accessoryPanel = null;
    }

    public void installComponents(final JFileChooser fc) {
        accessoryPanel = new JPanel(new BorderLayout());

        approveSelectionAction = new ApproveSelectionAction();
        updateAction = new UpdateAction();
        cancelSelectionAction = new CancelSelectionAction();
        changeToParentDirAction = new ChangeToParentDirectoryAction();
        goHomeAction = new GoHomeAction();
        newFolderAction = new NewFolderAction();
    }

    public void uninstallComponents(final JFileChooser fc) {
        accessoryPanel = null;
    }

    protected void installListeners(final JFileChooser fc) {
        propertyChangeHandler = new PropertyChangeHandler();
        fileChooser.addPropertyChangeListener(propertyChangeHandler);

        Utilities.installKeyboardActions(fc, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, "FileChooser.ancestorInputMap", null);
        fc.getActionMap().put("cancelSelection", cancelSelectionAction);
    }

    protected void uninstallListeners(final JFileChooser fc) {
        fileChooser.removePropertyChangeListener(propertyChangeHandler);

        Utilities.uninstallKeyboardActions(fc, JComponent.WHEN_IN_FOCUSED_WINDOW);
    }

    protected void installDefaults(final JFileChooser fc) {
        if (fc == null) {
            throw new NullPointerException();
        }

        helpButtonMnemonic = UIManager.getInt("FileChooser.helpButtonMnemonic");
        directoryOpenButtonMnemonic = UIManager.getInt("FileChooser.directoryOpenButtonMnemonic");

        openDialogTitleText = UIManager.getString("FileChooser.openDialogTitleText");
        saveDialogTitleText = UIManager.getString("FileChooser.saveDialogTitleText");
    }

    protected void installIcons(final JFileChooser fc) {
        directoryIcon = UIManager.getIcon("FileView.directoryIcon");
        fileIcon = UIManager.getIcon("FileView.fileIcon");
        computerIcon = UIManager.getIcon("FileView.computerIcon");
        hardDriveIcon = UIManager.getIcon("FileView.hardDriveIcon");
        floppyDriveIcon = UIManager.getIcon("FileView.floppyDriveIcon");
        newFolderIcon = UIManager.getIcon("FileChooser.newFolderIcon");
        upFolderIcon = UIManager.getIcon("FileChooser.upFolderIcon");
        homeFolderIcon = UIManager.getIcon("FileChooser.homeFolderIcon");
        listViewIcon = UIManager.getIcon("FileChooser.listViewIcon");
        detailsViewIcon = UIManager.getIcon("FileChooser.detailsViewIcon");

        clearIconCache();

    }

    protected void installStrings(final JFileChooser fc) {
        saveButtonText = UIManager.getString("FileChooser.saveButtonText");
        openButtonText = UIManager.getString("FileChooser.openButtonText");
        cancelButtonText = UIManager.getString("FileChooser.cancelButtonText");
        updateButtonText = UIManager.getString("FileChooser.updateButtonText");
        helpButtonText = UIManager.getString("FileChooser.helpButtonText");
        directoryOpenButtonText = UIManager.getString("FileChooser.directoryOpenButtonText");
        newFolderButtonText = UIManager.getString("FileChooser.newFolderAccessibleName");
        upFolderButtonText = UIManager.getString("FileChooser.upFolderAccessibleName");
        homeFolderButtonText = UIManager.getString("FileChooser.homeFolderAccessibleName");

        saveButtonToolTipText = UIManager.getString("FileChooser.saveButtonToolTipText");
        openButtonToolTipText = UIManager.getString("FileChooser.openButtonToolTipText");
        cancelButtonToolTipText = UIManager.getString("FileChooser.cancelButtonToolTipText");
        updateButtonToolTipText = UIManager.getString("FileChooser.updateButtonToolTipText");
        helpButtonToolTipText = UIManager.getString("FileChooser.helpButtonToolTipText");
        directoryOpenButtonToolTipText = UIManager.getString("FileChooser.directoryOpenButtonToolTipText");
        newFolderButtonToolTipText = UIManager.getString("FileChooser.newFolderToolTipText");
        upFolderButtonToolTipText = UIManager.getString("FileChooser.upFolderToolTipText");
        homeFolderButtonToolTipText = UIManager.getString("FileChooser.homeFolderToolTipText");

        setButtonsAttrs(fileChooser.getDialogType());
    }

    protected void uninstallDefaults(final JFileChooser fc) {
        fileChooser.setTransferHandler(null);
    }

    protected void uninstallIcons(final JFileChooser fc) {
        clearIconCache();
    }

    protected void uninstallStrings(final JFileChooser fc) {
    }

    protected void createModel() {
        model = new BasicDirectoryModel(fileChooser);
    }

    public BasicDirectoryModel getModel() {
        return model;
    }

    public PropertyChangeListener createPropertyChangeListener(final JFileChooser fc) {
        return null;
    }

    public String getFileName() {
        return fileName;
    }

    public String getDirectoryName() {
        return null;
    }

    public void setFileName(final String filename) {
        fileName = filename;
    }

    public void setDirectoryName(final String dirname) {
    }

    public void rescanCurrentDirectory(final JFileChooser fc) {
    }

    public void ensureFileIsVisible(final JFileChooser fc, final File f) {
        if (fileChooser != null) {
            fileChooser.ensureFileIsVisible(f);
        }
    }

    public JFileChooser getFileChooser() {
        return fileChooser;
    }

    public JPanel getAccessoryPanel() {
        return accessoryPanel;
    }

    public void clearIconCache() {
        if (fileView instanceof BasicFileView) {
            ((BasicFileView)fileView).clearIconCache();
        }
    }

    protected MouseListener createDoubleClickListener(final JFileChooser fc, final JList list) {
        return new DoubleClickListener(list);
    }

    public ListSelectionListener createListSelectionListener(final JFileChooser fc) {
        return new SelectionListener();
    }

    protected boolean isDirectorySelected() {
        return isDirectorySelected;
    }

    protected void setDirectorySelected(final boolean b) {
        isDirectorySelected = b;
    }

    protected File getDirectory() {
        return directory;
    }

    protected void setDirectory(final File f) {
        directory = f;
    }

    public FileFilter getAcceptAllFileFilter(final JFileChooser fc) {
        return acceptAllFileFilter;
    }

    public FileView getFileView(final JFileChooser fc) {
        return fileView;
    }

    public String getDialogTitle(final JFileChooser fc) {
        return dialogTitleText;
    }

    protected JButton getApproveButton(final JFileChooser fc) {
        return null;
    }

    public String getApproveButtonToolTipText(final JFileChooser fc) {
	if (fc == null) {
            throw new NullPointerException();
        }

        return approveButtonToolTipText;
    }

    public int getApproveButtonMnemonic(final JFileChooser fc) {
        return approveButtonMnemonic;
    }

    public String getApproveButtonText(final JFileChooser fc) {
        return approveButtonText;
    }

    public Action getNewFolderAction() {
        return newFolderAction;
    }

    public Action getGoHomeAction() {
        return goHomeAction;
    }

    public Action getChangeToParentDirectoryAction() {
        return changeToParentDirAction;
    }

    public Action getApproveSelectionAction() {
        return approveSelectionAction;
    }

    public Action getCancelSelectionAction() {
        return cancelSelectionAction;
    }

    public Action getUpdateAction() {
        return updateAction;
    }

    private void setButtonsAttrs(final int type) {
        if (type == JFileChooser.OPEN_DIALOG) {
            dialogTitleText = openDialogTitleText;
            approveButtonText = openButtonText;
            approveButtonToolTipText = openButtonToolTipText;
        } else if (type == JFileChooser.SAVE_DIALOG) {
            dialogTitleText = saveDialogTitleText;
            approveButtonText = saveButtonText;
            approveButtonToolTipText = saveButtonToolTipText;
        } else {
            dialogTitleText = null;
            approveButtonText = fileChooser.getApproveButtonText();
            approveButtonToolTipText = null;
            approveButtonMnemonic = 0;
        }

        if (approveSelectionAction != null) {
            approveSelectionAction.putValue(Action.NAME, approveButtonText);
            approveSelectionAction.putValue(Action.SHORT_DESCRIPTION, approveButtonToolTipText);
            approveSelectionAction.putValue(Action.MNEMONIC_KEY, new Integer(approveButtonMnemonic));
        }
    }
}


text:
package net.qiujuer.common.okhttp.impl;

import net.qiujuer.common.okhttp.core.HttpCallback;
import net.qiujuer.genius.kit.handler.Run;
import net.qiujuer.genius.kit.handler.runable.Action;

import okhttp3.Request;
import okhttp3.Response;

/**
 * This callback to call method by UI thread
 */
public abstract class UiCallback<T> extends HttpCallback<T> {
    @Override
    protected void dispatchFailure(final Request request, final Response response, final Exception e) {
        Run.onUiSync(new Action() {
            @Override
            public void call() {
                onFailure(request, response, e);
            }
        });
    }

    @Override
    protected void dispatchSuccess(final T response, final int code) {
        Run.onUiSync(new Action() {
            @Override
            public void call() {
                onSuccess(response, code);
            }
        });
    }

    @Override
    public void dispatchProgress(final long current, final long count) {
        Run.onUiSync(new Action() {
            @Override
            public void call() {
                onProgress(current, count);
            }
        });
    }
}


text:
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.

package com.intellij.codeInsight.preview;

import com.intellij.lang.LangBundle;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFileSystemItem;
import com.intellij.psi.PsiReference;
import com.intellij.reference.SoftReference;
import com.intellij.ui.JBColor;
import com.intellij.ui.scale.JBUIScale;
import com.intellij.ui.scale.ScaleContext;
import com.intellij.util.JBHiDPIScaledImage;
import com.intellij.util.SVGLoader;
import com.intellij.util.ui.ImageUtil;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * @author spleaner
 * @deprecated see {@link PreviewHintProvider} deprecation notice
 */
@Deprecated
public final class ImagePreviewComponent extends JPanel implements PreviewHintComponent {
  private static final Key<Long> TIMESTAMP_KEY = Key.create("Image.timeStamp");
  private static final Key<SoftReference<BufferedImage>> BUFFERED_IMAGE_REF_KEY = Key.create("Image.bufferedImage");

  private static final List<String> supportedExtensions = Arrays.asList(ImageIO.getReaderFormatNames());
  @NotNull
  private final BufferedImage myImage;

  /**
   * @param image buffered image
   * @param imageFileSize File length in bytes.
   */
  private ImagePreviewComponent(@NotNull final BufferedImage image, final long imageFileSize) {
    setLayout(new BorderLayout());

    myImage = (BufferedImage)ImageUtil.ensureHiDPI(image, ScaleContext.create(this));
    add(new ImageComp(), BorderLayout.CENTER);
    add(createLabel(image, imageFileSize), BorderLayout.SOUTH);

    setBackground(UIUtil.getToolTipBackground());
    setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(JBColor.BLACK), BorderFactory.createEmptyBorder(5, 5, 5, 5)));
  }

  @Override
  @TestOnly
  public boolean isEqualTo(@Nullable PreviewHintComponent other) {
    if (!(other instanceof ImagePreviewComponent)) {
      return false;
    }
    ImagePreviewComponent otherPreview = (ImagePreviewComponent)other;

    BufferedImage image1 = myImage instanceof JBHiDPIScaledImage
                           ? (BufferedImage)((JBHiDPIScaledImage)myImage).getDelegate()
                           : myImage;
    BufferedImage image2 = otherPreview.myImage instanceof JBHiDPIScaledImage
                           ? (BufferedImage)((JBHiDPIScaledImage)otherPreview.myImage).getDelegate()
                           : otherPreview.myImage;

    if (image1 == null || image2 == null) return false;
    if (image1.getWidth() != image2.getWidth() || image1.getHeight() != image2.getHeight()) return false;

    for (int x = 0; x < image1.getWidth(); x++) {
      for (int y = 0; y < image1.getHeight(); y++) {
        if (image1.getRGB(x, y) != image2.getRGB(x, y)) {
          return false;
        }
      }
    }

    return true;
  }

  @NotNull
  private static JLabel createLabel(@NotNull final BufferedImage image, long imageFileSize) {
    final int width = image.getWidth();
    final int height = image.getHeight();
    final ColorModel colorModel = image.getColorModel();
    final int i = colorModel.getPixelSize();
    return new JLabel(LangBundle.message("image.preview.label", width, height, i, StringUtil.formatFileSize(imageFileSize)));
  }

  private static boolean refresh(@NotNull VirtualFile file) throws IOException {
    Long loadedTimeStamp = file.getUserData(TIMESTAMP_KEY);
    SoftReference<BufferedImage> imageRef = file.getUserData(BUFFERED_IMAGE_REF_KEY);
    if (loadedTimeStamp == null || loadedTimeStamp < file.getTimeStamp() || SoftReference.dereference(imageRef) == null) {
      try {
        final byte[] content = file.contentsToByteArray();
        final BufferedImage image = readImageFromBytes(content);
        file.putUserData(BUFFERED_IMAGE_REF_KEY, new SoftReference<>(image));
        return true;
      }
      finally {
        // We perform loading no more needed
        file.putUserData(TIMESTAMP_KEY, System.currentTimeMillis());
      }
    }
    return false;
  }

  public static @NotNull BufferedImage readImageFromBytes(byte @NotNull [] content) throws IOException {
    try {
      return ImageUtil.toBufferedImage(SVGLoader.loadWithoutCache(content, JBUIScale.sysScale()));
    }
    catch (IOException ignored) {
    }

    InputStream inputStream = new ByteArrayInputStream(content, 0, content.length);
    try (ImageInputStream imageInputStream = ImageIO.createImageInputStream(inputStream)) {
      Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(imageInputStream);
      if (imageReaders.hasNext()) {
        ImageReader imageReader = imageReaders.next();
        try {
          ImageReadParam param = imageReader.getDefaultReadParam();
          imageReader.setInput(imageInputStream, true, true);
          int minIndex = imageReader.getMinIndex();
          return imageReader.read(minIndex, param);
        }
        catch (Exception e) {
          throw new IOException("Can't read image from given content", e);
        }
        finally {
          imageReader.dispose();
        }
      }
    }
    throw new IOException("Can't read image from given content");
  }

  public static JComponent getPreviewComponent(@Nullable final PsiElement parent) {
    if (parent == null) {
      return null;
    }
    final PsiReference[] references = parent.getReferences();
    for (final PsiReference reference : references) {
      final PsiElement fileItem = reference.resolve();
      if (fileItem instanceof PsiFileSystemItem) {
        final PsiFileSystemItem item = (PsiFileSystemItem)fileItem;
        if (!item.isDirectory()) {
          final VirtualFile file = item.getVirtualFile();
          if (file != null && supportedExtensions.contains(file.getExtension())) {
            try {
              refresh(file);
              SoftReference<BufferedImage> imageRef = file.getUserData(BUFFERED_IMAGE_REF_KEY);
              final BufferedImage image = SoftReference.dereference(imageRef);
              if (image != null) {
                return new ImagePreviewComponent(image, file.getLength());
              }
            }
            catch (IOException ignored) {
              // nothing
            }
          }
        }
      }
    }

    return null;
  }

  /**
   * This method doesn't use caching, so if you want to use it then you should consider implementing external cache.
   */
  public static ImagePreviewComponent getPreviewComponent(@NotNull final BufferedImage image, final long imageFileSize) {
    return new ImagePreviewComponent(image, imageFileSize);
  }

  private final class ImageComp extends JComponent {
    private final Dimension myPreferredSize;

    private ImageComp() {
      if (myImage.getWidth() > 300 || myImage.getHeight() > 300) {
        // will make image smaller
        final float factor = 300.0f / Math.max(myImage.getWidth(), myImage.getHeight());
        myPreferredSize = new Dimension((int)(myImage.getWidth() * factor), (int)(myImage.getHeight() * factor));
      }
      else {
        myPreferredSize = new Dimension(myImage.getWidth(), myImage.getHeight());
      }
    }

    @Override
    public void paint(final Graphics g) {
      super.paint(g);
      Rectangle r = getBounds();
      final int width = myImage.getWidth();
      final int height = myImage.getHeight();

      UIUtil.drawImage(g, myImage, new Rectangle(0, 0, Math.min(r.width, width), Math.min(r.height, height)), null, this);
    }

    @Override
    public Dimension getPreferredSize() {
      return myPreferredSize;
    }

    @Override
    public Dimension getMinimumSize() {
      return getPreferredSize();
    }

    @Override
    public Dimension getMaximumSize() {
      return getPreferredSize();
    }
  }
}


text:
// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkID=397704
// To debug code on page load in Ripple or on Android devices/emulators: launch your app, set breakpoints,
// and then run "window.location.reload()" in the JavaScript Console.
(function () {
    "use strict";

    document.addEventListener( 'deviceready', onDeviceReady.bind( this ), false );

    function onDeviceReady() {
        // Handle the Cordova pause and resume events
        document.addEventListener( 'pause', onPause.bind( this ), false );
        document.addEventListener( 'resume', onResume.bind( this ), false );

        console.log(navigator.geolocation);

        var onSuccess = function (position) {
            alert('Latitude: ' + position.coords.latitude + '\n' +
                  'Longitude: ' + position.coords.longitude + '\n' +
                  'Altitude: ' + position.coords.altitude + '\n' +
                  'Accuracy: ' + position.coords.accuracy + '\n' +
                  'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' +
                  'Heading: ' + position.coords.heading + '\n' +
                  'Speed: ' + position.coords.speed + '\n' +
                  'Timestamp: ' + position.timestamp + '\n');
        };

        // onError Callback receives a PositionError object
        //
        function onError(error) {
            alert('code: ' + error.code + '\n' +
                  'message: ' + error.message + '\n');
        }

        navigator.geolocation.getCurrentPosition(onSuccess, onError);
        // TODO: Cordova has been loaded. Perform any initialization that requires Cordova here.
    };

    function onPause() {
        // TODO: This application has been suspended. Save application state here.
    };

    function onResume() {
        // TODO: This application has been reactivated. Restore application state here.
    }
})();


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Capparis yunckeri Standl.

### Remarks
null


text:
 /*
  * Authors:
  *   Keith Whitwell <keith@tungstengraphics.com>
  */

#ifndef BRW_STATE_H
#define BRW_STATE_H

#include "brw_context.h"

static INLINE void
brw_add_validated_bo(struct brw_context *brw, drm_intel_bo *bo)
{
   assert(brw->state.validated_bo_count < ARRAY_SIZE(brw->state.validated_bos));

   if (bo != NULL) {
      drm_intel_bo_reference(bo);
      brw->state.validated_bos[brw->state.validated_bo_count++] = bo;
   }
};

extern const struct brw_tracked_state brw_blend_constant_color;
extern const struct brw_tracked_state brw_cc_unit;
extern const struct brw_tracked_state brw_check_fallback;
extern const struct brw_tracked_state brw_clip_prog;
extern const struct brw_tracked_state brw_clip_unit;
extern const struct brw_tracked_state brw_vs_constants;
extern const struct brw_tracked_state brw_wm_constants;
extern const struct brw_tracked_state brw_constant_buffer;
extern const struct brw_tracked_state brw_curbe_offsets;
extern const struct brw_tracked_state brw_invarient_state;
extern const struct brw_tracked_state brw_gs_prog;
extern const struct brw_tracked_state brw_gs_unit;
extern const struct brw_tracked_state brw_line_stipple;
extern const struct brw_tracked_state brw_aa_line_parameters;
extern const struct brw_tracked_state brw_pipelined_state_pointers;
extern const struct brw_tracked_state brw_binding_table_pointers;
extern const struct brw_tracked_state brw_depthbuffer;
extern const struct brw_tracked_state brw_polygon_stipple_offset;
extern const struct brw_tracked_state brw_polygon_stipple;
extern const struct brw_tracked_state brw_program_parameters;
extern const struct brw_tracked_state brw_recalculate_urb_fence;
extern const struct brw_tracked_state brw_sf_prog;
extern const struct brw_tracked_state brw_sf_unit;
extern const struct brw_tracked_state brw_sf_vp;
extern const struct brw_tracked_state brw_state_base_address;
extern const struct brw_tracked_state brw_urb_fence;
extern const struct brw_tracked_state brw_vertex_state;
extern const struct brw_tracked_state brw_vs_surfaces;
extern const struct brw_tracked_state brw_vs_prog;
extern const struct brw_tracked_state brw_vs_unit;
extern const struct brw_tracked_state brw_wm_input_sizes;
extern const struct brw_tracked_state brw_wm_prog;
extern const struct brw_tracked_state brw_wm_samplers;
extern const struct brw_tracked_state brw_wm_constant_surface;
extern const struct brw_tracked_state brw_wm_surfaces;
extern const struct brw_tracked_state brw_wm_binding_table;
extern const struct brw_tracked_state brw_wm_unit;

extern const struct brw_tracked_state brw_psp_urb_cbs;

extern const struct brw_tracked_state brw_pipe_control;

extern const struct brw_tracked_state brw_drawing_rect;
extern const struct brw_tracked_state brw_indices;
extern const struct brw_tracked_state brw_vertices;
extern const struct brw_tracked_state brw_index_buffer;
extern const struct brw_tracked_state gen6_binding_table_pointers;
extern const struct brw_tracked_state gen6_blend_state;
extern const struct brw_tracked_state gen6_cc_state_pointers;
extern const struct brw_tracked_state gen6_clip_state;
extern const struct brw_tracked_state gen6_clip_vp;
extern const struct brw_tracked_state gen6_color_calc_state;
extern const struct brw_tracked_state gen6_depth_stencil_state;
extern const struct brw_tracked_state gen6_gs_state;
extern const struct brw_tracked_state gen6_sampler_state;
extern const struct brw_tracked_state gen6_scissor_state;
extern const struct brw_tracked_state gen6_scissor_state_pointers;
extern const struct brw_tracked_state gen6_sf_state;
extern const struct brw_tracked_state gen6_sf_vp;
extern const struct brw_tracked_state gen6_urb;
extern const struct brw_tracked_state gen6_viewport_state;
extern const struct brw_tracked_state gen6_vs_state;
extern const struct brw_tracked_state gen6_wm_constants;
extern const struct brw_tracked_state gen6_wm_state;

/***********************************************************************
 * brw_state.c
 */
void brw_validate_state(struct brw_context *brw);
void brw_upload_state(struct brw_context *brw);
void brw_init_state(struct brw_context *brw);
void brw_destroy_state(struct brw_context *brw);
void brw_clear_validated_bos(struct brw_context *brw);

/***********************************************************************
 * brw_state_cache.c
 */
drm_intel_bo *brw_cache_data(struct brw_cache *cache,
		       enum brw_cache_id cache_id,
		       const void *data,
		       GLuint size);

drm_intel_bo *brw_upload_cache(struct brw_cache *cache,
			       enum brw_cache_id cache_id,
			       const void *key,
			       GLuint key_sz,
			       drm_intel_bo **reloc_bufs,
			       GLuint nr_reloc_bufs,
			       const void *data,
			       GLuint data_sz);

drm_intel_bo *brw_upload_cache_with_auxdata(struct brw_cache *cache,
					    enum brw_cache_id cache_id,
					    const void *key,
					    GLuint key_sz,
					    drm_intel_bo **reloc_bufs,
					    GLuint nr_reloc_bufs,
					    const void *data,
					    GLuint data_sz,
					    const void *aux,
					    GLuint aux_sz,
					    void *aux_return);

drm_intel_bo *brw_search_cache( struct brw_cache *cache,
			  enum brw_cache_id cache_id,
			  const void *key,
			  GLuint key_size,
			  drm_intel_bo **reloc_bufs,
			  GLuint nr_reloc_bufs,
			  void *aux_return);
void brw_state_cache_check_size( struct brw_context *brw );

void brw_init_caches( struct brw_context *brw );
void brw_destroy_caches( struct brw_context *brw );

/***********************************************************************
 * brw_state_batch.c
 */
#define BRW_BATCH_STRUCT(brw, s) intel_batchbuffer_data( brw->intel.batch, (s), sizeof(*(s)))
#define BRW_CACHED_BATCH_STRUCT(brw, s) brw_cached_batch_struct( brw, (s), sizeof(*(s)) )

GLboolean brw_cached_batch_struct( struct brw_context *brw,
				   const void *data,
				   GLuint sz );
void brw_destroy_batch_cache( struct brw_context *brw );
void brw_clear_batch_cache( struct brw_context *brw );
void *brw_state_batch(struct brw_context *brw,
		      int size,
		      int alignment,
		      drm_intel_bo **out_bo,
		      uint32_t *out_offset);

/* brw_wm_surface_state.c */
void brw_create_constant_surface(struct brw_context *brw,
				 drm_intel_bo *bo,
				 int width,
				 drm_intel_bo **out_bo,
				 uint32_t *out_offset);

#endif


text:
from .property import Property

class GraphElement(object):
    def __init__(self, **kwargs):
        self._graph = None
        self._id = None

        self._props = kwargs

    @classmethod
    def from_graph(cls, graph, element_id, props):
        elem = cls(**props)

        elem._graph = graph
        elem._id = element_id

        return elem

    def save(self):
        """:returns: True if successful, False otherwise"""
        if not self._graph:
            raise RuntimeError(
                'Can not save() element: it has no corresponding Graph')
        return self._graph.save_element(self.__class__, self._props, self._id)

    def __setattr__(self, key, value):
        # Check if the attribute is actually a property of the OGM type
        if (hasattr(type(self), key) and
            isinstance(getattr(type(self), key), Property)):
                self._props[key] = value
                return

        super(GraphElement, self).__setattr__(key, value)

    def __getattribute__(self, key):
        try:
            return super(GraphElement, self).__getattribute__('_props')[key]
        except:
            return super(GraphElement, self).__getattribute__(key)

    def __eq__(self, other):
        return type(self) is type(other) and \
               self._id == other._id and \
               self._props == other._props

    def __ne__(self, other):
        return not self.__eq__(other)

    def __format__(self, format_spec):
        """Quoted record id for specifying element as string argument."""
        return repr(self._id)


text:
sicp2014
========

Solutions to the Structure and Interpretation of Computer Programs (MIT Press, second edition, 1996)